[
  {
    "path": ".github/ISSUE_TEMPLATE/bug-report-or-feature-request.md",
    "content": "---\nname: Bug report or feature request\nabout: Create a report to help us improve\ntitle: ''\nlabels: docs\nassignees: ''\n\n---\n\n## Problem or new feature\n\nA clear and concise description of what the bug is, including links to the page where you have found it.\n\n## Suggestions\n\nIf applicable, suggest something towards the solution.\n"
  },
  {
    "path": ".github/pull_request_template.md",
    "content": "## The problem\n\n\n## Solution provided\n\n<!--\n\n    The template below contains optional suggestions. Simply omit it\n    if you think it does not apply to this PR.\n\n    Please state clearly in \"The problem\" what you are addressing with this\n    pull request, referencing the issue(s) where it is described.\n\n    In \"Solution provided\", tell us what you have done to address the\n    problem.\n\n-->\n"
  },
  {
    "path": ".github/workflows/test.yml",
    "content": "name: test\non:\n  push:\n    branches: [ main ]\n    paths:\n      - '**'\n  pull_request:\n    branches: [ main ]\n    paths:\n      - '**'\njobs:\n  test:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v3\n        with:\n          fetch-depth: ${{ github.event_name == 'pull_request' && 2 || 0 }}\n      - name: Get changed files\n        id: changed-files\n        run: |\n            if ${{ github.event_name == 'pull_request' }}; then\n                echo \"changed_files=$(git diff --name-only -r HEAD^1 HEAD | xargs)\" >> $GITHUB_OUTPUT\n            else\n                echo \"changed_files=$(git diff --name-only ${{ github.event.before }} ${{ github.event.after }} | xargs)\" >> $GITHUB_OUTPUT\n            fi\n      - name: Run tests\n        run: ./util/github-action-test.sh t\n        env:\n          TEST_IMAGE: docker.io/coke/rakudo-docs-test\n          TEST_FILES: ${{ steps.changed-files.outputs.changed_files }}\n"
  },
  {
    "path": ".gitignore",
    "content": "# Precompilation folders\n.precomp/\n.pod-precomp\n.pod-cache\n\n# Generated files for testing\nt/pws/aspell.pws\nretest\n\n# Cached file for building pages\nutil/Grammar.nqp\n\n# IDE\n*.iml\n\n# website clone for testing\ndoc-website\n"
  },
  {
    "path": "Build.rakumod",
    "content": "class Build {\n    BEGIN {\n        note q:to/END/;\n            This repository is not intended to be installed!\n            View the latest HTML version at https://docs.raku.org/\n            Command line viewer at https://github.com/raku/rakudoc\n        END\n        die;\n    }\n}\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing\n\nYour patches to `Raku/doc` are very welcome, and if you want to\nhelp,\n[please read this guide](https://github.com/Raku/doc/wiki) as\nwell as the detailed instructions below.\n\nThis document describes how to get started and helps to provide documentation\nthat adheres to the common style and formatting guidelines.\n\nYour contributions here will be credited in the next Rakudo release\nannouncement. Your name from the commit log will be used. If you'd like to be\ncredited under a different name, please add it to the local [CREDITS](CREDITS)\nfile (or ask someone to do it for you until you have commit privileges).\n\nIf you have any questions regarding contributing to this project, please ask\nin the [#raku IRC channel](https://raku.org/community/irc).\n\n# TABLE OF CONTENTS\n- [General principles](#general-principles)\n- [Writing code examples](#writing-code-examples)\n- [Indexing content](#indexing-content)\n- [Adding a new Language document](#adding-a-new-language-document)\n- [Documenting types](#documenting-types)\n- [Writing and Testing Examples](#writing-and-testing-examples)\n- [Debug mode](#debug-mode)\n    - [Invisible index anchors](#invisible-index-anchors)\n    - [Viewport size](#viewport-size)\n    - [Broken links](#broken-links)\n    - [Heading numbering](#heading-numbering)\n- [Reporting bugs](#reporting-bugs)\n- [Contributing pull requests](#contributing-pull-requests)\n- [Dependency installation](#dependency-installation)\n    - [Rakudo](#rakudo)\n    - [Zef](#zef)\n\n## General principles\n\n* Please use the present tense unless writing about history or upcoming events or planned features\n* Prefer [active voice](https://en.wikipedia.org/wiki/Active_voice) to the [passive voice](https://en.wikipedia.org/Passive_voice#In_English) with \"by\": \"this is used by crafty programmers\" → \"crafty programmers use this\"\n* Link to external resources (like Wikipedia) for topics that are not\n  directly related to Raku (like the math that our routines implement).\n* Duplicate small pieces of information rather than rely on linking.\n* Be explicit about routine signatures. If a method accepts an `*%args`,\n  but treats some of them specially, list them separately.\n* Check out [the styleguide](writing-docs/STYLEGUIDE.md) for further guidance.\n\n## Documenting versions\n\n* If you are adding a recently introduced feature, please indicate in a note\n  which version it was introduced in.\n* If you change an example to use the new feature, leave the old\n  example if it's still working, at least while it's not obsolete, for people\n  who have not upgraded yet, clarifying in the text around it the versions it\n  will run with.\n\n## Writing Code Examples\n\nSee [EXAMPLES.md](writing-docs/EXAMPLES.md) for detailed information on the options\navailable when writing code examples in the documentation.\n\n## Indexing content\n\nSee [INDEXING.md](writing-docs/INDEXING.md) for detailed information on how\nindexing of terms and locations in the documentation works.\n\n## Adding a new Language document\n\nWe suggest you discuss proposing a new Language document on the #raku\nchannel and/or the [issues for this repository](https://github.com/Raku/doc/issues)\nbefore you proceed further. After you get consensus on a title, subtitle,\nsection, and filename, you can add the document by following these steps:\n\n+ create a **filename.rakudoc** file in the **doc/Language** directory and\n  ensure it adheres to the conventions in\n  [CREATING-NEW-DOCS.md](writing-docs/CREATING-NEW-DOCS.md).\n\n## Documenting types\n\nThe Pod6 documentation of types is located in the `doc/Type` directory and\nsubdirectories of this repository. For example the Pod6 file of `X::Bind::Slice`\nlives in `doc/Type/X/Bind/Slice.pod6`.\n\nTo start contributing, fork and checkout the repository, find the document\nyou want to improve, commit your changes, and create a pull request. Should\nquestions come up in the process feel free to ask in\n[#raku IRC channel](https://raku.org/community/irc).\n\nIf the documentation for a type does not exist, create the skeleton of the doc\nwith the helper tool `util/new-type.raku`. Say you want to create `MyFunnyRole`:\n\n    $ raku util/new-type.raku --kind=role MyFunnyRole\n\nFill the documentation file `doc/Type/MyFunnyRole.rakudoc` like this:\n\n```raku\n=TITLE role MyFunnyRole\n\n=SUBTITLE Sentence or half-sentence about what it does\n\n    role MyFunnyRole does OtherRole is SuperClass { ... }\n\nLonger description here about what this type is, and\nhow you can use it.\n\n    # usage example goes here\n\n=head1 Methods\n\n=head2 method do-it\n\n    method do-it(Int $how-often --> Nil:D)\n\nMethod description here\n\n    MyFunnyRole.do-it(2);   # OUTPUT: «example output␤»\n```\n\nWhen documenting a pair of a sub and a method with the same functionality, the\nheading should be `=head2 routine do-it`, and the next thing should be two or\nmore lines with the signatures. Other allowed words instead of `method` are\n`sub`, `trait`, `infix`, `prefix`, `postfix`, `circumfix`, `postcircumfix`,\n`term`. If you wish to hide a heading from any index, prefix it with the empty\ncomment `Z<>`.\n\nWhen providing a code example result or output, use this style:\n\n```raku\n# For the result of an expression.\n1 + 2;     # RESULT: «3»\n# For the output.\nsay 1 + 3; # OUTPUT: «3␤»\n# For the explanatory comment\ndo-work;   # We call do-work sub\n```\n\n## Running tests\n\nAny contributions should pass the `make test` target. This insures basic\nintegrity of the documentation, and is run automatically by a corresponding\ntravis build. Even edits made via the GitHub editor should pass this test.\n\nThe repo should also pass `make xtest` most of the time - this includes\ntests about whitespace and spelling that might be difficult to get right\non an initial commit, and shouldn't be considered to break the build. However,\nif you're contributing a patch or pull request, this must pass.\n\nIf you have local modifications and want to insure they pass xtest before\ncommitting, you can use this command to test only modified files:\n\n    TEST_FILES=`git status --porcelain --untracked-files=no | awk '{print $2}'` make xtest\n\n## Writing and Testing Examples\n\nSee [Writing and Testing Examples](writing-docs/EXAMPLES.md)\n\n## Debug mode\n\nOn the right side of the footer you can find [Debug: off]. Click it and reload\nthe page to activate debug mode. The state of debug mode will be remembered by\n`window.sessionStorage` and will not survive a browser restart or opening the\ndocs in a new tab.\n\n### Broken links\n\nTo check for broken links use debug mode. Any spotted broken link will be\nlisted under the search input. Please note that some external links may not get\nchecked depending on your browser settings.\n\n### Heading numbering\n\nPlease check if the headings you add are well structured. You can use [debug mode](#debug-mode)\nto display heading numbers.\n\n## Reporting bugs\n\nReport issues with the content on [github](https://github.com/Raku/doc/issues).\nThis includes missing or incorrect documentation, as well as information about\nversioning (e.g., \"method foo\" only available in raku v6.d).\n\nFor issues with the website functionality (as opposed to the content), for\nexamples issues with search,\nplease report on [doc-website](https://github.com/Raku/doc-website/issues).\n\n## Contributing pull requests\n\nIf you would like to contribute documentation or other bug fixes, please use\n[GitHub's pull requests (PRs)](https://github.com/Raku/doc/pulls). For a complete\nrecipe for a new PR contributor, check [this PR guide](https://github.com/tbrowder/tidbits/blob/master/Contributing-PRs.md).\n\n### Dependency installation\n\n#### Raku\n\nSee [rakudo.org](https://rakudo.org/downloads) for Raku installation information.\n\n#### Zef\n\nTo install any prerequisites for this module, use:\n\n    $ zef install --deps-only .\n\nSee [zef](https://github.com/ugexe/zef) for any questions on zef.\n\n### Test the documentation\n\nThe [Makefile] has a lot of targets to help with testing the documentation\nUse this command to see them:\n\n    $ make help\n"
  },
  {
    "path": "CREDITS",
    "content": "=pod\n\n    Following in the steps of other open source projects that\n    eventually take over the world, here is the partial list\n    of people who have contributed to this documentation.\n    It is sorted by name and formatted to allow easy\n    grepping and beautification by scripts.\n    The fields are: name (N), email (E), web-address (W),\n    description (D), GitHub username (U) and snail-mail\n    address (S).\n\n        Thanks,\n\n        The Raku/doc Team\n        PS: Yes, this looks remarkably like the Linux CREDITS format\n        PPS: This file is encoded in UTF-8\n\n----------\n\nN: ab5tract\nE: john.haltiwanger@gmail.com\n\nN: abcxyzp\nE: abcxyz@cpan.org\n\nN: Adrian Kreher\nE: avuserow@gmail.com\n\nN: Ahmad M. Zawawi\nE: ahmad.zawawi@gmail.com\n\nN: Akim Demaille\nE: akim@lrde.epita.fr\n\nN: Alex Chen\nU: TisonKun\nU: W4anD0eR96\nE: wander4096@gmail.com\n\nN: Alexander Moquin\nE: alexmoquin@gmail.com\n\nN: andreoss\nE: andreoss@sdf.org\n\nN: Andrew Egeler\nE: andrew@egeler.us\n\nN: Ben Noordhuis\nE: info@bnoordhuis.nl\n\nN: Ben Tyler\nE: benjamin.tyler@gmail.com\n\nN: Brent Laabs\nE: bslaabs@gmail.com\n\nN: Brian Duggan\nU: bduggan\nE: bduggan@matatu.org\n\nN: Brock Wilcox\nE: awwaiid@thelackthereof.org\n\nN: Bruce Gray\nE: bruce.gray@acm.org\n\nN: Calvin Schwenzfeier\nE: cschwenz@users.noreply.github.com\n\nN: Carl Hayter\nE: hayter@usc.edu\n\nN: Carl Mäsak\nE: cmasak@gmail.com\n\nN: Carlin\nE: carbin@users.noreply.github.com\n\nN: Chloé Kekoa\nE: rightfold+ck@gmail.com\nW: foldr.nl\nU: chloekek\n\nN: Christopher Bottoms\nE: molecules@users.noreply.github.com\n\nN: Cole Keirsey\nE: ckeirsey2@gmail.com\n\nN: cygx\nE: cygx@users.noreply.github.com\n\nN: Cédric Vincent\nE: cedric@reproducible.io\n\nN: Daniel Green\nU: MasterDuke17\nE: ddgreen@gmail.com\n\nN: David Farrell\nE: davidnmfarrell@gmail.com\n\nN: David H. Adler\nE: dha@pobox.com\n\nN: David M. Cawthon\nE: dmc00@fastmail.com\n\nN: David Simon Schultz\nU: schultzdavid\nE: dss@noreply.codeberg.org\n\nN: Dmitriy Olshevskiy\nE: olshevskiy87@bk.ru\n\nN: Edwin Steiner\nE: edwin.steiner@gmx.net\n\nN: Elizabeth Mattijsen\nU: lizmat\nE: liz@wenzperl.nl\n\nN: Eric Forste\nU: arkiuat\nE: arkiuat@mm.st\n\nN: ennio\nE: scriplit@yahoo.com\n\nN: Felix Herrmann\nE: felix@herrmann-koenigsberg.de\n\nN: Florian Helmberger\nE: fh@25th-floor.com\n\nN: Gabor Szabo\nE: gabor@szabgab.com\n\nN: Geoffrey Broadwell\nE: geoff@broadwell.org\n\nN: GlitchMr\nE: glitchmr@myopera.com\n\nN: Graham Todd\nE: info@opendevelopment.net\n\nN: Heiko Jansen\nE: heiko_jansen@web.de\n\nN: Ilmari Vacklin\nE: ilmari.vacklin@reaktor.fi\n\nN: isBEKaml\nE: nastavs@gmail.com\n\nN: Jeremy Studer\nE: studerj1.mail@gmail.com\n\nN: Jimmy Zhuo\nE: zhuomingliang@yahoo.com.cn\n\nN: JJ Merelo\nN: Juan Julián Merelo Guervós\nE: jjmerelo@gmail.com\nU: JJ\n\nN: Joelle Maslak\nE: jmaslak@antelope.net\nU: jmaslak\n\nN: John Gabriele\nE: jgabriele@fastmail.fm\n\nN: Joji Antony\nE: simula67@gmail.com\n\nN: Jonathan Scott Duff\nE: duff@pobox.com\n\nN: Jonathan Stowe\nE: jns+git@gellyfish.co.uk\n\nN: Jonathan Worthington\nE: jnthn@jnthn.net\n\nN: Justin DeVuyst\nE: justin@devuyst.com\n\nN: Kamil Kułaga\nE: teodozjan@gmail.com\n\nN: Karl Yerkes\nE: karl.yerkes@gmail.com\n\nN: Klaus Brüssel\nE: trixium@web.de\n\nN: Konrad Borowski\nE: glitchmr@myopera.com\n\nN: LLFourn\nE: LLFourn@users.noreply.github.com\n\nN: Lloyd Fournier\nE: LLFourn@users.noreply.github.com\n\nN: Luca Ferrari\nE: fluca1978@gmail.com\nW: https://fluca1978.github.io\nU: fluca1978\n\nN: lue\nE: rnddim@gmail.com\n\nN: lumimies\nE: lumimies@gmail.com\n\nN: Marcel Timmerman\nE: mt1957@gmail.com\n\nN: Matthew\nE: rnddim@gmail.com\n\nN: Matthias Krull\nE: m.krull@uninets.eu\n\nN: mdinger\nE: mdinger.bugzilla@gmail.com\n\nN: Mike Francis\nE: ungrim97@gmail.com\n\nN: Moray Jones\nE: github@mrjones.co.uk\n\nN: Moritz Lenz\nE: moritz@faui2k3.org\nU: moritz\nU: moritz_\nD: Initial p6doc development, documentation\n\nN: Mouq\nE: alexmoquin@gmail.com\n\nN: muraiki\nE: muraiki@users.noreply.github.com\n\nN: Nami-Doc\nE: vendethiel@hotmail.fr\n\nN: Nathan Brown\nE: nbrown04@gmail.com\n\nN: Nick Logan\nE: nlogan@gmail.com\n\nN: niner\nE: nine@detonation.org\n\nN: Noel Maddy\nE: zhtwnpanta@gmail.com\n\nN: Nova Patch\nE: patch@cpan.org\n\nN: Patrick R. Michaud\nU: pmichaud\nD: Perl 6 (Rakudo Perl) lead developer\nE: pmichaud@pobox.com\n\nN: Paul Cochrane\nE: paul@liekut.de\n\nN: Pawel Pabian\nE: bbkr@post.pl\n\nN: Philippe Bruhat (BooK)\nE: book@cpan.org\n\nN: Prog Rammer\nE: prammer1@gmail.com\n\nN: raiph\nE: ralphdjmellor@gmail.com\n\nN: raydiak\nE: raydiak@cyberuniverses.com\n\nN: Ricardo Signes\nE: rjbs@users.noreply.github.com\n\nN: Rob Hoelz\nE: rob@hoelz.ro\n\nN: Ronald Schmidt\nE: ronaldxs@software-path.com\n\nN: ronaldxs\nE: ronaldxs@software-path.com\n\nN: Salve J. Nilsen\nE: sjn@cpan.org\n\nN: Sam S\nE: smls75@gmail.com\n\nN: sergot\nE: filip@sergot.pl\n\nN: Sgeo\nE: sgeoster@gmail.com\n\nN: ShimmerFairy\nE: rnddim@gmail.com\n\nN: Sizhe Zhao\nE: prc.zhao@outlook.com\nU: Prince213\n\nN: skids\nE: bri@abrij.org\n\nN: smls\nE: smls75@gmail.com\n\nN: Stefan Seifert\nE: nine@detonation.org\n\nN: Sterling Hanenkamp\nE: sterling@hanenkamp.com\n\nN: Steve Mynott\nE: steve.mynott@gmail.com\n\nN: Stéphane Payrard\nE: cognominal@gmail.com\n\nN: Tadeusz Sośnierz\nE: tadzikes@gmail.com\n\nN: Tim Nelson\nE: wayland@wayland.id.au\n\nN: Tim Smith\nE: tim.dolores@gmail.com\n\nN: timo\nE: timonator@perpetuum-immobile.de\n\nN: Timo Paulssen\nE: timonator@perpetuum-immobile.de\n\nN: TimToady\nE: larry@wall.org\n\nN: Tobias Leich\nE: email@froggs.de\n\nN: Tokuhiro Matsuno\nE: tokuhirom@gmail.com\n\nN: Tom Browder\nE: tom.browder@gmail.com\nU: tbrowder\n\nN: Trey Harris\nE: treyharris@gmail.com\n\nN: Claudio Ramirez\nE: pub.claudio@gmail.com\n\nN: ugexe\nE: nlogan@gmail.com\n\nN: usev6\nE: use_v6@aglaz.de\n\nN: ven\nE: vendethiel@hotmail.fr\n\nN: VZ\nE: vz-github@zeitlins.org\n\nN: Wenzel P. P. Peppmeyer\nU: gfldex\nE: wenzel.peppmeyer@gmx.de\n\nN: Will Coleda\nN: Coke\nE: will@coleda.com\n\nN: Xtreak\nE: tirkarthi@users.noreply.github.com\n\nN: Zoffix Znet\nE: cpan@zoffix.com\n\n=cut\n"
  },
  {
    "path": "LICENSE",
    "content": "\t\t       The Artistic License 2.0\n\n\t    Copyright (c) 2000-2006, The Perl Foundation.\n\n     Everyone is permitted to copy and distribute verbatim copies\n      of this license document, but changing it is not allowed.\n\nPreamble\n\nThis license establishes the terms under which a given free software\nPackage may be copied, modified, distributed, and/or redistributed.\nThe intent is that the Copyright Holder maintains some artistic\ncontrol over the development of that Package while still keeping the\nPackage available as open source and free software.\n\nYou are always permitted to make arrangements wholly outside of this\nlicense directly with the Copyright Holder of a given Package.  If the\nterms of this license do not permit the full use that you propose to\nmake of the Package, you should contact the Copyright Holder and seek\na different licensing arrangement.\n\nDefinitions\n\n    \"Copyright Holder\" means the individual(s) or organization(s)\n    named in the copyright notice for the entire Package.\n\n    \"Contributor\" means any party that has contributed code or other\n    material to the Package, in accordance with the Copyright Holder's\n    procedures.\n\n    \"You\" and \"your\" means any person who would like to copy,\n    distribute, or modify the Package.\n\n    \"Package\" means the collection of files distributed by the\n    Copyright Holder, and derivatives of that collection and/or of\n    those files. A given Package may consist of either the Standard\n    Version, or a Modified Version.\n\n    \"Distribute\" means providing a copy of the Package or making it\n    accessible to anyone else, or in the case of a company or\n    organization, to others outside of your company or organization.\n\n    \"Distributor Fee\" means any fee that you charge for Distributing\n    this Package or providing support for this Package to another\n    party.  It does not mean licensing fees.\n\n    \"Standard Version\" refers to the Package if it has not been\n    modified, or has been modified only in ways explicitly requested\n    by the Copyright Holder.\n\n    \"Modified Version\" means the Package, if it has been changed, and\n    such changes were not explicitly requested by the Copyright\n    Holder.\n\n    \"Original License\" means this Artistic License as Distributed with\n    the Standard Version of the Package, in its current version or as\n    it may be modified by The Perl Foundation in the future.\n\n    \"Source\" form means the source code, documentation source, and\n    configuration files for the Package.\n\n    \"Compiled\" form means the compiled bytecode, object code, binary,\n    or any other form resulting from mechanical transformation or\n    translation of the Source form.\n\n\nPermission for Use and Modification Without Distribution\n\n(1)  You are permitted to use the Standard Version and create and use\nModified Versions for any purpose without restriction, provided that\nyou do not Distribute the Modified Version.\n\n\nPermissions for Redistribution of the Standard Version\n\n(2)  You may Distribute verbatim copies of the Source form of the\nStandard Version of this Package in any medium without restriction,\neither gratis or for a Distributor Fee, provided that you duplicate\nall of the original copyright notices and associated disclaimers.  At\nyour discretion, such verbatim copies may or may not include a\nCompiled form of the Package.\n\n(3)  You may apply any bug fixes, portability changes, and other\nmodifications made available from the Copyright Holder.  The resulting\nPackage will still be considered the Standard Version, and as such\nwill be subject to the Original License.\n\n\nDistribution of Modified Versions of the Package as Source\n\n(4)  You may Distribute your Modified Version as Source (either gratis\nor for a Distributor Fee, and with or without a Compiled form of the\nModified Version) provided that you clearly document how it differs\nfrom the Standard Version, including, but not limited to, documenting\nany non-standard features, executables, or modules, and provided that\nyou do at least ONE of the following:\n\n    (a)  make the Modified Version available to the Copyright Holder\n    of the Standard Version, under the Original License, so that the\n    Copyright Holder may include your modifications in the Standard\n    Version.\n\n    (b)  ensure that installation of your Modified Version does not\n    prevent the user installing or running the Standard Version. In\n    addition, the Modified Version must bear a name that is different\n    from the name of the Standard Version.\n\n    (c)  allow anyone who receives a copy of the Modified Version to\n    make the Source form of the Modified Version available to others\n    under\n\n\t(i)  the Original License or\n\n\t(ii)  a license that permits the licensee to freely copy,\n\tmodify and redistribute the Modified Version using the same\n\tlicensing terms that apply to the copy that the licensee\n\treceived, and requires that the Source form of the Modified\n\tVersion, and of any works derived from it, be made freely\n\tavailable in that license fees are prohibited but Distributor\n\tFees are allowed.\n\n\nDistribution of Compiled Forms of the Standard Version\nor Modified Versions without the Source\n\n(5)  You may Distribute Compiled forms of the Standard Version without\nthe Source, provided that you include complete instructions on how to\nget the Source of the Standard Version.  Such instructions must be\nvalid at the time of your distribution.  If these instructions, at any\ntime while you are carrying out such distribution, become invalid, you\nmust provide new instructions on demand or cease further distribution.\nIf you provide valid instructions or cease distribution within thirty\ndays after you become aware that the instructions are invalid, then\nyou do not forfeit any of your rights under this license.\n\n(6)  You may Distribute a Modified Version in Compiled form without\nthe Source, provided that you comply with Section 4 with respect to\nthe Source of the Modified Version.\n\n\nAggregating or Linking the Package\n\n(7)  You may aggregate the Package (either the Standard Version or\nModified Version) with other packages and Distribute the resulting\naggregation provided that you do not charge a licensing fee for the\nPackage.  Distributor Fees are permitted, and licensing fees for other\ncomponents in the aggregation are permitted. The terms of this license\napply to the use and Distribution of the Standard or Modified Versions\nas included in the aggregation.\n\n(8) You are permitted to link Modified and Standard Versions with\nother works, to embed the Package in a larger work of your own, or to\nbuild stand-alone binary or bytecode versions of applications that\ninclude the Package, and Distribute the result without restriction,\nprovided the result does not expose a direct interface to the Package.\n\n\nItems That are Not Considered Part of a Modified Version\n\n(9) Works (including, but not limited to, modules and scripts) that\nmerely extend or make use of the Package, do not, by themselves, cause\nthe Package to be a Modified Version.  In addition, such works are not\nconsidered parts of the Package itself, and are not subject to the\nterms of this license.\n\n\nGeneral Provisions\n\n(10)  Any use, modification, and distribution of the Standard or\nModified Versions is governed by this Artistic License. By using,\nmodifying or distributing the Package, you accept this license. Do not\nuse, modify, or distribute the Package, if you do not accept this\nlicense.\n\n(11)  If your Modified Version has been derived from a Modified\nVersion made by someone other than you, you are nevertheless required\nto ensure that your Modified Version complies with the requirements of\nthis license.\n\n(12)  This license does not grant you the right to use any trademark,\nservice mark, tradename, or logo of the Copyright Holder.\n\n(13)  This license includes the non-exclusive, worldwide,\nfree-of-charge patent license to make, have made, use, offer to sell,\nsell, import and otherwise transfer the Package with respect to any\npatent claims licensable by the Copyright Holder that are necessarily\ninfringed by the Package. If you institute patent litigation\n(including a cross-claim or counterclaim) against any party alleging\nthat the Package constitutes direct or contributory patent\ninfringement, then this Artistic License to you shall terminate on the\ndate that such litigation is filed.\n\n(14)  Disclaimer of Warranty:\nTHE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS \"AS\nIS\" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED\nWARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR\nNON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL\nLAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL\nBE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL\nDAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "META6.json",
    "content": "{\n  \"name\": \"Raku doc\",\n  \"description\": \"Raku™ documentation\",\n  \"version\": \"2.0\",\n  \"raku\": \"6.*\",\n  \"authors\": [\n    \"raku\"\n  ],\n  \"auth\": \"raku\",\n  \"test-depends\": [\n    \"Cro::HTTP::Client\",\n    \"File::Temp\",\n    \"Test::META\",\n    \"Doc::TypeGraph\",\n    \"RakuDoc::Test::Files:ver<0.3+>\"\n  ],\n  \"build-depends\": [],\n  \"provides\": {\n      \"Pod::Cache\": \"lib/Pod/Cache.rakumod\",\n      \"Pod::Convenience\": \"lib/Pod/Convenience.rakumod\"\n  },\n  \"support\": {\n    \"source\": \"git://github.com/Raku/doc.git\"\n  },\n  \"license\": \"Artistic-2.0\",\n  \"tags\": [\n    \"raku\",\n    \"pod6\",\n    \"rakudoc\",\n    \"documentation\",\n    \"reference\",\n    \"perl6\"\n  ],\n  \"source-url\": \"git://github.com/Raku/doc.git\",\n  \"meta6\": \"0\"\n}\n"
  },
  {
    "path": "Makefile",
    "content": ".PHONY: test xtest push help\n\nhelp:\n\t@echo \"Usage: make [test|xtest|push]\"\n\t@echo \"\"\n\t@echo \"Options:\"\n\t@echo \"   test:             run the basic test suite\"\n\t@echo \"  xtest:             run all tests\"\n\t@echo \"   push:             run the basic test suite and git push\"\n\n# Common tests - also run by CI\ntest:\n\tif [ \"${TEST_JOBS}\" != \"\" ]; then prove --ext=rakutest -j ${TEST_JOBS} -e raku t; else prove --ext=rakutest -e raku t; fi\n\n# Extended tests - should be run by authors before committing\nxtest:\n\tif [ \"${TEST_JOBS}\" != \"\" ]; then prove --ext=rakutest -j ${TEST_JOBS} -e raku t xt; else prove --ext=rakutest -e raku t xt; fi\n\npush: test\n\tgit pull --rebase && git push\n"
  },
  {
    "path": "README.md",
    "content": "# Official Documentation of Raku™\n\n[![artistic](https://img.shields.io/badge/license-Artistic%202.0-blue.svg?style=flat)](https://opensource.org/licenses/Artistic-2.0)\n[![test](https://github.com/Raku/doc/actions/workflows/test.yml/badge.svg)](https://github.com/Raku/doc/actions/workflows/test.yml)\n\nAn HTML version of this documentation can be found\nat [https://docs.raku.org/](https://docs.raku.org/).\nThat site is updated from the main branch here\nfrequently (but not continuously).\n\nThis is currently the recommended way to consume the documentation. The tooling\nto build and run this site is [available on github](https://github.com/Raku/doc-website).\n\nThis repository is not intended to be installed as a module. When running tests or\nscripts locally, you may need to set ``RAKULIB=.``\n\n## README in other languages\n\n  [日本語](resources/i18n/jp/README.jp.md)\n| [普通话](resources/i18n/zh/README.zh.md)\n| [Deutsch](resources/i18n/de/README.de.md)\n| [español](resources/i18n/es/README.es.md)\n| [français](resources/i18n/fr/README.fr.md)\n| [italiano](resources/i18n/it/README.it.md)\n| [nederlands](resources/i18n/nl/README.nl.md)\n| [Português](resources/i18n/pt/README.pt.md)\n\n## Help Wanted!\n\n[Interested in contributing?](writing-docs/README.md)\n\n## Why aren't the docs embedded in the compiler source?\n\n  1. This documentation is intended to be universal with\n     respect to the specification, and not tied to any specific\n     implementation.\n  2. Implementations' handling of embedded Pod is still\n     a bit uneven; this avoids potential runtime impacts.\n  3. This separate repo in the Raku Github account invites\n     more potential contributors and editors.\n\n## rakudoc\n\nThere is a [CLI](https://github.com/Raku/rakudoc) for viewing Raku documentation.\n\n## Vision\n\n> I want p6doc and docs.raku.org to become the No. 1 resource to consult\n> when you want to know something about a Raku feature, be it from the\n> language, or built-in types and routines. I want it to be useful to every\n> Raku programmer.\n>\n>    -- moritz\n\n# LICENSE\n\nThe documentation and code in this repository is available under the Artistic License 2.0\nas published by [The Perl & Raku Foundation (TPRF)](https://rakufoundation.org).\nSee the [LICENSE](LICENSE) file for the full text.\n\nThis repository may also contain examples authored by third parties that may be licensed under a different license. Such\nfiles indicate the copyright and license terms at the top of the file. Currently these include:\n\n* Examples from Stack Overflow; [MIT License](http://creativecommons.org/licenses/MIT) ([ref #1](http://stackoverflow.com/a/43669837/215487) for [1f7cc4e](https://github.com/Raku/doc/commit/1f7cc4efa0da38b5a9bf544c9b13cc335f87f7f6))\n"
  },
  {
    "path": "doc/Language/101-basics.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"beginning\")\n\n=TITLE  Raku by example 101\n\n=SUBTITLE A basic introductory example of a Raku program\n\nSuppose that you host a table tennis tournament. The referees tell you\nthe results of each game in the format C<Player1 Player2 | 3:2>, which\nmeans that C<Player1> won against C<Player2> by 3 to 2 sets. You need a\nscript that sums up how many matches and sets each player has won to\ndetermine the overall winner.\n\nThe input data (stored in a file called C<scores.txt>) looks like this:\n\n=for code :lang<data>\nBeth Ana Charlie Dave\nAna Dave | 3:0\nCharlie Beth | 3:1\nAna Beth | 2:3\nDave Charlie | 3:0\nAna Charlie | 3:1\nBeth Dave | 0:3\n\nThe first line is the list of players. Every subsequent line records a result\nof a match.\n\nHere's one way to solve that problem in Raku:\n\n=begin code :solo\nuse v6;\n\n# start by printing out the header.\nsay \"Tournament Results:\\n\";\n\nmy $file  = open 'scores.txt'; # get filehandle and...\nmy @names = $file.get.words;   # ... get players.\n\nmy %matches;\nmy %sets;\n\nfor $file.lines -> $line {\n    next unless $line; # ignore any empty lines\n\n    my ($pairing, $result) = $line.split(' | ');\n    my ($p1, $p2)          = $pairing.words;\n    my ($r1, $r2)          = $result.split(':');\n\n    %sets{$p1} += $r1;\n    %sets{$p2} += $r2;\n\n    if $r1 > $r2 {\n        %matches{$p1}++;\n    } else {\n        %matches{$p2}++;\n    }\n}\n\nmy @sorted = @names.sort({ %sets{$_} }).sort({ %matches{$_} }).reverse;\n\nfor @sorted -> $n {\n    my $match-noun = %matches{$n} == 1 ?? 'match' !! 'matches';\n    my $set-noun   = %sets{$n} == 1 ?? 'set' !! 'sets';\n    say \"$n has won %matches{$n} $match-noun and %sets{$n} $set-noun\";\n}\n=end code\n\nThis produces the output:\n\n=begin code :lang<text>\nTournament Results:\n\nAna has won 2 matches and 8 sets\nDave has won 2 matches and 6 sets\nCharlie has won 1 match and 4 sets\nBeth has won 1 match and 4 sets\n=end code\n\n=head1 Pragma X<C<v6>|Tutorial,v6 (Basics)>\n\n=begin code :solo\nuse v6;\n=end code\n\nEvery Raku program should begin with a line similar to C<use v6;>. This line\ntells the compiler which version of Raku the program expects. For instance,\n6.c is an example of a Raku version. Should you accidentally run the file\nwith Perl, you'll get a helpful error message.\n\n=head1 X<Statements|Tutorial,statement (Basics)>\n\n=begin code\n# start by printing out the header.\nsay \"Tournament Results:\\n\";\n=end code\n\nA Raku program consists of zero or more statements. A I<statement> ends with\na semicolon or a curly brace at the end of a line.\n\nIn Raku, single line comments start with a single hash character C<#> and\nextend until the end of the line. Raku also supports\nL<multi-line/embedded comments|/language/syntax#Multi-line_/_embedded_comments>.\nThe compiler doesn't evaluate comments as program text and they're only intended\nfor human readers.\n\n=head1 X<Lexical scope|Tutorial,my (Basics)> and X<block|Tutorial,block (Basics)>\n\n=begin code\nmy $file = open 'scores.txt';\n=end code\n\nC<my> declares a lexical variable, which are visible only in the current block\nfrom the point of declaration to the end of the block. If there's no enclosing\nblock, it's visible throughout the remainder of the file (which would\neffectively be the enclosing block). A block is any part of the code enclosed\nbetween curly braces C<{ }>.\n\n=head2 X<Sigils|Tutorial,sigils (Basics)> and X<identifiers|Tutorial,identifiers (Basics)>\n\nA variable name begins with a I<sigil>, which is a non-alpha-numeric\nsymbol such as C<$>, C<@>, C<%>, or C<&> E<mdash> or occasionally the double\ncolon C<::>. Sigils indicate the structural interface for the variable,\nsuch as whether it should be treated as a single value, a compound value,\na subroutine, etc. After the sigil comes an I<identifier>, which may\nconsist of letters, digits and the underscore. Between letters you can\nalso use a dash C<-> or an apostrophe C<'>, so C<isn't> and\nC<double-click> are valid identifiers.\n\n=head2 X<Scalar|Tutorial,scalar (Basics)>\n\nSigils indicate the default access method for a variable. Variables\nwith the C<@> sigil are accessed positionally; variables with the C<%>\nsigil are accessed by string key. The C<$> sigil, however, indicates a\ngeneral scalar container that can hold any single value and be accessed\nin any manner. A scalar can even contain a compound object like an\nL<C<Array>|/type/Array> or a L<C<Hash>|/type/Hash>; the C<$> sigil signifies that it should be\ntreated as a single value, even in a context that expects multiple\nvalues (as with an L<C<Array>|/type/Array> or L<C<Hash>|/type/Hash>).\n\n=head2 X<Filehandle|Tutorial,filehandle (Basics)> and X<assignment|Tutorial,assignment (Basics)>\n\nThe built-in function C<open> opens a file, here named C<scores.txt>,\nand returns a I<filehandle> E<mdash> an object representing that file. The\nassignment operator C<=> I<assigns> that filehandle to the variable on the left,\nwhich means that C<$file> now stores the filehandle.\n\n=head2 X<String literals|Tutorial,string literal (Basics)>\n\nC<'scores.txt'> is a I<string literal>. A string is a piece of text, and a\nstring literal is a string which appears directly in the program. In this line,\nit's the argument provided to C<open>.\n\n=head1 X<Arrays|Tutorial,array (Basics)>, X<methods|Tutorial,method (Basics)> and X<invocants|Tutorial,invocant (Basics)>\n\n=begin code :preamble<my $file>\nmy @names = $file.get.words;\n=end code\n\nThe right-hand side calls a I<method> E<mdash> a named group of\nbehavior E<mdash> named C<get> on the filehandle stored in C<$file>. The C<get>\nmethod reads and returns one line from the file, removing the line ending. If\nyou print the contents of C<$file> after calling C<get>, you will see that the\nfirst line is no longer in there. C<words> is also a method, called on the\nstring returned from C<get>. C<words> decomposes its I<invocant> E<mdash>\nthe string on which it operates E<mdash> into a list of words, which here means\nstrings separated by whitespace. It turns the single string C<'Beth Ana Charlie\nDave'> into the list of strings C<'Beth', 'Ana', 'Charlie', 'Dave'>.\n\nFinally, this list gets stored in the L<C<Array>|/type/Array> C<@names>.\nThe C<@> sigil marks the declared variable as an L<C<Array>|/type/Array>.\nArrays store ordered lists.\n\n=head1 X<Hashes|Tutorial,hash (Basics)>\n\n=begin code\nmy %matches;\nmy %sets;\n=end code\n\nThese two lines of code declare two hashes. The C<%> sigil marks each variable\nas a L<C<Hash>|/type/Hash>. A L<C<Hash>|/type/Hash> is an unordered collection of key-value pairs. Other\nprogramming languages call that a I<hash table>, I<dictionary>, or I<map>.\nYou can query a hash table for the value that corresponds to a certain\nC<$key> with C<%hash{$key}>.\n\nIn the score counting program, C<%matches> stores the number of matches each\nplayer has won. C<%sets> stores the number of sets each player has won. Both\nof these hashes are indexed by the player's name.\n\n=head1 X<C<for>|Tutorial,for (Basics)> and blocks\n\n=begin code :preamble<my $file>\nfor $file.lines -> $line {\n    ...\n}\n=end code\n\nC<for> produces a loop that runs the I<block> delimited by curly braces\nonce for each item of the list, setting the variable C<$line>\nto the current value of each iteration. C<$file.lines> produces a list of\nthe lines read from the file C<scores.txt>, starting with the second line\nof the file since we already called C<$file.get> once, and going all the way\nto the end of the file.\n\nDuring the first iteration, C<$line> will contain the string C<Ana Dave |\n3:0>; during the second, C<Charlie Beth | 3:1>, and so on.\n\n=begin code :preamble<my $line>\nmy ($pairing, $result) = $line.split(' | ');\n=end code\n\nC<my> can declare multiple variables simultaneously. The right-hand side of the\nassignment is a call to a method named C<split>, passing along the string\nC<' | '> as an argument.\n\nC<split> decomposes its invocant into a list of strings, so that joining the\nlist items with the separator C<' | '> produces the original string.\n\nC<$pairing> gets the first item of the returned list, and C<$result> the second.\n\nAfter processing the first line, C<$pairing> will hold the string C<Ana Dave>\nand C<$result> will hold C<3:0>.\n\nThe next two lines follow the same pattern:\n\n=begin code :preamble<my $pairing;my $result>\nmy ($p1, $p2) = $pairing.words;\nmy ($r1, $r2) = $result.split(':');\n=end code\n\nThe first extracts and stores the names of the two players in the variables\nC<$p1> and C<$p2>. The second extracts the results for each player and stores\nthem in C<$r1> and C<$r2>.\n\nAfter processing the first line of the file, the variables contain the values:\n=begin table\n    Variable    Contents\n    $line       'Ana Dave \\| 3:0'\n    $pairing    'Ana Dave'\n    $result     '3:0'\n    $p1         'Ana'\n    $p2         'Dave'\n    $r1         '3'\n    $r2         '0'\n\n=end table\n\nThe program then counts the number of sets each player has won:\n\n=begin code :preamble<my %sets;my $p1;my $p2;my $r1;my $r2>\n%sets{$p1} += $r1;\n%sets{$p2} += $r2;\n=end code\n\nThe above two statements involve the C<+=> compound assignment operator. They\nare a variant of the following two statements that use the simple assignment\noperator C<=> and that may be easier to understand at first sight:\n\n=begin code :preamble<my %sets;my $p1;my $p2;my $r1;my $r2>\n%sets{$p1} = %sets{$p1} + $r1;\n%sets{$p2} = %sets{$p2} + $r2;\n=end code\n\nFor your program, the shorthand version using the C<+=> compound assignment\noperator is preferred over the longhand version using the simple assignment\noperator C<=>. This is not only because the shorter version requires less\ntyping, but also because the C<+=> operator silently initializes undefined\nvalues of the hash's key-value pairs to zero. In other words: by using C<+=>,\nthere is no need to include a separate statement like C<%sets{$p1} = 0> before\nyou can meaningfully add C<$r1> to it. We'll look at this behavior in a bit\nmore detail below.\n\n=head2 X<C<Any>|Tutorial,Any (Basics)> and X<C<+=>|Tutorial,+= (Basics)>\n\n=begin code :preamble<my %sets;my $p1;my $p2;my $r1;my $r2>\n%sets{$p1} += $r1;\n%sets{$p2} += $r2;\n=end code\n\nC<%sets{$p1} += $r1> means I<increase the value in the variable on the left by $r1>.\nIn the first iteration C<%sets{$p1}> is not yet defined, so it defaults to a special\nvalue called L<C<Any>|/type/Any>. The C<+=> operator conveniently treats the undefined value\nL<C<Any>|/type/Any> as a number with the value C<0>, allowing it to sensibly add some other\nvalue to it. To perform the addition, the strings C<$r1>, C<$r2>, etc. are\nautomatically converted to numbers, as addition is a numeric operation.\n\n=head2 X<Fat arrow|Tutorial,fat arrow (Basics)>, X<pairs|Tutorial,pair (Basics)> and X<autovivification|Tutorial,autovivification (Basics)>\n\nBefore these two lines execute, C<%sets> is empty. Adding to an entry that is\nnot in the hash yet will cause that entry to spring into existence\njust-in-time, with a value starting at zero. This behavior is known as\nI<autovivification>. After these two lines have run for the first time, C<%sets>\ncontains C«'Ana' => 3, 'Dave' => 0». (The fat arrow C«=>» separates the\nkey and the value in a L<C<Pair>|/type/Pair>.)\n\n=head2 X<Postincrement|Tutorial,postincrement (Basics)> and X<preincrement|Tutorial,preincrement (Basics)>\n\n=begin code :preamble<my $r1;my $r2;my $p1;my $p2;my %matches;>\nif $r1 > $r2 {\n    %matches{$p1}++;\n} else {\n    %matches{$p2}++;\n}\n=end code\n\nIf C<$r1> is numerically larger than C<$r2>, C<%matches{$p1}> increments by one.\nIf C<$r1> is not larger than C<$r2>, C<%matches{$p2}> increments. Just as in\nthe case of C<+=>, if either hash value did not exist previously, it is\nautovivified by the increment operation.\n\nC<$thing++> is a variant of C<$thing += 1>; it differs from the latter in that\nthe return value of the expression is C<$thing> I<before> the increment, and not\nthe incremented value. As in many other programming languages, you can use C<++>\nas a prefix. Then it returns the incremented value: C<my $x = 1; say ++$x>\nprints C<2>.\n\n=head1 X<Topic variable|Tutorial,topic variable (Basics)>\n\n=begin code :preamble<my @names;my %sets;my %matches>\nmy @sorted = @names.sort({ %sets{$_} }).sort({ %matches{$_} }).reverse;\n=end code\n\nThis line consists of three individually simple steps. An array's C<sort>\nmethod returns a sorted version of the array's contents. However, the default\nsort on an array sorts by its contents. To print player names in winner-first\norder, the code must sort the array by the I<scores> of the players, not their\nnames. The C<sort> method's argument is a I<block> used to transform the array\nelements (the names of players) to the data by which to sort. The array items\nare passed in through the I<topic variable> C<$_>.\n\n=head2 Blocks\n\nYou have seen blocks before: both the C<for> loop C<<-> $line { ... }>> and\nthe C<if> statement worked on blocks. A block is a self-contained piece of\nRaku code with an optional signature (the C<<-> $line>> part).\n\nThe simplest way to sort the players by score would be C<@names.sort({\n%matches{$_} })>, which sorts by number of matches won. However Ana and Dave\nhave both won two matches. That simple sort doesn't account for the number of\nsets won, which is the secondary criterion to decide who has won the\ntournament.\n\n=head2 Stable sort\n\nWhen two array items have the same value, C<sort> leaves them in the same order\nas it found them. Computer scientists call this a I<stable sort>. The program\ntakes advantage of this property of Raku's C<sort> to achieve the goal by\nsorting twice: first by the number of sets won (the secondary criterion), then\nby the number of matches won (the primary criterion).\n\nAfter the first sorting step, the names are in the order C<Beth Charlie Dave\nAna>. After the second sorting step, it's still the same, because no one has\nwon fewer matches but more sets than someone else. Such a situation is entirely\npossible, especially at larger tournaments.\n\nC<sort> sorts in ascending order, from smallest to largest. This is the\nopposite of the desired order. Therefore, the code calls the C<.reverse> method\non the result of the second sort, and stores the final list in C<@sorted>.\n\n=head1 Standard output\n\n=begin code :preamble<my @sorted;my %matches;my %sets>\nfor @sorted -> $n {\n    my $match-noun = %matches{$n} == 1 ?? 'match' !! 'matches';\n    my $set-noun   = %sets{$n} == 1 ?? 'set' !! 'sets';\n    say \"$n has won %matches{$n} $match-noun and %sets{$n} $set-noun\";\n}\n=end code\n\nTo print out the players and their scores, the code loops over C<@sorted>,\nsetting C<$n> to the name of each player in turn. Read this code as \"For each\nelement of sorted, set C<$n> to the element, then execute the contents of the\nfollowing block.\" The variable C<$match-noun> will store either the string\nI<match> if the player has won a single match or I<matches> if the player\nhas won zero or more matches. In order to do this, the I<ternary>\noperator (C<?? !!>) is used. If C<%matches{$n} == 1> evaluates to C<True>,\nthen I<match> is returned. Otherwise, I<matches> is returned. Either way,\nthe returned value is stored in C<$match-noun>. The same approach applies\nto C<$set-noun>.\n\nThe statement C<say> prints its arguments to the standard output\n(the screen, normally), followed by a newline. (Use C<print> if you don't\nwant the newline at the end.)\n\nNote that C<say> will truncate certain data structures by calling the C<.gist>\nmethod so C<put> is safer if you want exact output.\n\n=head2 X<Variable interpolation|Tutorial,variable interpolation (Basics)>\n\nWhen you run the program, you'll see that C<say> doesn't print the contents of\nthat string verbatim. In place of C<$n> it prints the contents of the variable\nC<$n> E<mdash> a player's name stored in C<$n>. This automatic substitution\nof code with its contents is called I<interpolation>. This interpolation happens\nonly in strings delimited by double quotes C<\"...\">. Single quoted strings\nC<'...'> do not interpolate:\n\n=head2 X<Double-quoted strings|Tutorial,double-quoted strings> and X<single-quoted strings|Tutorial,single-quoted strings>\n\n=begin code\nmy $names = 'things';\nsay 'Do not call me $names'; # OUTPUT: «Do not call me $names␤»\nsay \"Do not call me $names\"; # OUTPUT: «Do not call me things␤»\n=end code\n\nDouble quoted strings in Raku can interpolate variables with the C<$>\nsigil as well as blocks of code in curly braces. Since any arbitrary\nRaku code can appear within curly braces, L<C<Array>|/type/Array>s and L<C<Hash>|/type/Hash>es may be\ninterpolated by placing them within curly braces.\n\nArrays within curly braces are interpolated with a single space character\nbetween each item. Hashes within curly braces are interpolated as a series of\nlines. Each line will contain a key, followed by a tab character, then the\nvalue associated with that key, and finally a newline.\n\nLet's see an example of this now.\n\nIn this example, you will see some special syntax that makes it easier\nto make a list of strings. This is the\nC«<...>» L<quote-words|/language/operators#index-entry-qw-quote-words-quote-words>\nconstruct. When you put words in between the C«<» and C«>» they are all assumed\nto be strings, so you do not need to wrap them each in double quotes\nC«\"...\"».\n\n=begin code :preamble<my %sets>\nsay \"Math: { 1 + 2 }\";\n# OUTPUT: «Math: 3␤»\n\nmy @people = <Luke Matthew Mark>;\nsay \"The synoptics are: {@people}\";\n# OUTPUT: «The synoptics are: Luke Matthew Mark␤»\n\nsay \"{%sets}\";\n# OUTPUT (From the table tennis tournament):\n\n# Charlie 4\n# Dave    6\n# Ana     8\n# Beth    4\n=end code\n\nWhen array and hash variables appear directly in a double-quoted string (and\nnot inside curly braces), they are only interpolated if their name is\nfollowed by a postcircumfix operator E<mdash> a bracketing pair that follows a\nstatement. It's also ok to have a method call between the variable name and\nthe postcircumfix.\n\n=head1 Zen slices\n\n=begin code\nmy @flavors = <vanilla peach>;\n\nsay \"we have @flavors\";           # OUTPUT: «we have @flavors␤»\nsay \"we have @flavors[0]\";        # OUTPUT: «we have vanilla␤»\n# so-called \"Zen slice\"\nsay \"we have @flavors[]\";         # OUTPUT: «we have vanilla peach␤»\n\n# method calls ending in postcircumfix\nsay \"we have @flavors.sort()\";    # OUTPUT: «we have peach vanilla␤»\n\n# chained method calls:\nsay \"we have @flavors.sort.join(', ')\";\n                                  # OUTPUT: «we have peach, vanilla␤»\n=end code\n\n=head1 Calling a raku method from another file\n\nTo call a raku subroutine from another file, the convention is to have a minimal\nraku module or class file.\n\n=begin code\n# MyClass.rakumod\nclass C {\n    has $.x;\n}\n=end code\n\nThen your script can C<use> this file.\n\n=begin code :skip-test\n# myscript.raku\nuse MyClass;\n\nmy $instance = C.new(x=>42);\nsay $instance.x;\n=end code\n\nThe C<-I.> directive tells the raku interpreter to look for modules in directory C<.>.\n\n=begin code :lang<shell>\n> raku -I. myscript.raku\n=end code\n\n=head1 Exercises\n\nB<1.> The input format of the example program is redundant: the first line\ncontaining the name of all players is not necessary, because you can find out\nwhich players participated in the tournament by looking at their names in the\nsubsequent rows, so in principle we could safely remove it.\n\nHow can you make the program run if you do not use the C<@names> variable?\nHint: C<%hash.keys> returns a list of all keys stored in C<%hash>.\n\nB<Answer:> After removing the first line in C<scores.txt>, remove the line C<my\n@names = $file.get.words;> (which would read it), and change:\n\n=begin code :preamble<my @names;my %sets;my %matches>\nmy @sorted = @names.sort({ %sets{$_} }).sort({ %matches{$_} }).reverse;\n=end code\n\n... into:\n\n=begin code :preamble<my %sets;my %matches>\nmy @sorted = %sets.keys.sort({ %sets{$_} }).sort({ %matches{$_} }).reverse;\n=end code\n\nB<2.> Instead of deleting the redundant C<@names> variable, you can also use it\nto warn if a player appears that wasn't mentioned in the first line, for\nexample due to a typo. How would you modify your program to achieve that?\n\nHint: Try using L<membership operators|/language/operators#infix_(elem),_infix_∈>.\n\nB<Answer:> Change C<@names> to C<@valid-players>. When looping through the\nlines of the file, check to see that C<$p1> and C<$p2> are in\nC<@valid-players>. Note that for membership operators you can also use C<(elem)>\nand C<!(elem)>.\n\n=begin code :preamble<my $file>\n...;\nmy @valid-players = $file.get.words;\n...;\n\nfor $file.lines -> $line {\n    my ($pairing, $result) = $line.split(' | ');\n    my ($p1, $p2)          = $pairing.split(' ');\n    if $p1 ∉ @valid-players {\n        say \"Warning: '$p1' is not on our list!\";\n    }\n    if $p2 ∉ @valid-players {\n        say \"Warning: '$p2' is not on our list!\";\n    }\n    ...\n}\n=end code\n\n=end pod\n\n"
  },
  {
    "path": "doc/Language/REPL.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"tutorial\")\n\n=TITLE REPL\n\n=SUBTITLE Interactive Raku, read-eval-print loop\n\n=head1 Overview\n\nThe C<REPL> is an interactive Raku prompt. Each line of code you enter in the C<REPL>\nis executed, and if no output was generated, the value returned\nby the expression is output.\n\n=head1 Trap\n\nB<Note>: Running code in the C<REPL> is not equivalent to saving the code in a file and\nrunning that. Each line introduces a new scope which can confuse code that has multiple\nlines. See C<sub repl()> below for a way to target a REPL inside a larger script.\n\n=head1 Previous Values\n\nAs you enter commands into the REPL, each line has a numeric ID associated with it, starting\nwith C<0>. On subsequent lines, you can use the result with a special variable only available\nin the REPL.  C<$*0>, C<$*1>, etc. In this example, we calculate two values and then use them\nboth on the third line.\n\n=begin code :lang<REPL>\n✗ raku\nWelcome to Rakudo™ v2025.08.\nImplementing the Raku® Programming Language v6.d.\nBuilt on MoarVM version 2025.08.\n\nTo exit type 'exit' or '^D'\n[0] > 3+2\n5\n[1] > 7+1\n8\n[2] > $*0 * $*1\n40\n[3] >\n=end code\n\n=head1 non-interactive mode\n\nIf invoked from the command line with  C<raku --repl-mode=non-interactive>, no history or prompts\nare printed, and the code is not executed until you close input (on Linux, for example, you can pipe\nthe code to it or press C<Control-d>.\n\n=for code :lang<shell>\n    $ echo \"say 3\" | raku --repl-mode=non-interactive\n    3\n\n=head1 sub repl()\n\nThis routine allows you to embed a REPL inside a larger script and have access to all\nthe variables in context.\n\nSee L<sub repl()|/type/independent-routines#sub_repl> in Independent Routines for more\ninformation.\n\n=head1 ENVIRONMENT Variables\n\nSee L<ENVIRONMENT Variables|/programs/03-environment-variables#Environment_variables_used_by_the_raku_command_line>.\n\n=head2 Get command line history\n\nIn a fresh install, there is no command history. Running the C<REPL> in this mode will\nprompt you to install one of the various modules that provide this support. If enabled,\nyou can use the arrow keys to scroll through previous commands and use standard terminal\nshortcuts for editing. There are currently four options:\n\n=item 1\n\n=for code :lang<shell>\n    zef install Terminal::LineEditor\n\n=item 2\n\n=for code :lang<shell>\n    zef install Linenoise\n\nThis requires a working C<C> toolchain.\n\n=item 3\n\n=for code :lang<shell>\n    zef install Readline\n\nThis requires an installation of the C<Readline> development library.\n\n=item 4\n\nAn alternative for UNIX-like systems is to install C<rlwrap>. This can\nbe done on Debian-ish systems by running:\n\n=for code :lang<shell>\nsudo apt-get install rlwrap\n\nAnd then use it to invoke the C<REPL>:\n\n=for code :lang<shell>\nrlwrap raku\n\n\n=end pod\n"
  },
  {
    "path": "doc/Language/about.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"beginning\")\n\n=TITLE About the docs\n\n=SUBTITLE How to locally generate the Raku documentation; and how to contribute to it.\n\nThis document collection represents the on-going effort to document the\nRaku programming language with the goals of being comprehensive,\neasy to use, easy to navigate, and useful to both newcomers and experienced\nRaku programmers.\n\nAn L<HTML version of the documentation|https://docs.raku.org> is available.\n\nThe official source for this documentation is located at\nL<Raku/doc on GitHub|https://github.com/Raku/doc>.\n\n=head1 Structure\n\nAll of the documentation is written in Raku Pod and kept in the C<doc/>\ndirectory.  These files are processed are rendered to HTML, and also\nprocessed into some generated pages, using the C<.rakudoc> files as\nsources.\n\n=head1 Generating HTML from Pod\n\nThe build process is managed through a separate repository,\nL<Raku/doc-website on GitHub|https://github.com/Raku/doc-website>.\n\n=head1 Contributing\n\nFor a quick introduction to Raku Pod, see L<Raku Pod|/language/pod>.\n\nFor historic details about the Raku Pod specification, see L<Synopsis 26, Documentation|https://github.com/Raku/old-design-docs/blob/master/S26-documentation.pod>.\n\nFor information on how to contribute to the documentation, please\nread L<CONTRIBUTING.md|https://github.com/Raku/doc/blob/main/CONTRIBUTING.md>.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/brackets.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"reference\")\n\n=TITLE Brackets\n\n=SUBTITLE Valid opening/closing paired delimiters\n\nThe following table shows all of the valid graphemes usable as opening\nand closing paired delimiters in such constructs as I<Pod6 declarator\nblocks>.  Note they are shown between pipe symbols so the extra bounding\nspace for any wide characters can be seen.\n\nThe data source for the table is the I<$brackets> string defined in the\nI<HLL::Grammar> module in the I<github.com/Raku/nqp> repository.\n\nThe data are arranged in the order found in the source string.\nEach opening bracket is shown in its printed form followed by its\npaired closing bracket. Each pair is then followed by its codepoints.\nThere are two sets of bracket pairs shown per table row.\n\n=begin table :caption<Bracket pairs>\n LChar | RChar | LHex  | RHex  | LChar | RChar | LHex  | RHex\n======+======+======+======+======+======+======+======\n\\|(\\| | \\|)\\| | 0x0028 | 0x0029 | \\|<\\| | \\|>\\| | 0x003C | 0x003E\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|[\\| | \\|]\\| | 0x005B | 0x005D | \\|{\\| | \\|}\\| | 0x007B | 0x007D\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|«\\| | \\|»\\| | 0x00AB | 0x00BB | \\|༺\\| | \\|༻\\| | 0x0F3A | 0x0F3B\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|༼\\| | \\|༽\\| | 0x0F3C | 0x0F3D | \\|᚛\\| | \\|᚜\\| | 0x169B | 0x169C\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|‘\\| | \\|’\\| | 0x2018 | 0x2019 | \\|‚\\| | \\|’\\| | 0x201A | 0x2019\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|‛\\| | \\|’\\| | 0x201B | 0x2019 | \\|“\\| | \\|”\\| | 0x201C | 0x201D\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|„\\| | \\|”\\| | 0x201E | 0x201D | \\|‟\\| | \\|”\\| | 0x201F | 0x201D\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|‹\\| | \\|›\\| | 0x2039 | 0x203A | \\|⁅\\| | \\|⁆\\| | 0x2045 | 0x2046\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⁽\\| | \\|⁾\\| | 0x207D | 0x207E | \\|₍\\| | \\|₎\\| | 0x208D | 0x208E\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|∈\\| | \\|∋\\| | 0x2208 | 0x220B | \\|∉\\| | \\|∌\\| | 0x2209 | 0x220C\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|∊\\| | \\|∍\\| | 0x220A | 0x220D | \\|∕\\| | \\|⧵\\| | 0x2215 | 0x29F5\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|∼\\| | \\|∽\\| | 0x223C | 0x223D | \\|≃\\| | \\|⋍\\| | 0x2243 | 0x22CD\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|≒\\| | \\|≓\\| | 0x2252 | 0x2253 | \\|≔\\| | \\|≕\\| | 0x2254 | 0x2255\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|≤\\| | \\|≥\\| | 0x2264 | 0x2265 | \\|≦\\| | \\|≧\\| | 0x2266 | 0x2267\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|≨\\| | \\|≩\\| | 0x2268 | 0x2269 | \\|≪\\| | \\|≫\\| | 0x226A | 0x226B\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|≮\\| | \\|≯\\| | 0x226E | 0x226F | \\|≰\\| | \\|≱\\| | 0x2270 | 0x2271\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|≲\\| | \\|≳\\| | 0x2272 | 0x2273 | \\|≴\\| | \\|≵\\| | 0x2274 | 0x2275\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|≶\\| | \\|≷\\| | 0x2276 | 0x2277 | \\|≸\\| | \\|≹\\| | 0x2278 | 0x2279\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|≺\\| | \\|≻\\| | 0x227A | 0x227B | \\|≼\\| | \\|≽\\| | 0x227C | 0x227D\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|≾\\| | \\|≿\\| | 0x227E | 0x227F | \\|⊀\\| | \\|⊁\\| | 0x2280 | 0x2281\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⊂\\| | \\|⊃\\| | 0x2282 | 0x2283 | \\|⊄\\| | \\|⊅\\| | 0x2284 | 0x2285\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⊆\\| | \\|⊇\\| | 0x2286 | 0x2287 | \\|⊈\\| | \\|⊉\\| | 0x2288 | 0x2289\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⊊\\| | \\|⊋\\| | 0x228A | 0x228B | \\|⊏\\| | \\|⊐\\| | 0x228F | 0x2290\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⊑\\| | \\|⊒\\| | 0x2291 | 0x2292 | \\|⊘\\| | \\|⦸\\| | 0x2298 | 0x29B8\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⊢\\| | \\|⊣\\| | 0x22A2 | 0x22A3 | \\|⊦\\| | \\|⫞\\| | 0x22A6 | 0x2ADE\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⊨\\| | \\|⫤\\| | 0x22A8 | 0x2AE4 | \\|⊩\\| | \\|⫣\\| | 0x22A9 | 0x2AE3\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⊫\\| | \\|⫥\\| | 0x22AB | 0x2AE5 | \\|⊰\\| | \\|⊱\\| | 0x22B0 | 0x22B1\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⊲\\| | \\|⊳\\| | 0x22B2 | 0x22B3 | \\|⊴\\| | \\|⊵\\| | 0x22B4 | 0x22B5\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⊶\\| | \\|⊷\\| | 0x22B6 | 0x22B7 | \\|⋉\\| | \\|⋊\\| | 0x22C9 | 0x22CA\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⋋\\| | \\|⋌\\| | 0x22CB | 0x22CC | \\|⋐\\| | \\|⋑\\| | 0x22D0 | 0x22D1\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⋖\\| | \\|⋗\\| | 0x22D6 | 0x22D7 | \\|⋘\\| | \\|⋙\\| | 0x22D8 | 0x22D9\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⋚\\| | \\|⋛\\| | 0x22DA | 0x22DB | \\|⋜\\| | \\|⋝\\| | 0x22DC | 0x22DD\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⋞\\| | \\|⋟\\| | 0x22DE | 0x22DF | \\|⋠\\| | \\|⋡\\| | 0x22E0 | 0x22E1\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⋢\\| | \\|⋣\\| | 0x22E2 | 0x22E3 | \\|⋤\\| | \\|⋥\\| | 0x22E4 | 0x22E5\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⋦\\| | \\|⋧\\| | 0x22E6 | 0x22E7 | \\|⋨\\| | \\|⋩\\| | 0x22E8 | 0x22E9\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⋪\\| | \\|⋫\\| | 0x22EA | 0x22EB | \\|⋬\\| | \\|⋭\\| | 0x22EC | 0x22ED\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⋰\\| | \\|⋱\\| | 0x22F0 | 0x22F1 | \\|⋲\\| | \\|⋺\\| | 0x22F2 | 0x22FA\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⋳\\| | \\|⋻\\| | 0x22F3 | 0x22FB | \\|⋴\\| | \\|⋼\\| | 0x22F4 | 0x22FC\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⋶\\| | \\|⋽\\| | 0x22F6 | 0x22FD | \\|⋷\\| | \\|⋾\\| | 0x22F7 | 0x22FE\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⌈\\| | \\|⌉\\| | 0x2308 | 0x2309 | \\|⌊\\| | \\|⌋\\| | 0x230A | 0x230B\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|〈\\| | \\|〉\\| | 0x2329 | 0x232A | \\|⎴\\| | \\|⎵\\| | 0x23B4 | 0x23B5\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|❨\\| | \\|❩\\| | 0x2768 | 0x2769 | \\|❪\\| | \\|❫\\| | 0x276A | 0x276B\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|❬\\| | \\|❭\\| | 0x276C | 0x276D | \\|❮\\| | \\|❯\\| | 0x276E | 0x276F\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|❰\\| | \\|❱\\| | 0x2770 | 0x2771 | \\|❲\\| | \\|❳\\| | 0x2772 | 0x2773\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|❴\\| | \\|❵\\| | 0x2774 | 0x2775 | \\|⟃\\| | \\|⟄\\| | 0x27C3 | 0x27C4\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⟅\\| | \\|⟆\\| | 0x27C5 | 0x27C6 | \\|⟕\\| | \\|⟖\\| | 0x27D5 | 0x27D6\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⟝\\| | \\|⟞\\| | 0x27DD | 0x27DE | \\|⟢\\| | \\|⟣\\| | 0x27E2 | 0x27E3\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⟤\\| | \\|⟥\\| | 0x27E4 | 0x27E5 | \\|⟦\\| | \\|⟧\\| | 0x27E6 | 0x27E7\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⟨\\| | \\|⟩\\| | 0x27E8 | 0x27E9 | \\|⟪\\| | \\|⟫\\| | 0x27EA | 0x27EB\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⦃\\| | \\|⦄\\| | 0x2983 | 0x2984 | \\|⦅\\| | \\|⦆\\| | 0x2985 | 0x2986\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⦇\\| | \\|⦈\\| | 0x2987 | 0x2988 | \\|⦉\\| | \\|⦊\\| | 0x2989 | 0x298A\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⦋\\| | \\|⦌\\| | 0x298B | 0x298C | \\|⦍\\| | \\|⦐\\| | 0x298D | 0x2990\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⦏\\| | \\|⦎\\| | 0x298F | 0x298E | \\|⦑\\| | \\|⦒\\| | 0x2991 | 0x2992\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⦓\\| | \\|⦔\\| | 0x2993 | 0x2994 | \\|⦕\\| | \\|⦖\\| | 0x2995 | 0x2996\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⦗\\| | \\|⦘\\| | 0x2997 | 0x2998 | \\|⧀\\| | \\|⧁\\| | 0x29C0 | 0x29C1\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⧄\\| | \\|⧅\\| | 0x29C4 | 0x29C5 | \\|⧏\\| | \\|⧐\\| | 0x29CF | 0x29D0\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⧑\\| | \\|⧒\\| | 0x29D1 | 0x29D2 | \\|⧔\\| | \\|⧕\\| | 0x29D4 | 0x29D5\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⧘\\| | \\|⧙\\| | 0x29D8 | 0x29D9 | \\|⧚\\| | \\|⧛\\| | 0x29DA | 0x29DB\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⧸\\| | \\|⧹\\| | 0x29F8 | 0x29F9 | \\|⧼\\| | \\|⧽\\| | 0x29FC | 0x29FD\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⨫\\| | \\|⨬\\| | 0x2A2B | 0x2A2C | \\|⨭\\| | \\|⨮\\| | 0x2A2D | 0x2A2E\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⨴\\| | \\|⨵\\| | 0x2A34 | 0x2A35 | \\|⨼\\| | \\|⨽\\| | 0x2A3C | 0x2A3D\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⩤\\| | \\|⩥\\| | 0x2A64 | 0x2A65 | \\|⩹\\| | \\|⩺\\| | 0x2A79 | 0x2A7A\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⩽\\| | \\|⩾\\| | 0x2A7D | 0x2A7E | \\|⩿\\| | \\|⪀\\| | 0x2A7F | 0x2A80\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⪁\\| | \\|⪂\\| | 0x2A81 | 0x2A82 | \\|⪃\\| | \\|⪄\\| | 0x2A83 | 0x2A84\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⪋\\| | \\|⪌\\| | 0x2A8B | 0x2A8C | \\|⪑\\| | \\|⪒\\| | 0x2A91 | 0x2A92\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⪓\\| | \\|⪔\\| | 0x2A93 | 0x2A94 | \\|⪕\\| | \\|⪖\\| | 0x2A95 | 0x2A96\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⪗\\| | \\|⪘\\| | 0x2A97 | 0x2A98 | \\|⪙\\| | \\|⪚\\| | 0x2A99 | 0x2A9A\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⪛\\| | \\|⪜\\| | 0x2A9B | 0x2A9C | \\|⪡\\| | \\|⪢\\| | 0x2AA1 | 0x2AA2\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⪦\\| | \\|⪧\\| | 0x2AA6 | 0x2AA7 | \\|⪨\\| | \\|⪩\\| | 0x2AA8 | 0x2AA9\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⪪\\| | \\|⪫\\| | 0x2AAA | 0x2AAB | \\|⪬\\| | \\|⪭\\| | 0x2AAC | 0x2AAD\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⪯\\| | \\|⪰\\| | 0x2AAF | 0x2AB0 | \\|⪳\\| | \\|⪴\\| | 0x2AB3 | 0x2AB4\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⪻\\| | \\|⪼\\| | 0x2ABB | 0x2ABC | \\|⪽\\| | \\|⪾\\| | 0x2ABD | 0x2ABE\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⪿\\| | \\|⫀\\| | 0x2ABF | 0x2AC0 | \\|⫁\\| | \\|⫂\\| | 0x2AC1 | 0x2AC2\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⫃\\| | \\|⫄\\| | 0x2AC3 | 0x2AC4 | \\|⫅\\| | \\|⫆\\| | 0x2AC5 | 0x2AC6\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⫍\\| | \\|⫎\\| | 0x2ACD | 0x2ACE | \\|⫏\\| | \\|⫐\\| | 0x2ACF | 0x2AD0\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⫑\\| | \\|⫒\\| | 0x2AD1 | 0x2AD2 | \\|⫓\\| | \\|⫔\\| | 0x2AD3 | 0x2AD4\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⫕\\| | \\|⫖\\| | 0x2AD5 | 0x2AD6 | \\|⫬\\| | \\|⫭\\| | 0x2AEC | 0x2AED\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⫷\\| | \\|⫸\\| | 0x2AF7 | 0x2AF8 | \\|⫹\\| | \\|⫺\\| | 0x2AF9 | 0x2AFA\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⸂\\| | \\|⸃\\| | 0x2E02 | 0x2E03 | \\|⸄\\| | \\|⸅\\| | 0x2E04 | 0x2E05\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⸉\\| | \\|⸊\\| | 0x2E09 | 0x2E0A | \\|⸌\\| | \\|⸍\\| | 0x2E0C | 0x2E0D\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⸜\\| | \\|⸝\\| | 0x2E1C | 0x2E1D | \\|⸠\\| | \\|⸡\\| | 0x2E20 | 0x2E21\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⸨\\| | \\|⸩\\| | 0x2E28 | 0x2E29 | \\|〈\\| | \\|〉\\| | 0x3008 | 0x3009\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|《\\| | \\|》\\| | 0x300A | 0x300B | \\|「\\| | \\|」\\| | 0x300C | 0x300D\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|『\\| | \\|』\\| | 0x300E | 0x300F | \\|【\\| | \\|】\\| | 0x3010 | 0x3011\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|〔\\| | \\|〕\\| | 0x3014 | 0x3015 | \\|〖\\| | \\|〗\\| | 0x3016 | 0x3017\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|〘\\| | \\|〙\\| | 0x3018 | 0x3019 | \\|〚\\| | \\|〛\\| | 0x301A | 0x301B\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|〝\\| | \\|〞\\| | 0x301D | 0x301E | \\|︗\\| | \\|︘\\| | 0xFE17 | 0xFE18\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|︵\\| | \\|︶\\| | 0xFE35 | 0xFE36 | \\|︷\\| | \\|︸\\| | 0xFE37 | 0xFE38\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|︹\\| | \\|︺\\| | 0xFE39 | 0xFE3A | \\|︻\\| | \\|︼\\| | 0xFE3B | 0xFE3C\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|︽\\| | \\|︾\\| | 0xFE3D | 0xFE3E | \\|︿\\| | \\|﹀\\| | 0xFE3F | 0xFE40\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|﹁\\| | \\|﹂\\| | 0xFE41 | 0xFE42 | \\|﹃\\| | \\|﹄\\| | 0xFE43 | 0xFE44\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|﹇\\| | \\|﹈\\| | 0xFE47 | 0xFE48 | \\|﹙\\| | \\|﹚\\| | 0xFE59 | 0xFE5A\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|﹛\\| | \\|﹜\\| | 0xFE5B | 0xFE5C | \\|﹝\\| | \\|﹞\\| | 0xFE5D | 0xFE5E\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|（\\| | \\|）\\| | 0xFF08 | 0xFF09 | \\|＜\\| | \\|＞\\| | 0xFF1C | 0xFF1E\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|［\\| | \\|］\\| | 0xFF3B | 0xFF3D | \\|｛\\| | \\|｝\\| | 0xFF5B | 0xFF5D\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|｟\\| | \\|｠\\| | 0xFF5F | 0xFF60 | \\|｢\\| | \\|｣\\| | 0xFF62 | 0xFF63\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⟮\\| | \\|⟯\\| | 0x27EE | 0x27EF | \\|⸤\\| | \\|⸥\\| | 0x2E24 | 0x2E25\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⟬\\| | \\|⟭\\| | 0x27EC | 0x27ED | \\|⸢\\| | \\|⸣\\| | 0x2E22 | 0x2E23\n--------+---------+---------+---------+--------+---------+---------+---------\n\\|⸦\\| | \\|⸧\\| | 0x2E26 | 0x2E27 |  |  |  |\n--------+---------+---------+---------+--------+---------+---------+---------\n=end table\nZ<This file was created by program '/util/create-brackets-table.raku'>\n\n=end pod\n"
  },
  {
    "path": "doc/Language/classtut.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"tutorial\")\n\n=TITLE Classes and objects\n\n=SUBTITLE A tutorial about creating and using classes in Raku\n\nX<|Tutorial,OOP>\nRaku provides a rich built-in syntax for defining and using classes. It makes writing classes\nexpressive and short for most cases, but also provides mechanisms to cover\nthe rare corner cases.\n\n=head1 A quick overview\n\nLet's start with an example to give an overview:\n\n=begin code\nclass Rectangle {\n    has Int $.length = 1;\n    has Int $.width = 1;\n\n    method area(--> Int) {\n        return $!length * $!width;\n    }\n}\n\nmy $r1 = Rectangle.new(length => 2, width => 3);\nsay $r1.area(); # OUTPUT: «6␤»\n=end code\n\nWe define a new I<Rectangle> class using the L<class|/language/objects#Classes> keyword. It has two L<attributes|#Attributes>, C<$!length> and C<$!width> introduced\nwith the L<has|/syntax/has> keyword. Both default to C<1>. Read only accessor methods are automatically generated. (Note the C<.> instead of C<!> in the declaration, which triggers the generation. Mnemonic: C<!> resembles a closed door, C<.> an open one.)\n\nThe L<method|/language/objects#Methods> named C<area> will return the area of the rectangle.\n\nIt is rarely necessary to explicitly write a constructor. An automatically inherited default constructor called L<new|/language/objects#Object_construction> will automatically initialize attributes from named parameters passed to the constructor.\n\n=head1 The Task example\n\nAs a more elaborate example the following piece of code implements a dependency\nhandler. It showcases custom constructors, private and public attributes,\nmethods, and various aspects of signatures. It's not a lot of code, and yet the\nresult is interesting and useful. It will be used as an example throughout the\nfollowing sections.\n\n=begin code\nclass Task {\n    has      &!callback     is built;\n    has Task @!dependencies is built;\n    has Bool $.done;\n\n    method new(&callback, *@dependencies) {\n        return self.bless(:&callback, :@dependencies);\n    }\n\n    method add-dependency(Task $dependency) {\n        push @!dependencies, $dependency;\n    }\n\n    method perform() {\n        unless $!done {\n            .perform() for @!dependencies;\n            &!callback();\n            $!done = True;\n        }\n    }\n}\n\nmy $eat =\n    Task.new({ say 'eating dinner. NOM!' },\n        Task.new({ say 'making dinner' },\n            Task.new({ say 'buying food' },\n                Task.new({ say 'making some money' }),\n                Task.new({ say 'going to the store' })\n            ),\n            Task.new({ say 'cleaning kitchen' })\n        )\n    );\n\n$eat.perform();\n=end code\n\n=head1 X<Class|Tutorial,class>\n\nX<|Tutorial,state>\nRaku, like many other languages, uses the C<class> keyword to define a\nclass. The block that follows may contain arbitrary code, just as with\nany other block, but classes commonly contain state and behavior\ndeclarations. The example code includes attributes (state), introduced\nthrough the C<has> keyword, and behaviors, introduced through the C<method>\nkeyword.\n\n\n=head1 X<Attributes|Tutorial,attributes>\n\nX<|Tutorial,encapsulation>\nX<|Tutorial,has>\nIn the C<Task> class, the first three lines inside the block all\ndeclare attributes (called I<fields> or I<instance storage> in other\nlanguages) using the C<has> declarator. Just as a C<my> variable cannot be\naccessed from outside its declared scope, attributes are never directly\naccessible from outside of the class (this is in contrast to many other\nlanguages). This I<encapsulation> is one of the key principles of object\noriented design.\n\n=head2 X<Twigil C<$!>|Tutorial,twigils>\n\nX<|Tutorial,!>\nX<|Tutorial,&>\nThe first declaration specifies instance storage for a callback (i.e.\na bit of code to invoke in order to perform the task that an object\nrepresents):\n\n=for code\nhas &!callback is built;\n\nThe C<&> sigil indicates that this attribute represents something invocable.\nThe C<!> character is a I<twigil>, or secondary sigil. A twigil forms part\nof the name of the variable. In this case, the C<!> twigil emphasizes that\nthis attribute is private to the class. The attribute is I<encapsulated>.\nPrivate attributes will not be set by the default constructor by default, which is\nwhy we add the C<is built> trait to allow just that. Mnemonic: C<!> looks like a closed door.\n\nThe second declaration also uses the private twigil:\n\n=for code :preamble<class Task {}>\nhas Task @!dependencies is built;\n\nHowever, this attribute represents an array of items, so it requires the\nC<@> sigil. These items each specify a task that must be completed before\nthe present one is completed. Furthermore, the type declaration on this\nattribute indicates that the array may only hold instances of the C<Task>\nclass (or some subclass of it).\n\nX<|Tutorial,.>\nX<|Tutorial,accessors>\nX<|Tutorial,accessor methods>\n=head2 Twigil C<$.>\n\nThe third attribute represents the state of completion of a task:\n\n=for code\nhas Bool $.done;\n\nThis scalar attribute (with the C<$> sigil) has a type of L<C<Bool>|/type/Bool>. Instead\nof the C<!> twigil, the C<.> twigil is used. While Raku does enforce\nencapsulation on attributes, it also saves you from writing accessor\nmethods. Replacing the C<!> with a C<.> both declares a private attribute\nand an accessor method named after the attribute. In this case,\nboth the attribute C<$!done> and the accessor method C<done> are declared.\nIt's as if you had written:\n\n=begin code\nhas Bool $!done;\nmethod done() { return $!done }\n=end code\n\nNote that this is not like declaring a public attribute, as some languages\nallow; you really get I<both> a private attribute and a method,\nwithout having to write the method by hand. You are free instead to write\nyour own accessor method, if at some future point you need to do something\nmore complex than returning the value.\n\n=head2 X<C<is rw> trait|Tutorial,is rw>\n\nNote that using the C<.> twigil has created a method that will provide\nread-only access to the attribute. If instead the users of this object\nshould be able to reset a task's completion state (perhaps to perform it\nagain), you can change the attribute declaration:\n\n=for code\nhas Bool $.done is rw;\n\nThe L<C<is rw>|/type/Attribute#trait_is_rw> trait causes the generated accessor method to return a container\nso external code can modify the value of the attribute.\n\n=head2 C<is built> trait\n\n=for code\nhas &!callback is built;\n\nX<|Types,traits>\nX<|Types,is built>\nBy default private attributes are not automatically set by the default constructor. (They are private after\nall.) In the above example we want to allow the user to provide the initial value but keep the attribute\notherwise private. The L<C<is built>|/type/Attribute#trait_is_built> trait allows to do just that.\n\nOne can use the same trait C<is built> to do the opposite for public attributes, i.e. prevent them from being\nautomatically initialized with a user-provided value, but still generate the accessor method. This is done by giving\nthe argument C<False> to the trait:\n\n=for code\nhas $.done is built(False);\n\nAbove declaration makes sure one can't construct finished tasks, but still allow users to look if a task is done.\n\nThe C<is built> trait was introduced in Rakudo release 2020.01.\n\n=head2 C<is required> trait\n\nX<|Types,traits>\nX<|Types,is required>\nProviding a value for an attribute during initialization is optional by default. Which in the task example\nmakes sense for all three, the C<&!callback>, the C<@!dependencies> and the C<$.done> attribute. But lets say\nwe want to add another attribute, C<$.name>, that holds a tasks name and we want to force the user to\nprovide a value on initialization. We can do that as follows:\n\n=for code\nhas $.name is required;\n\n=head2 Default values\n\nYou can also supply default values to attributes (which works equally for\nthose with and without accessors):\n\n=for code\nhas Bool $.done = False;\n\nThe assignment is carried out at object build time. The right-hand side is\nevaluated at that time, and can even reference earlier attributes:\n\n=begin code :preamble<class Task {}>\nhas Task @!dependencies;\nhas $.ready = not @!dependencies;\n=end code\n\nWritable attributes are accessible through writable containers:\n\n=begin code\nclass a-class {\n    has $.an-attribute is rw;\n}\nsay (a-class.new.an-attribute = \"hey\"); # OUTPUT: «hey␤»\n=end code\n\nThis attribute can also be accessed using the C<.an-attribute> or\nC<.an-attribute()> syntax. See also\nL<the C<is rw> trait on classes|/language/typesystem#trait_is_rw> for examples\non how this works on the whole class.\n\nX<|Tutorial,class variables>\n=head1 Class variables\n\nA class declaration can also include I<class variables>, declared with C<my> or C<our>, which are variables\nwhose value is shared by all instances, and can be used for things like\ncounting the number of instantiations or any other shared state. So I<class variables> act similarly to\nI<static> variables known from other programming languages.\nThey look the same as normal (non class) lexical variables (and in fact they are the same):\n\n=begin code\nclass Str-with-ID is Str {\n    my  $counter = 0;\n    our $our-counter = 0;\n    has Str $.string;\n    has Int $.ID is built(False);\n\n    submethod TWEAK() {\n        $counter++;\n        $our-counter++;\n        $!ID = $counter;\n    }\n\n}\n\nclass Str-with-ID-and-tag is Str-with-ID {\n    has Str $.tag;\n}\n\nsay Str-with-ID.new(string => 'First').ID;  # OUTPUT: «1␤»\nsay Str-with-ID.new(string => 'Second').ID; # OUTPUT: «2␤»\nsay Str-with-ID-and-tag.new( string => 'Third', tag => 'Ordinal' ).ID; # OUTPUT: «3␤»\nsay $Str-with-ID::our-counter;        # OUTPUT: «3␤»\n=end code\n\nI<Class variables> are shared by all subclasses, in this case\nC<Str-with-ID-and-tag>. Additionally, when the package scope C<our> declarator\nis used, the variable is visible via their fully qualified name (FQN), while\nlexically scoped C<my> variables are \"private\". This is the exact behavior that\nC<my> and C<our> also show in non class context.\n\nX<|Types,static>\nI<Class variables> act similarly to I<static> variables in many other programming\nlanguages.\n\n=begin code\nclass Singleton {\n    my Singleton $instance;\n    method new {!!!}\n    submethod instance {\n        $instance = Singleton.bless unless $instance;\n        $instance;\n    }\n}\n=end code\n\nIn this implementation of the I<Singleton> pattern a I<class variable> is used\nto save the instance.\n\n=begin code\nclass HaveStaticAttr {\n    my Int $.foo = 5;\n}\n=end code\n\nClass attributes may also be declared with a secondary sigil – in a similar\nmanner to instance attributes – that will generate read-only accessors if the\nattribute is to be public.\nDefault values behave as expected and are assigned only once.\n\n=head1 Methods\n\nX<|Tutorial,methods>\n\nWhile attributes give objects state, methods give objects behaviors. Back to our C<Task> example. Let's\nignore the C<new> method temporarily; it's a special type of method.\nConsider the second method, C<add-dependency>, which adds a new task to a\ntask's dependency list:\n\n=begin code :skip-test<incomplete code>\nmethod add-dependency(Task $dependency) {\n    push @!dependencies, $dependency;\n}\n=end code\n\nX<|Tutorial,invocant>\nIn many ways, this looks a lot like a C<sub> declaration. However, there are\ntwo important differences. First, declaring this routine as a method adds it\nto the list of methods for the current class, thus any instance of the\nC<Task> class can call it with the C<.> method call operator.\nSecond, a method places its invocant into the special variable C<self>.\n\nThe method itself takes the passed parameter – which must be an instance of\nthe C<Task> class – and C<push>es it onto the invocant's C<@!dependencies>\nattribute.\n\nThe C<perform> method contains the main logic of the dependency handler:\n\n=begin code :skip-test<incomplete code>\nmethod perform() {\n    unless $!done {\n        .perform() for @!dependencies;\n        &!callback();\n        $!done = True;\n    }\n}\n=end code\n\nIt takes no parameters, working instead with the object's attributes. First,\nit checks if the task has already completed by checking the C<$!done>\nattribute. If so, there's nothing to do.\n\nOtherwise, the method performs all of the task's dependencies, using the\nC<for> construct to iterate over all of the items in the C<@!dependencies>\nattribute. This iteration places each item – each a C<Task> object – into\nthe topic variable, C<$_>. Using the C<.> method call operator without\nspecifying an explicit invocant uses the current topic as the invocant.\nThus the iteration construct calls the C<.perform()> method on every C<Task>\nobject in the C<@!dependencies> attribute of the current invocant.\n\nAfter all of the dependencies have completed, it's time to perform the\ncurrent C<Task>'s task by invoking the C<&!callback> attribute directly;\nthis is the purpose of the parentheses. Finally, the method sets the\nC<$!done> attribute to C<True>, so that subsequent invocations of C<perform>\non this object (if this C<Task> is a dependency of another C<Task>, for\nexample) will not repeat the task.\n\n=head2 X<Private methods|Tutorial,FQN>\n\nX<|Tutorial,Private methods>\nJust like attributes, methods can also be private. Private methods are declared\nwith a prefixed exclamation mark. They are called with C<self!> followed by the\nmethod's name. In the following implementation of a C<MP3TagData> class to\nextract L<ID3v1|https://en.wikipedia.org/wiki/ID3> metadata from an mp3 file,\nmethods C<parse-data>, C<can-read-format>, and C<trim-nulls> are private\nmethods while the remaining ones are public methods:\n\n=begin code\nclass MP3TagData {\n    has $.filename where { .IO ~~ :e };\n\n    has Str $.title   is built(False);\n    has Str $.artist  is built(False);\n    has Str $.album   is built(False);\n    has Str $.year    is built(False);\n    has Str $.comment is built(False);\n    has Int $.genre   is built(False);\n    has Int $.track   is built(False);\n    has Str $.version is built(False);\n    has Str $.type    is built(False) = 'ID3';\n\n    submethod TWEAK {\n        with $!filename.IO.open(:r, :bin) -> $fh {\n            $fh.seek(-128, SeekFromEnd);\n            my $tagdata = $fh.read(128);\n            self!parse-data: $tagdata;\n            $fh.close;\n        }\n        else {\n            warn \"Failed to open file.\"\n        }\n    }\n\n    method !parse-data($data) {\n        if self!can-read-format($data) {\n            my $offset = $data.bytes - 128;\n\n            $!title  = self!trim-nulls: $data.subbuf($offset +  3, 30);\n            $!artist = self!trim-nulls: $data.subbuf($offset + 33, 30);\n            $!album  = self!trim-nulls: $data.subbuf($offset + 63, 30);\n            $!year   = self!trim-nulls: $data.subbuf($offset + 93,  4);\n\n            my Int $track-flag = $data.subbuf($offset + 97 + 28, 1).Int;\n            $!track            = $data.subbuf($offset + 97 + 29, 1).Int;\n\n            ($!version, $!comment) = $track-flag == 0 && $!track != 0\n                ?? ('1.1', self!trim-nulls: $data.subbuf($offset + 97, 28))\n                !! ('1.0', self!trim-nulls: $data.subbuf($offset + 97, 30));\n\n            $!genre = $data.subbuf($offset + 97 + 30, 1).Int;\n        }\n    }\n\n    method !can-read-format(Buf $data --> Bool) {\n        self!trim-nulls($data.subbuf(0..2)) eq 'TAG'\n    }\n\n    method !trim-nulls(Buf $data --> Str) {\n        $data.decode('utf-8').subst(/\\x[0000]+/, '')\n    }\n}\n=end code\n\nTo call a private method of another class, the caller has to be trusted by the\ncallee. A trust relationship is declared with\nL<C<trusts>|/language/typesystem#trait_trusts> and the class to be trusted must\nalready be declared. Calling a private method of another class requires an\ninstance of that class and the fully qualified name (FQN) of the method. A trust\nrelationship also allows access to private attributes.\n\n=begin code\nclass B {...}\n\nclass C {\n    trusts B;\n    has $!hidden = 'invisible';\n    method !not-yours () { say 'hidden' }\n    method yours-to-use () {\n        say $!hidden;\n        self!not-yours();\n    }\n}\n\nclass B {\n    method i-am-trusted () {\n        my C $c.=new;\n        $c!C::not-yours();\n    }\n}\n\nC.new.yours-to-use(); # the context of this call is GLOBAL, and not trusted by C\nB.new.i-am-trusted();\n=end code\n\nTrust relationships are not subject to inheritance. To trust the global\nnamespace, the pseudo package C<GLOBAL> can be used.\n\n\n=head1 X<Construction|Tutorial,Constructor>\n\nThe object construction mechanisms described up to now suffice for most use cases. But if one actually needs\nto tweak object construction more than said mechanisms allow, it's good to understand how object construction\nworks in more detail.\n\nRaku is rather more liberal than many languages in the area of\nconstructors. A constructor is anything that returns an instance of the\nclass. Furthermore, constructors are ordinary methods. You inherit a\ndefault constructor named C<new> from the base class L<C<Mu>|/type/Mu>, but you are\nfree to override C<new>, as the Task example does:\n\n=begin code\nmethod new(&callback, *@dependencies) {\n    return self.bless(:&callback, :@dependencies);\n}\n=end code\n\nX<|Tutorial,bless>\n=head2 bless\n\nThe biggest difference between constructors in Raku and constructors in\nlanguages such as C# and Java is that rather than setting up state on a\nsomehow already magically created object, Raku constructors create the\nobject themselves. They do this by calling the\nL<bless|/routine/bless> method, also inherited from L<C<Mu>|/type/Mu>.\nThe C<bless> method expects a set of named parameters to provide the initial\nvalues for each attribute.\n\nThe example's constructor turns positional arguments into named arguments,\nso that the class can provide a nicer constructor for its users. The first\nparameter is the callback (the thing which will execute the task). The rest\nof the parameters are dependent C<Task> instances. The constructor captures\nthese into the C<@dependencies> slurpy array and passes them as named\nparameters to C<bless> (note that C<:&callback> uses the name of the\nvariable – minus the sigil – as the name of the parameter).\nOne should refrain from putting logic other than reformulating the parameters in the constructor, because\nconstructor methods are not recursively called for parent classes. This is different from e.g. Java.\n\nDeclaring C<new> as a C<method> and not as a C<multi method> prevents access to the default constructor.\n+So if you intend to keep the default constructor available, use C<multi method new>.\n\n=head2 X<C<TWEAK>|Tutorial,TWEAK>\n\nAfter C<bless> has initialized the classes attributes from the passed values, it will in turn call C<TWEAK>\nfor each class in the inheritance hierarchy.\nC<TWEAK> gets passed all the arguments passed to bless.\nThis is where custom initialization logic should go.\n\nRemember to always make C<TWEAK> a L<submethod|/type/Submethod> and not a normal C<method>. If in a class hierarchy a class contains a C<TWEAK> method (declared as a C<method> instead of a C<submethod>) that method is inherited to its subclass and will thus be called twice during construction of the subclass!\n\n=head2 X<C<BUILD>|Tutorial,BUILD>\n\nIt is possible to disable the automatic attribute initialization and perform the initialization of\nattributes oneself. To do so one needs to write a custom C<BUILD> submethod. There are several edge cases one\nneeds to be aware of and take into account though. This is detailed in the\nL<Object Construction Reference|/language/objects#Object_construction>. Because of the difficulty of using\nC<BUILD>, it is recommended to only make use of it when none of the other approaches described above suffices.\n\nX<|Tutorial,submethod DESTROY>\n=head1 X<Destruction|Tutorial,DESTROY>\n\nRaku is a garbage collecting language. This means that one usually doesn't need to care about cleaning up objects,\nbecause Raku does so automatically. Raku does not give any guarantees as to when it will\nclean up a given object though. It usually does a cleanup run only if the runtime needs the memory, so we\ncan't rely on when it's going to happen.\n\nTo run custom code when an object is cleaned up one can use the C<DESTROY> submethod. It can for example be used to close handles or supplies or delete temporary files that are no longer\ngoing to be used. As garbage collection can happen at arbitrary points during the runtime of our program, even in the middle of some totally unrelated piece of code in a different thread, we\n must make sure to not assume any context in our C<DESTROY> submethod.\n\n=begin code\nmy $in_destructor = 0;\n\nclass Foo {\n    submethod DESTROY { $in_destructor++ }\n}\n\nmy $foo;\nfor 1 .. 6000 {\n    $foo = Foo.new();\n}\n\nsay \"DESTROY called $in_destructor times\";\n=end code\n\nThis might print something like C<DESTROY called 5701 times> and possibly only kicks\nin after we have stomped over former instances of C<Foo> a few thousand times. We also can't\nrely, on the order of destruction.\n\nSame as C<TWEAK>: Make sure to always declare C<DESTROY> as a C<submethod>.\n\n=head1 Consuming our class\n\nAfter creating a class, you can create instances of the class. Declaring a\ncustom constructor provides a simple way of declaring tasks along with their\ndependencies. To create a single task with no dependencies, write:\n\n=for code :preamble<class Task {}>\nmy $eat = Task.new({ say 'eating dinner. NOM!' });\n\nAn earlier section explained that declaring the class C<Task> installed a\ntype object in the namespace. This type object is a kind of \"empty\ninstance\" of the class, specifically an instance without any state. You can\ncall methods on that instance, as long as they do not try to access any\nstate; C<new> is an example, as it creates a new object rather than\nmodifying or accessing an existing object.\n\nUnfortunately, dinner never magically happens. It has dependent tasks:\n\n=begin code :preamble<class Task {}>\nmy $eat =\n    Task.new({ say 'eating dinner. NOM!' },\n        Task.new({ say 'making dinner' },\n            Task.new({ say 'buying food' },\n                Task.new({ say 'making some money' }),\n                Task.new({ say 'going to the store' })\n            ),\n            Task.new({ say 'cleaning kitchen' })\n        )\n    );\n=end code\n\nNotice how the custom constructor and the sensible use of whitespace makes\ntask dependencies clear.\n\nFinally, the C<perform> method call recursively calls the C<perform> method\non the various other dependencies in order, giving the output:\n\n=begin code :lang<output>\nmaking some money\ngoing to the store\nbuying food\ncleaning kitchen\nmaking dinner\neating dinner. NOM!\n=end code\n\n\n=head2 X<A word on types|Tutorial,type object>\n\nX<|Tutorial,DEFINITE>\nDeclaring a class creates a new I<type object> which, by default, is installed\ninto the current package (just like a variable declared with C<our> scope).\nThis type object is an \"empty instance\" of the class. For example, types such as\nL<C<Int>|/type/Int> and L<C<Str>|/type/Str> refer to the type object of one of the Raku built-in\nclasses. One can call methods on these type objects. So there is nothing special\nwith calling the C<new> method on a type object.\n\nYou can use the C<.DEFINITE> method to find out if what you have is an instance\nor a type object:\n\n=begin code\nsay Int.DEFINITE; # OUTPUT: «False␤» (type object)\nsay 426.DEFINITE; # OUTPUT: «True␤»  (instance)\n\nclass Foo {};\nsay Foo.DEFINITE;     # OUTPUT: «False␤» (type object)\nsay Foo.new.DEFINITE; # OUTPUT: «True␤»  (instance)\n=end code\n\nIn function signatures one can use so called type \"smileys\" to only accept instances\nor type objects:\n\n=begin code\nmulti foo (Int:U) { \"It's a type object!\" }\nmulti foo (Int:D) { \"It's an instance!\"   }\nsay foo Int; # OUTPUT: «It's a type object!␤»\nsay foo 42;  # OUTPUT: «It's an instance!␤»\n=end code\n\n=head1 X<Inheritance|Tutorial,inheritance>\n\nObject Oriented Programming provides the concept of inheritance as one of\nthe mechanisms for code reuse. Raku supports the ability for one\nclass to inherit from one or more classes. When a class inherits from\nanother class it informs the method dispatcher to follow the inheritance\nchain to look for a method to dispatch. This happens both for standard\nmethods defined via the C<method> keyword and for methods generated through\nother means, such as attribute accessors.\n\n=begin code\nclass Employee {\n    has $.salary;\n}\n\nclass Programmer is Employee {\n    has @.known_languages is rw;\n    has $.favorite_editor;\n\n    method code_to_solve( $problem ) {\n        return \"Solving $problem using $.favorite_editor in \"\n        ~ $.known_languages[0];\n    }\n}\n=end code\n\nNow, any object of type Programmer can make use of the methods and accessors\ndefined in the Employee class as though they were from the Programmer class.\n\n=begin code :preamble<class Programmer {}>\nmy $programmer = Programmer.new(\n    salary => 100_000,\n    known_languages => <Raku Perl Erlang C++>,\n    favorite_editor => 'vim'\n);\n\nsay $programmer.code_to_solve('halting problem'),\n    \" will get \\$ {$programmer.salary()}\";\n# OUTPUT: «Solving halting problem using vim in Raku will get $100000␤»\n=end code\n\n=head2 Overriding inherited methods\n\nClasses can override methods and attributes defined by parent\nclasses by defining their own. The example below demonstrates the C<Baker>\nclass overriding the C<Cook>'s C<cook> method.\n\n=begin code :preamble<class Employee {}>\nclass Cook is Employee {\n    has @.utensils  is rw;\n    has @.cookbooks is rw;\n\n    method cook( $food ) {\n        say \"Cooking $food\";\n    }\n\n    method clean_utensils {\n        say \"Cleaning $_\" for @.utensils;\n    }\n}\n\nclass Baker is Cook {\n    method cook( $confection ) {\n        say \"Baking a tasty $confection\";\n    }\n}\n\nmy $cook = Cook.new(\n    utensils  => <spoon ladle knife pan>,\n    cookbooks => 'The Joy of Cooking',\n    salary    => 40000\n);\n\n$cook.cook( 'pizza' );       # OUTPUT: «Cooking pizza␤»\nsay $cook.utensils.raku;     # OUTPUT: «[\"spoon\", \"ladle\", \"knife\", \"pan\"]␤»\nsay $cook.cookbooks.raku;    # OUTPUT: «[\"The Joy of Cooking\"]␤»\nsay $cook.salary;            # OUTPUT: «40000␤»\n\nmy $baker = Baker.new(\n    utensils  => 'self cleaning oven',\n    cookbooks => \"The Baker's Apprentice\",\n    salary    => 50000\n);\n\n$baker.cook('brioche');      # OUTPUT: «Baking a tasty brioche␤»\nsay $baker.utensils.raku;    # OUTPUT: «[\"self cleaning oven\"]␤»\nsay $baker.cookbooks.raku;   # OUTPUT: «[\"The Baker's Apprentice\"]␤»\nsay $baker.salary;           # OUTPUT: «50000␤»\n=end code\n\nBecause the dispatcher will see the C<cook> method on C<Baker> before it\nmoves up to the parent class the C<Baker>'s C<cook> method will be called.\n\nTo access methods in the inheritance chain, use\nL<re-dispatch|/language/functions#Re-dispatching> or the\nL<MOP|/type/Metamodel::ClassHOW#method_can>.\n\n=head2 Multiple inheritance\n\nAs mentioned before, a class can inherit from multiple classes. When a\nclass inherits from multiple classes the dispatcher knows to look at both\nclasses when looking up a method to search for. Raku uses the\nL<C3 algorithm|https://en.wikipedia.org/wiki/Multiple_inheritance> to linearize\nmultiple inheritance hierarchies, which is better than depth-first search\nfor handling multiple inheritance.\n\n=begin code :preamble<class Programmer {}; class Cook {}>\nclass GeekCook is Programmer is Cook {\n    method new( *%params ) {\n        push( %params<cookbooks>, \"Cooking for Geeks\" );\n        return self.bless(|%params);\n    }\n}\n\nmy $geek = GeekCook.new(\n    books           => 'Learning Raku',\n    utensils        => ('stainless steel pot', 'knife', 'calibrated oven'),\n    favorite_editor => 'MacVim',\n    known_languages => <Raku>\n);\n\n$geek.cook('pizza');\n$geek.code_to_solve('P =? NP');\n=end code\n\nNow all the methods made available to the Programmer and the Cook classes\nare available from the GeekCook class.\n\nWhile multiple inheritance is a useful concept to know and occasionally use,\nit is important to understand that there are more useful OOP concepts.  When\nreaching for multiple inheritance it is good practice to consider whether\nthe design wouldn't be better realized by using roles, which are generally\nsafer because they force the class author to explicitly resolve conflicting\nmethod names. For more information on roles, see\nL<Roles|/language/objects#Roles>.\n\n=head2 The X<C<also>|Tutorial,also declarator> declarator\n\nClasses to be inherited from can be listed in the class declaration body by\nprefixing the C<is> trait with C<also>. This also works for the role\ncomposition trait C<does>.\n\n=begin code :preamble<class Programmer {}; class Cook {}>\nclass GeekCook {\n    also is Programmer;\n    also is Cook;\n    # ...\n}\n\nrole A {};\nrole B {};\nclass C {\n    also does A;\n    also does B;\n    # ...\n}\n=end code\n\n=head1 Introspection\n\nIntrospection is the process of gathering information about some objects in\nyour program, not by reading the source code, but by querying the object (or\na controlling object) for some properties, such as its type.\n\nGiven an object C<$o> and the class definitions from the previous sections,\nwe can ask it a few questions:\n\n=begin code :preamble<class Programmer {}; class Employee {}; class GeekCook {}>\nmy Programmer $o .= new;\nif $o ~~ Employee { say \"It's an employee\" };\nsay $o ~~ GeekCook ?? \"It's a geeky cook\" !! \"Not a geeky cook\";\nsay $o.^name;\nsay $o.raku;\nsay $o.^methods(:local)».name.join(', ');\n=end code\n\nThe output might look like this:\n\n=begin code :lang<output>\nIt's an employee\nNot a geeky cook\nProgrammer\nProgrammer.new(known_languages => [\"Perl\", \"Python\", \"Pascal\"],\n        favorite_editor => \"gvim\", salary => \"too small\")\ncode_to_solve, known_languages, favorite_editor\n=end code\n\nThe first two tests each smartmatch against a class name. If the object is\nof that class, or of an inheriting class, it returns C<True>. So the object in\nquestion is of class C<Employee> or one that inherits from it, but not\nC<GeekCook>.\n\nThe call C<$o.^name> tells us the type of C<$o>; in this case C<Programmer>.\n\nC<$o.raku> returns a string that can be executed as Raku code, and\nreproduces the original object C<$o>. While this does not work perfectly in\nall cases, it is very useful for debugging simple objects.\nN<For example, closures cannot easily be reproduced this way; if you\ndon't know what a closure is don't worry. Also current implementations have\nproblems with dumping cyclic data structures this way, but they are expected\nto be handled correctly by C<.raku> at some point.>\n\nThe syntax of calling a method with C<.^> instead of a single dot means that\nit is actually a method call on its I<metaclass>, which is a class managing\nthe properties of the C<Programmer> class – or any other class you are\ninterested in. This metaclass enables other ways of introspection too:\n\n=for code :preamble<my $o>\nsay $o.^attributes.join(', ');\nsay $o.^parents.map({ $_.^name }).join(', ');\n\nFinally C<$o.^name> calls the C<name> method on the metaobject, which\nunsurprisingly returns the class name.\n\nGiven an object C<$mp3> and the C<MP3TagData> class definition from the section\nL<Private methods|/language/classtut#Private_methods>, we can inquire about its\npublic methods with C<.^methods>:\n\n=begin code :skip-test<compile time error>\nmy $mp3 = MP3TagData.new(filename => 'football-head.mp3');\nsay $mp3.^methods(:local);\n# OUTPUT: (TWEAK filename title artist album year comment genre track version\n# type Submethod+{is-hidden-from-backtrace}.new)\n=end code\n\nX<|Syntax,^methods>\nC<$mp3.^methods(:local)> produces a list of L<C<Method>|/type/Method>s that can be\ncalled on C<$mp3>. The C<:local> named argument limits the returned methods to\nthose defined in the C<MP3TagData> class and excludes the inherited methods;\nC<MP3TagData> inherits from no class, so providing C<:local> makes no difference.\n\nX<|Language,find_method>\nTo check if a type object (or an instance object) implements a certain public\nmethod, use the L<C<.^find-method>|/routine/find_method> metamethod, which\nreturns the method object if it exists. Otherwise, it returns L<C<Mu>|/type/Mu>.\n\n=begin code :skip-test<compile time error>\nsay $mp3.^find_method('name');   # OUTPUT: «(Mu)␤»\nsay $mp3.^find_method('artist'); # OUTPUT: «artist␤»\n=end code\n\nX<|Language,private_methods>\nX<|Language,find_private_methods>\nType objects can also be introspected for its private methods. However, public\nand private methods don't use the same APIs, and thus different metamethods\nmust be used: L<C<.^private_methods>|/routine/private_methods> and\nL<C<.^find_private_method>|/routine/find_private_method>.\n\n=begin code :skip-test<compile time error>\nsay $mp3.^private_methods;                     # OUTPUT: «(parse-data can-read-format trim-nulls)␤»\nsay $mp3.^find_private_method('parse-data');   # OUTPUT: «parse-data␤»\nsay $mp3.^find_private_method('remove-nulls'); # OUTPUT: «(Mu)␤»\n=end code\n\nIntrospection is very useful for debugging and for learning the language\nand new libraries. When a function or method returns an object you don't\nknow about, by finding its type with C<.^name>, seeing a construction recipe\nfor it with C<.raku>, and so on, you'll get a good idea of what its return\nvalue is. With C<.^methods>, you can learn what you can do with the class.\n\nBut there are other applications too. For instance, a routine that serializes\nobjects to a bunch of bytes needs to know the attributes of that object,\nwhich it can find out via introspection.\n\n=head2 X<Overriding default gist method|Reference,Overriding default gist method>\n\nSome classes might need their own version of C<gist>, which overrides the terse\nway they are printed when called to provide a default representation of the class.\nFor instance, L<exceptions|/language/exceptions#Uncaught_exceptions> might want\nto write just the C<payload> and not the full object so that it is clearer what\nto see what's happened. However, this isn't limited to exceptions; you can\ndo that with every class:\n\n=begin code\nclass Cook {\n    has @.utensils  is rw;\n    has @.cookbooks is rw;\n\n    method cook( $food ) {\n        return \"Cooking $food\";\n    }\n\n    method clean_utensils {\n        return \"Cleaning $_\" for @.utensils;\n    }\n\n    multi method gist(Cook:U:) { '⚗' ~ self.^name ~ '⚗' }\n    multi method gist(Cook:D:) {\n        '⚗ Cooks with ' ~ @.utensils.join( \" ‣ \") ~ ' using '\n          ~ @.cookbooks.map( \"«\" ~ * ~ \"»\").join( \" and \") }\n}\n\nmy $cook = Cook.new(\n    utensils => <spoon ladle knife pan>,\n    cookbooks => ['Cooking for geeks','The French Chef Cookbook']);\n\nsay Cook.gist; # OUTPUT: «⚗Cook⚗»\nsay $cook.gist; # OUTPUT: «⚗ Cooks with spoon ‣ ladle ‣ knife ‣ pan using «Cooking for geeks» and «The French Chef Cookbook»␤»\n=end code\n\nUsually you will want to define two methods, one for the class and another for\nclass instances; in this case, the class method uses the alembic symbol, and the\ninstance method, defined below it, aggregates the data we have on the cook to show\nit in a narrative way.\n\n=head2 A practical introspection example\n\nWhen one creates a new class, it is sometimes useful to have\ninformative (and safe) introspection accessible more easily as a\npublic method. For example, the following class is used to hold\nattributes for a record row in a CSV spreadsheet with a header row\ndefining its field (attribute) names.\n\n=begin code :solo\nunit class CSV-Record;\n#| Field names and values for a CSV row\nhas $last;\nhas $first;\n#...more fields (attributes)...\n\nmethod fields(--> List) {\n    #| Return a list of the the attribute names (fields)\n    #| of the class instance\n    my @attributes = self.^attributes;\n    my @names;\n    for @attributes -> $a {\n        my $name = $a.name;\n        # The name is prefixed by its sigil and twigil\n        # which we don't want\n        $name ~~ s/\\S\\S//;\n        @names.push: $name;\n    }\n    @names\n}\n\nmethod values(--> List) {\n    #| Return a list of the values for the attributes\n    #| of the class instance\n    my @attributes = self.^attributes;\n    my @values;\n    for @attributes -> $a {\n        # Syntax is not obvious\n        my $value = $a.get_value: self;\n        @values.push: $value;\n    }\n    @values\n}\n=end code\n\nWe use it with a simple CSV file with contents:\n\n=begin code :lang<csv>\nlast,   first #...more fields...\nWall,   Larry\nConway, Damian\n=end code\n\nLoad the first record and show its contents:\n\n=begin code :preamble<my $last; my $first; class CSV-Record {}>\nmy $record = CSV-Record.new: :$last, :$first;\nsay $record.fields.raku; # OUTPUT: «[\"last\", \"first\"]␤»\nsay $record.values.raku; # OUTPUT: «[\"Wall\", \"Larry\"]␤»\n=end code\n\nNote that practically we would have designed the class so that it has\nthe C<fields> list as a constant since its values are the same for all\nclass objects:\n\n=begin code\nconstant @fields = <last first>;\nmethod fields(--> List) {\n    @fields\n}\n=end code\n\nDownsides of using the introspective method for attribute names\ninclude slightly more processing time and power and the probable need\nto remove the sigil and twigil for public presentation.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/community.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"reference\")\n\n=TITLE Community\n\n=SUBTITLE Information about the people working on and using Raku\n\n=head1 Overview\n\n\"Perl 5 was my rewrite of Perl.  I want Perl 6 to be the community's rewrite\nof Perl and of the community.\" - Larry Wall (circa 2000)\n\n\"I am in favor of this change [a community driven renaming from Perl 6 to Raku], because it reflects an ancient wisdom:\n'No one sews a patch of unshrunk cloth on an old garment, for the patch will pull away from\nthe garment, making the tear worse. Neither do people pour new wine into old wineskins.\nIf they do, the skins will burst; the wine will run out and the wineskins will be ruined.\nNo, they pour new wine into new wineskins, and both are preserved.'\" - Larry Wall\n(L<2019|https://github.com/Raku/problem-solving/pull/89#pullrequestreview-300789072>)\n\n=head1 The Raku community\n\n=head2 Online communities\n\nL<IRC|/language/glossary#IRC> communication has played an integral role in the Raku community for more than a decade. There are various channels for Raku-related activities on C<libera.chat>. There are several L<bots|/language/glossary#Bot> to make IRC activity more convenient and fun. You can read about IRC content L<here|https://raku.org/community/> in greater details.\n\nL<The Raku Discord server|https://discord.gg/VzYpdQ6> serves a similar purpose. Thanks to the bridges written by fellow Raku members, it integrates well with the main IRC channels.\n\nL<StackOverflow|https://stackoverflow.com/questions/tagged/raku> is also a great\nresource for asking questions and helping others with their Raku problems and\nchallenges.\n\nMore resources can be found in the\nL<raku.org community page|https://raku.org/community>.\n\n=head2 Offline communities\n\nRaku is also a common topic at\nL<Perl conferences|https://www.perl.org/events.html> and\nL<Perl Monger meetings|https://www.pm.org/>.\nIf you prefer in-person meetings, these are warmly recommended!\n\n=head2 Other resources\n\nL<Camelia|https://raku.org/>, the multi-color butterfly with P 6 in her wings, is the symbol of this diverse and welcoming community.\n\n=head1 Rakudo Weekly\n\nElizabeth Mattijsen usually posts in L<the \"Rakudo Weekly\" blog|https://rakudoweekly.blog/>, a summary of Raku posts, tweets, comments and other interesting tidbits.\nIf you want a single resource to know what is going on in the Raku community now, this is your best resource.\n\nHistorical articles (pre name change) can be found archived on\nL<the \"Perl 6 Weekly\" blog|https://p6weekly.wordpress.com/>.\n\n=head1 Raku Advent calendar\n\nThe Raku community publishes every December an\nL<Advent Calendar|https://raku-advent.blog/>, with Raku tutorials every day until\nChristmas. Previous calendars (pre name change) are\nL<still available|https://perl6advent.wordpress.com/> and relevant.\n\nOrganization and assignment of days is done through the different Raku channels and the\nL<Raku/advent|https://github.com/Raku/advent> repository. If you want to\nparticipate, its organization starts by the end of October, so check out\nthe channels above to keep up to date.\n\n=comment HOW TO WRITE: One topic/point/idea per sentence, one sentence per line - to make diffs & translation easier.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/compilation.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"tutorial\")\n\n=TITLE CompUnits and where to find them\n\n=SUBTITLE How and when Raku modules are compiled, where they are stored, and how to access them in compiled form.\n\n=head1 Overview\n\nPrograms in Raku, as a member of the Perl language family, tend at the top level to be more at the interpreted\nend of the interpreted-compiled spectrum. In this tutorial, an 'interpreted' program means that the source code,\nnamely the human-readable text such as C<say 'hello world';>, is immediately processed by the C<Raku> program into code\nthat can be executed by the computer, with any intermediate stages being stored in memory.\n\nA compiled program, by contrast, is one where the human readable source is first processed into machine-executable code\nand some form of this code is stored 'on disk'. In order to execute the program, the machine-readable version is loaded\ninto memory and then run by the computer.\n\nBoth compiled and interpreted forms have advantages. Briefly, interpreted programs can be 'whipped up' quickly and\nthe source changed quickly. Compiled programs can be complex and take a significant time to pre-process into machine-readable\ncode, but then running them is much faster for a user, who only 'sees' the loading and running time, not the compilation\ntime.\n\nC<Raku> has both paradigms. At the B<top level> a Raku program is interpreted, but code that is separated out into a\nModule will be compiled and the preprocessed version is then loaded when necessary. In practice, Modules that have been\nwritten by the community will only need to be precompiled once by a user when they are 'installed', for example by a\nModule manager such as C<zef>. Then they can be C<use>d  by a developer in her own program. The effect is to make C<Raku>\ntop level programs run quickly.\n\nOne of the great strengths of the C<Perl> family of languages was the ability to integrate a whole ecosystem of modules\nwritten by competent programmers into a small program. This strength was widely copied and is now the norm for all\nlanguages. C<Raku> takes integration even further, making it relatively easy for C<Raku> programs to incorporate system\nlibraries written in other languages into C<Raku> programs, see L<Native Call|/language/nativecall>.\n\nThe experience from C<Perl> and other languages is that the distributive nature of Modules generate several practical difficulties:\n=item a popular module may go through several iterations as the API gets improved, without a guarantee that there is\nbackward compatibility. So, if a program relies on some specific function or return, then there has to be a way to\nspecify the L<C<Version>|/type/Version>.\n=item a module may have been written by Bob, a very competent programmer, who moves on in life, leaving the module unmaintained,\nso Alice takes over. This means that the same module, with the same name, and the same general API may have two\nversions in the wild. Alternatively, two developers (e.g., Alice and Bob) who initially cooperated on a module, then part company about its\ndevelopment. Consequently, it sometimes is necessary for there to be a way to define the B<Auth> of the module.\n=item a module may be enhanced over time and the maintainer keeps two versions up to date, but with different APIs. So it is\nmay be necessary to define the B<API> required.\n=item when developing a new program a developer may want to have the modules written by both Alice and Bob installed locally.\nSo it is not possible simply to have only one version of a module with a single name installed.\n\nC<Raku> enables all of these possibilities, allowing for multiple versions, multiple authorities, and multiple APIs to be present,\ninstalled, and available locally. The way classes and modules can be accessed with specific attributes\nis explained L<elsewhere|/language/typesystem#Versioning,_authorship,_and_API_version.>. This tutorial is about how C<Raku> handles these\npossibilities.\n\n=head1 Introduction\n\nBefore considering the C<Raku> framework, let's have a look at how languages like C<Perl> or C<Python> handle module\ninstallation and loading.\n\n=begin code :lang<text>\nACME::Foo::Bar -> ACME/Foo/Bar.pm\nos.path -> os/path.py\n=end code\n\nIn those languages, module names have a 1:1 relation with filesystem paths.\nWe simply replace the double colons or periods with slashes and add a C<.pm> or C<.py>.\n\nNote that these are relative paths.\nBoth C<Python> and C<Perl> use a list of include paths, to complete these paths.\nIn C<Perl> they are available in the global C<@INC> array.\n\n=begin code :lang<text>\n@INC\n\n/usr/lib/perl5/site_perl/5.22.1/x86_64-linux-thread-multi\n/usr/lib/perl5/site_perl/5.22.1/\n/usr/lib/perl5/vendor_perl/5.22.1/x86_64-linux-thread-multi\n/usr/lib/perl5/vendor_perl/5.22.1/\n/usr/lib/perl5/5.22.1/x86_64-linux-thread-multi\n/usr/lib/perl5/5.22.1/\n=end code\n\nEach of these include directories is checked for whether it contains a relative path determined from the module name.\nIf the shoe fits, the file is loaded.\n\nOf course that's a bit of a simplified version.\nBoth languages support caching compiled versions of modules.\nSo instead of just the C<.pm> file C<Perl> first looks for a C<.pmc> file.\nAnd C<Python> first looks for C<.pyc> files.\n\nModule installation in both cases means mostly copying files into locations determined by the same simple mapping. The\nsystem is easy to explain, easy to understand, simple and robust.\n\n=head2 Why change?\n\nWhy would C<Raku> need another framework? The reason is there are features that those languages lack, namely:\n=item Unicode module names\n=item Modules published under the same names by different authors\n=item Having multiple versions of a module installed\n\nThe set of 26 Latin characters is too restrictive for virtually all real modern languages, including English, which\nhave diacritics for many commonly-used words.\n\nWith a 1:1 relation between module names and filesystem paths, you enter a world of pain\nonce you try to support Unicode on multiple platforms and filesystems.\n\nThen there's sharing module names between multiple authors. This one may or may not work out well in practice.\nI can imagine using it for example for publishing a module with some fix until the original author includes\nthe fix in the \"official\" version.\n\nFinally there's multiple versions. Usually people who need certain versions of modules reach for local::lib or\ncontainers or some home grown workarounds. They all have their own disadvantages. None of them would be necessary\nif applications could just say, hey I need good old, trusty version 2.9 or maybe a bug fix release of that branch.\n\nIf you had any hopes of continuing using the simple name mapping solution, you probably gave up at the\nversioning requirement. Because, how would you find version 3.2 of a module when looking for a 2.9 or higher?\n\nPopular ideas included collecting information about installed modules in JSON files but when those turned out to be\ntoe-nail growing slow, text files were replace by putting the metadata into SQLite databases.\nHowever, these ideas can be easily shot down by introducing another requirement: distribution packages.\n\nPackages for Linux distributions are mostly just archives containing some files plus some metadata.\nIdeally the process of installing such a package means just unpacking the files and updating the central package database.\nUninstalling means deleting the files installed this way and again updating the package database.\nChanging existing files on install and uninstall makes packagers' lives much harder, so we really want to avoid that.\nAlso the names of the installed files may not depend on what was previously installed.\nWe must know at the time of packaging what the names are going to be.\n\n=head2 Long names\n\n=begin code :lang<text>\nFoo::Bar:auth<cpan:nine>:ver<0.3>:api<1>\n=end code\n\nStep 0 in getting us back out of this mess is to define a long name.\nA full module name in C<Raku> consists of the short-name, auth, version and API\n\nAt the same time, the thing you install is usually not a single module but a distribution which probably contains one or more modules.\nDistribution names work just the same way as module names.\nIndeed, distributions often will just be called after their main module.\nAn important property of distributions is that they are immutable.\nC«Foo:auth<cpan:nine>:ver<0.3>:api<1>» will always be the name for exactly the same code.\n\n=head2 $*REPO\n\nIn C<Perl> and C<Python> you deal with include paths pointing to filesystem directories.\nIn C<Raku> we call such directories \"repositories\" and each of these repositories is governed by an object that does the\nL<C<CompUnit::Repository>|/type/CompUnit::Repository> role.\nInstead of an B<C<@INC>> array, there's the C<$*REPO> variable.\nIt contains a single repository object.\nThis object has a B<next-repo> attribute that may contain another repository.\nIn other words: repositories are managed as a I<linked list>.\nThe important difference to the traditional array is, that when going through the list, each object has a say in whether\nto pass along a request to the next-repo or not.\nC<Raku> sets up a standard set of repositories, \"core\", \"vendor\", and \"site\".\nIn addition, there is a \"home\" repository for the current user.\n\nRepositories must implement the C<need> method.\nA C<use> or C<require> statement in C<Raku> code is basically translated to a call to B<C<$*REPO>>'s C<need> method.\nThis method may in turn delegate the request to the next-repo.\n\n=begin code :preamble<class CompUnit::Store {};> :method\nrole CompUnit::Repository {\n    has CompUnit::Repository $.next-repo is rw;\n\n    method need(CompUnit::DependencySpecification $spec,\n                CompUnit::PrecompilationRepository $precomp,\n                CompUnit::Store :@precomp-stores\n                --> CompUnit:D\n                )\n        { ... }\n    method loaded(\n                --> Iterable\n                )\n        { ... }\n\n    method id( --> Str )\n        { ... }\n}\n=end code\n\n=head2 Repositories\n\nRakudo comes with several classes that can be used for repositories.\nThe most important ones are L<C<CompUnit::Repository::FileSystem>|/type/CompUnit::Repository::FileSystem> and L<C<CompUnit::Repository::Installation>|/type/CompUnit::Repository::Installation>.\nThe FileSystem repo is meant to be used during module development and actually works just like C<Perl> when\nlooking for a module.\nIt doesn't support versions or C<auth>s and simply maps the short-name to a filesystem path.\n\nThe Installation repository is where the real smarts are. When requesting a module, you will usually either do it\nvia its exact long name, or you say something along the lines of \"give me a module that matches this filter.\"\nSuch a filter is given by way of a C<CompUnit::DependencySpecification> object which has fields for\n=item short-name,\n=item auth-matcher,\n=item version-matcher and\n=item api-matcher.\n\nWhen looking through candidates, the Installation repository will smartmatch a module's long name against this\nDependencySpecification or rather the individual fields against the individual matchers.\nThus a matcher may be some concrete value, a version range, or even a regex (though an arbitrary regex, such as C<.*>,\nwould not produce a useful result, but something like C<3.20.1+> will only find candidates higher than 3.20.1).\n\nLoading the metadata of all installed distributions would be prohibitively slow. The current implementation of\nthe C<Raku> framework uses\nthe filesystem as a kind of database. However, another implementation may use another strategy. The following description\nshows how one implementation works and is included here to illustrate what is happening.\n\nWe store not only a distribution's files but also create indices for speeding up lookups.\nOne of these indices comes in the form of directories named after the short-name of installed modules.\nHowever most of the filesystems in common use today cannot handle Unicode names, so we cannot just use\nmodule names directly.\nThis is where the now infamous SHA-1 hashes enter the game.\nThe directory names are the ASCII encoded SHA-1 hashes of the UTF-8 encoded module short-names.\n\nIn these directories we find one file per distribution that contains a module with a matching short name.\nThese files again contain the ID of the dist and the other fields that make up the long name: auth, version, and api.\nSo by reading these files we have a usually short list of auth-version-api triplets which we can match against our\nDependencySpecification.\nWe end up with the winning distribution's ID, which we use to look up the metadata, stored in a JSON encoded file.\nThis metadata contains the name of the file in the sources/ directory containing the requested module's code.\nThis is what we can load.\n\nFinding names for source files is again a bit tricky, as there's still the Unicode issue and in addition the same\nrelative file names may be used by different installed distributions (think versions).\nSo for now at least, we use SHA-1 hashes of the long-names.\n\n=head2 Resources\n\n=begin code :lang<text>\n%?RESOURCES\n%?RESOURCES<libraries/p5helper>\n%?RESOURCES<icons/foo.png>\n%?RESOURCES<schema.sql>\n\nFoo\n|___ lib\n|     |____ Foo.rakumod\n|\n|___ resources\n      |___ schema.sql\n      |\n      |___ libraries\n            |____ p5helper\n            |        |___\n            |___ icons\n                     |___ foo.png\n=end code\n\nIt's not only source files that are stored and found this way.\nDistributions may also contain arbitrary resource files.\nThese could be images, language files or shared libraries that are compiled on installation.\nThey can be accessed from within the module through the C<%?RESOURCES> hash.\n\nAs long as you stick to the standard layout conventions for distributions, this even works during development\nwithout installing anything.\n\nA nice result of this architecture is that it's fairly easy to create special purpose repositories.\n\n=head2 Dependencies\n\nLuckily precompilation at least works quite well in most cases. Yet it comes with its own set of challenges.\nLoading a single module is easy.\nThe fun starts when a module has dependencies and those dependencies have again dependencies of their own.\n\nWhen loading a precompiled file in C<Raku> we need to load the precompiled files of all its dependencies, too.\nAnd those dependencies B<must> be precompiled, we cannot load them from source files.\nEven worse, the precomp files of the dependencies B<must> be exactly the same files we used for precompiling our\nmodule in the first place.\n\nTo top it off, precompiled files work only with the exact C<Raku> binary, that was used for compilation.\n\nAll of that would still be quite manageable if it weren't for an additional requirement: as a user you expect a new\nversion of a module you just installed to be actually used, don't you?\n\nIn other words: if you upgrade a dependency of a precompiled module, we have to detect this and precompile the module\nagain with the new dependency.\n\n=head2 Precomp stores\n\nNow remember that while we have a standard repository chain, the user may prepend additional repositories by way of\nC<-I> on the command line or \"use lib\" in the code.\n\nThese repositories may contain the dependencies of precompiled modules.\n\nOur first solution to this riddle was that each repository gets its own precomp store where precompiled files are stored.\nWe only ever load precomp files from the precomp store of the very first repository in the chain because this is the\nonly repository that has direct or at least indirect access to all the candidates.\n\nIf this repository is a FileSystem repository, we create a precomp store in a C<.precomp> directory.\n\nWhile being the safe option, this has the consequence that whenever you use a new repository, we will start out\nwithout access to precompiled files.\n\nInstead, we will precompile the modules used when they are first loaded.\n\n=head2 Credit\n\nThis tutorial is based on a C<niner> L<talk|http://niner.name/talks/A%20look%20behind%20the%20curtains%20-%20module%20loading%20in%20Perl%206/>.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/concurrency.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"tutorial\")\n\n=TITLE Concurrency\n\n=SUBTITLE Concurrency and asynchronous programming\n\nIn common with most modern programming languages, Raku is designed to support\nparallelism, asynchronicity and\nL<concurrency|https://en.wikipedia.org/wiki/Concurrent_computing>.  Parallelism\nis about doing multiple things at once. I<Asynchronous programming>, which is\nsometimes called event driven or reactive programming, is about supporting\nchanges in the program flow caused by events triggered elsewhere in the program.\nFinally, concurrency is about the coordination of access and modification of\nsome shared resources.\n\nThe aim of the Raku concurrency design is to provide a high-level,\ncomposable and consistent interface, regardless of how a virtual machine\nmay implement it for a particular operating system, through layers of\nfacilities as described below.\n\n=begin comment\n\nI'm not quite clear which specific features should be included below\n\nhyper-operators, autothreading junctions?\n\n=end comment\n\nAdditionally, certain Raku features may implicitly operate in an asynchronous\nfashion, so in order to ensure predictable interoperation with these features,\nuser code should, where possible, avoid the lower level concurrency APIs (e.g.,\nL<C<Thread>|/type/Thread> and L<C<Scheduler>|/type/Scheduler>) and use the\nhigher-level interfaces.\n\n=head1 High-level APIs\n\nX<|Other languages,Futures>\n=head2 Promises\n\nA L<C<Promise>|/type/Promise> (also called I<future> in other programming\nenvironments) encapsulates the result of a computation that may not\nhave completed or even started at the time the promise is obtained.\nA L<C<Promise>|/type/Promise> starts from a C<Planned> status and can result in either a\nC<Kept> status, meaning the promise has been successfully completed, or\na C<Broken> status meaning that the promise has failed.\nUsually this is much of the functionality that user code needs to operate\nin a concurrent or asynchronous manner.\n\n=begin code\nmy $p1 = Promise.new;\nsay $p1.status;         # OUTPUT: «Planned␤»\n$p1.keep('Result');\nsay $p1.status;         # OUTPUT: «Kept␤»\nsay $p1.result;         # OUTPUT: «Result␤»\n                        # (since it has been kept, a result is available!)\n\nmy $p2 = Promise.new;\n$p2.break('oh no');\nsay $p2.status;         # OUTPUT: «Broken␤»\nsay $p2.result;         # dies, because the promise has been broken\nCATCH { default { say .^name, ': ', .Str } };\n# OUTPUT: «X::AdHoc+{X::Promise::Broken}: oh no␤»\n=end code\n\nPromises gain much of their power by being composable, for example by\nchaining, usually by the L<then|/type/Promise#method_then> method:\n\n    my $promise1 = Promise.new();\n    my $promise2 = $promise1.then(\n        -> $v { say $v.result; \"Second Result\" }\n    );\n    $promise1.keep(\"First Result\");\n    say $promise2.result;   # OUTPUT: «First Result␤Second Result␤»\n\nHere the L<then|/type/Promise#method_then> method schedules code to be executed\nwhen the first L<C<Promise>|/type/Promise> is kept or broken, itself returning a\nnew L<C<Promise>|/type/Promise> which will be kept with the result of the code when\nit is executed (or broken if the code fails).  C<keep> changes the status of the\npromise to C<Kept> setting the result to the positional argument. C<result>\nblocks the current thread of execution until the promise is kept or broken, if\nit was kept then it will return the result (that is the value passed to\nC<keep>), otherwise it will throw an exception based on the value passed to\nC<break>. The latter behavior is illustrated with:\n\n    my $promise1 = Promise.new();\n    my $promise2 = $promise1.then(-> $v { say \"Handled but : \"; say $v.result});\n    $promise1.break(\"First Result\");\n    try $promise2.result;\n    say $promise2.cause;        # OUTPUT: «Handled but : ␤First Result␤»\n\nHere the C<break> will cause the code block of the C<then> to throw an exception\nwhen it calls the C<result> method on the original promise that was passed as an\nargument, which will subsequently cause the second promise to be broken, raising\nan exception in turn when its result is taken. The actual\nL<C<Exception>|/type/Exception> object will then be available from C<cause>. If the\npromise had not been broken C<cause> would raise an\nL<C<X::Promise::CauseOnlyValidOnBroken>|/type/X::Promise::CauseOnlyValidOnBroken> exception.\n\nA L<C<Promise>|/type/Promise> can also be scheduled to be automatically kept at a\nfuture time:\n\n    my $promise1 = Promise.in(5);\n    my $promise2 = $promise1.then(-> $v { say $v.status; 'Second Result' });\n    say $promise2.result;\n\nThe L<method in|/type/Promise#method_in> creates a new promise and\nschedules a new task to call C<keep> on it no earlier than the supplied\nnumber of seconds, returning the new L<C<Promise>|/type/Promise> object.\n\nA very frequent use of promises is to run a piece of code, and keep the\npromise once it returns successfully, or break it when the code dies.\nThe L<start method|/type/Promise#method_start> provides a shortcut\nfor that:\n\n    my $promise = Promise.start(\n        { my $i = 0; for 1 .. 10 { $i += $_ }; $i}\n    );\n    say $promise.result;    # OUTPUT: «55␤»\n\nHere the C<result> of the promise returned is the value returned from\nthe code.  Similarly if the code fails (and the promise is thus broken),\nthen C<cause> will be the L<C<Exception>|/type/Exception> object that was thrown:\n\n    my $promise = Promise.start({ die \"Broken Promise\" });\n    try $promise.result;\n    say $promise.cause;\n\nThis is considered to be such a commonly required pattern that it is\nalso provided as a keyword:\n\n    my $promise = start {\n        my $i = 0;\n        for 1 .. 10 {\n            $i += $_\n        }\n        $i\n    }\n    my $result = await $promise;\n    say $result;\n\nThe subroutine L<await|/type/Promise#sub_await> is almost equivalent to\ncalling C<result> on the promise object returned by C<start> but it will\nalso take a list of promises and return the result of each:\n\n    my $p1 = start {\n        my $i = 0;\n        for 1 .. 10 {\n            $i += $_\n        }\n        $i\n    };\n    my $p2 = start {\n        my $i = 0;\n        for 1 .. 10 {\n            $i -= $_\n        }\n        $i\n    };\n    my @result = await $p1, $p2;\n    say @result;            # OUTPUT: «[55 -55]␤»\n\nIn addition to C<await>, two class methods combine several\nL<C<Promise>|/type/Promise> objects into a new promise: C<allof> returns a promise\nthat is kept when all the original promises are kept or broken:\n\n    my $promise = Promise.allof(\n        Promise.in(2),\n        Promise.in(3)\n    );\n\n    await $promise;\n    say \"All done\"; # Should be not much more than three seconds later\n\nAnd C<anyof> returns a new promise that will be kept when any of the\noriginal promises is kept or broken:\n\n    my $promise = Promise.anyof(\n        Promise.in(3),\n        Promise.in(8600)\n    );\n\n    await $promise;\n    say \"All done\"; # Should be about 3 seconds later\n\nUnlike C<await> however the results of the original kept promises are not\navailable without referring to the original, so these are more useful\nwhen the completion or otherwise of the tasks is more important to the\nconsumer than the actual results, or when the results have been collected\nby other means.  You may, for example, want to create a dependent Promise\nthat will examine each of the original promises:\n\n    my @promises;\n    for 1..5 -> $t {\n        push @promises, start {\n            sleep $t;\n            Bool.pick;\n        };\n    }\n    say await Promise.allof(@promises).then({ so all(@promises>>.result) });\n\nWhich will give True if all of the promises were kept with True, False\notherwise.\n\nIf you are creating a promise that you intend to keep or break yourself\nthen you probably don't want any code that might receive the promise to\ninadvertently (or otherwise) keep or break the promise before you do.\nFor this purpose there is the L<method vow|/type/Promise#method_vow>, which\nreturns a Vow object which becomes the only mechanism by which the promise\ncan be kept or broken.  If an attempt to keep or break the Promise is made\ndirectly then the exception L<C<X::Promise::Vowed>|/type/X::Promise::Vowed> will be thrown, as long\nas the vow object is kept private, the status of the promise is safe:\n\n    sub get_promise {\n        my $promise = Promise.new;\n        my $vow = $promise.vow;\n        Promise.in(10).then({$vow.keep});\n        $promise;\n    }\n\n    my $promise = get_promise();\n\n    # Will throw an exception\n    # \"Access denied to keep/break this Promise; already vowed\"\n    $promise.keep;\n    CATCH { default { say .^name, ': ', .Str } };\n    # OUTPUT: «X::Promise::Vowed: Access denied to keep/break this Promise; already vowed␤»\n\nThe methods that return a promise that will be kept or broken\nautomatically such as C<in> or C<start> will do this, so it is not\nnecessary to do it for these.\n\n=head2 Supplies\n\nA L<C<Supply>|/type/Supply> is an asynchronous data streaming mechanism that can be\nconsumed by one or more consumers simultaneously in a manner similar to\n\"events\" in other programming languages and can be seen as enabling\nI<event driven> or reactive designs.\n\nAt its simplest, a L<C<Supply>|/type/Supply> is a message stream that can have\nmultiple subscribers created with the method C<tap> on to which data items can\nbe placed with C<emit>.\n\nThere are two types of Supplies: C<live> and C<on demand>. A C<live>\nsupply is like a TV broadcast: those who tune in don't get previously emitted\nvalues. An C<on-demand> broadcast is like a video streaming service:\neveryone who starts streaming a movie (taps a L<C<Supply>|/type/Supply>),\nalways starts it from the beginning (gets all the values),\nregardless of how many people are watching it right now.\n\nNote that no\nhistory is kept for C<on-demand> supplies, instead, the C<supply> block is run\nfor each tap of the supply.\n\nA C<live> L<C<Supply>|/type/Supply>\nis created by the L<C<Supplier>|/type/Supplier> factory, each emitted value is passed to\nall the active tappers as they are added:\n\n    my $supplier = Supplier.new;\n    my $supply   = $supplier.Supply;\n\n    $supply.tap( -> $v { say $v });\n\n    for 1 .. 10 {\n        $supplier.emit($_);\n    }\n\nNote that the C<tap> is called on a L<C<Supply>|/type/Supply> object created by the\nL<C<Supplier>|/type/Supplier> and new values are emitted on the\nL<C<Supplier>|/type/Supplier>.\n\nX<|Reference,supply (on-demand)>\nAn C<on-demand> L<C<Supply>|/type/Supply> is created by the C<supply> keyword:\n\n    my $supply = supply {\n        for 1 .. 10 {\n            emit($_);\n        }\n    }\n    $supply.tap( -> $v { say $v });\n\nIn this case the code in the supply block is executed every time the\nL<C<Supply>|/type/Supply> returned by C<supply> is tapped, as demonstrated by:\n\n    my $supply = supply {\n        for 1 .. 10 {\n            emit($_);\n        }\n    }\n    $supply.tap( -> $v { say \"First : $v\" });\n    $supply.tap( -> $v { say \"Second : $v\" });\n\nThe C<tap> method returns a L<C<Tap>|/type/Tap> object which can be used to obtain\ninformation about the tap and also to turn it off when we are no longer\ninterested in the events:\n\n    my $supplier = Supplier.new;\n    my $supply   = $supplier.Supply;\n\n    my $tap = $supply.tap( -> $v { say $v });\n\n    $supplier.emit(\"OK\");\n    $tap.close;\n    $supplier.emit(\"Won't trigger the tap\");\n\nCalling C<done> on the supply object calls the C<done> callback that\nmay be specified for any taps, but does not prevent any further events\nbeing emitted to the stream, or taps receiving them.\n\nThe method C<interval> returns a new C<on-demand> supply which periodically\nemits a new event at the specified interval. The data that is emitted\nis an integer starting at 0 that is incremented for each event. The\nfollowing code outputs 0 .. 5 :\n\n\n    my $supply = Supply.interval(2);\n    $supply.tap(-> $v { say $v });\n    sleep 10;\n\nA second argument can be supplied to C<interval> which specifies a delay\nin seconds before the first event is fired. Each tap of a supply created\nby C<interval> has its own sequence starting from 0, as illustrated by\nthe following:\n\n    my $supply = Supply.interval(2);\n    $supply.tap(-> $v { say \"First $v\" });\n    sleep 6;\n    $supply.tap(-> $v { say \"Second $v\"});\n    sleep 10;\n\nA live L<C<Supply>|/type/Supply> that keeps values until first tapped can be created with\nL<C<Supplier::Preserving>|/type/Supplier::Preserving>.\n\n\n=head3 X<C<whenever>|Control flow,whenever>\n\nThe C<whenever> keyword can be used in supply blocks or in react\nblocks. From the 6.d version, it needs to be used within the lexical scope of\nthem.  It introduces a block of code that will be run when prompted by an\nasynchronous event that it specifies - that could be a L<C<Supply>|/type/Supply>, a\nL<C<Channel>|/type/Channel>, a L<C<Promise>|/type/Promise> or an\nL<C<Iterable>|/type/Iterable>.\n\nPlease note that one should keep the code inside the C<whenever> as small as\npossible, as only one C<whenever> block will be executed at any time.  One can\nuse a C<start> block inside the C<whenever> block to run longer running code.\n\nIn this example we are watching two supplies.\n\n=begin code\nmy $bread-supplier = Supplier.new;\nmy $vegetable-supplier = Supplier.new;\n\nmy $supply = supply {\n    whenever $bread-supplier.Supply {\n        emit(\"We've got bread: \" ~ $_);\n    };\n    whenever $vegetable-supplier.Supply {\n        emit(\"We've got a vegetable: \" ~ $_);\n    };\n}\n$supply.tap( -> $v { say \"$v\" });\n\n$vegetable-supplier.emit(\"Radish\");   # OUTPUT: «We've got a vegetable: Radish␤»\n$bread-supplier.emit(\"Thick sliced\"); # OUTPUT: «We've got bread: Thick sliced␤»\n$vegetable-supplier.emit(\"Lettuce\");  # OUTPUT: «We've got a vegetable: Lettuce␤»\n=end code\n\n\n=head3 X<C<react>|Control flow,react>\n\nThe C<react> keyword introduces a block of code containing one or more\nC<whenever> keywords to watch asynchronous events. The main difference between a\nsupply block and a react block is that the code in a react block runs where it\nappears in the code flow, whereas a supply block has to be tapped before it does\nanything.\n\nAnother difference is that a supply block can be used without the C<whenever>\nkeyword, but a react block requires at least one C<whenever> to be of any real\nuse.\n\n    react {\n        whenever Supply.interval(2) -> $v {\n            say $v;\n            done() if $v == 4;\n        }\n    }\n\nHere the C<whenever> keyword uses L«C<.act>|/type/Supply#method_act» to create a\ntap on the L<C<Supply>|/type/Supply> from the provided block. The C<react> block is\nexited when C<done()> is called in one of the taps.\n\nAn C<on-demand> L<C<Supply>|/type/Supply> can also be created from a list of values\nthat will be emitted in turn, thus the first C<on-demand> example could be\nwritten as:\n\n    react {\n        whenever Supply.from-list(1..10) -> $v {\n            say $v;\n        }\n    }\n\n=head3 Transforming supplies\n\nAn existing supply object can be filtered or transformed, using the methods\nC<grep> and C<map> respectively, to create a new supply in a manner like\nthe similarly named list methods: C<grep> returns a supply such that only\nthose events emitted on the source stream for which the C<grep> condition\nis true is emitted on the second supply:\n\n    my $supplier = Supplier.new;\n    my $supply = $supplier.Supply;\n    $supply.tap(-> $v { say \"Original : $v\" });\n    my $odd_supply = $supply.grep({ $_ % 2 });\n    $odd_supply.tap(-> $v { say \"Odd : $v\" });\n    my $even_supply = $supply.grep({ not $_ % 2 });\n    $even_supply.tap(-> $v { say \"Even : $v\" });\n    for 0 .. 10 {\n        $supplier.emit($_);\n    }\n\nC<map> returns a new supply such that for each item emitted to the\noriginal supply a new item which is the result of the expression passed\nto the C<map> is emitted:\n\n     my $supplier = Supplier.new;\n     my $supply = $supplier.Supply;\n     $supply.tap(-> $v { say \"Original : $v\" });\n     my $half_supply = $supply.map({ $_ / 2 });\n     $half_supply.tap(-> $v { say \"Half : $v\" });\n     for 0 .. 10 {\n         $supplier.emit($_);\n     }\n\n=head3 Ending a supply\n\nIf you need to have an action that runs when the supply finishes, you can do so\nby setting the C<done> and C<quit> options in the call to C<tap>:\n\n    =begin code :preamble<my $supply; class X::MyApp::Error is Exception {}>\n    $supply.tap: { ... },\n        done => { say 'Job is done.' },\n        quit => {\n            when X::MyApp::Error { say \"App Error: \", $_.message }\n        };\n    =end code\n\nThe C<quit> block works very similar to a C<CATCH>. If the exception is marked\nas seen by a C<when> or C<default> block, the exception is caught and handled.\nOtherwise, the exception continues to up the call tree (i.e., the same behavior\nas when C<quit> is not set).\n\n=head3 Phasers in a supply or react block\n\nIf you are using the C<react> or C<supply> block syntax with C<whenever>, you\ncan add phasers within your C<whenever> blocks to handle the C<done> and C<quit>\nmessages from the tapped supply:\n\n    =begin code :preamble<my $supply; class X::MyApp::Error is Exception {}>\n    react {\n        whenever $supply {\n            ...; # your usual supply tap code here\n            LAST { say 'Job is done.' }\n            QUIT { when X::MyApp::Error { say \"App Error: \", $_.message } }\n        }\n    }\n    =end code\n\nThe behavior here is the same as setting C<done> and C<quit> on C<tap>.\n\n=head2 Channels\n\nA L<C<Channel>|/type/Channel> is a thread-safe queue that can have multiple readers and\nwriters that could be considered to be similar in operation to a \"fifo\" or\nnamed pipe except it does not enable inter-process communication. It should\nbe noted that, being a true queue, each value sent to the L<C<Channel>|/type/Channel> will only\nbe available to a single reader on a first read, first served basis: if you\nwant multiple readers to be able to receive every item sent you probably\nwant to consider a L<C<Supply>|/type/Supply>.\n\nAn item is queued onto the L<C<Channel>|/type/Channel> with the\nL<method send|/type/Channel#method_send>, and the L<method\nreceive|/type/Channel#method_receive> removes an item from the queue\nand returns it, blocking until a new item is sent if the queue is empty:\n\n    my $channel = Channel.new;\n    $channel.send('Channel One');\n    say $channel.receive;  # OUTPUT: «Channel One␤»\n\nIf the channel has been closed with the L<method\nclose|/type/Channel#method_close> then any C<send> will cause the\nexception L<C<X::Channel::SendOnClosed>|/type/X::Channel::SendOnClosed> to be thrown, and a C<receive>\nwill throw an L<C<X::Channel::ReceiveOnClosed>|/type/X::Channel::ReceiveOnClosed>.\n\nThe L<method list|/type/Channel#method_list> returns all the items on\nthe L<C<Channel>|/type/Channel> and will block until further items are queued unless the\nchannel is closed:\n\n    my $channel = Channel.new;\n    await (^10).map: -> $r {\n        start {\n            sleep $r;\n            $channel.send($r);\n        }\n    }\n    $channel.close;\n    for $channel.list -> $r {\n        say $r;\n    }\n\nThere is also the non-blocking L<method poll|/type/Channel#method_poll>\nthat returns an available item from the channel or L<C<Nil>|/type/Nil> if there\nis no item or the channel is closed.  This does mean that the\nchannel must be checked to determine whether it is closed:\n\n    my $c = Channel.new;\n\n    # Start three Promises that sleep for 1..3 seconds, and then\n    # send a value to our Channel\n    ^3 .map: -> $v {\n        start {\n            sleep 3 - $v;\n            $c.send: \"$v from thread {$*THREAD.id}\";\n        }\n    }\n\n    # Wait 3 seconds before closing the channel\n    Promise.in(3).then: { $c.close }\n\n    # Continuously loop and poll the channel, until it's closed\n    my $is-closed = $c.closed;\n    loop {\n        if $c.poll -> $item {\n            say \"$item received after {now - INIT now} seconds\";\n        }\n        elsif $is-closed {\n            last;\n        }\n\n        say 'Doing some unrelated things...';\n        sleep .6;\n    }\n\n    # Doing some unrelated things...\n    # Doing some unrelated things...\n    # 2 from thread 5 received after 1.2063182 seconds\n    # Doing some unrelated things...\n    # Doing some unrelated things...\n    # 1 from thread 4 received after 2.41117376 seconds\n    # Doing some unrelated things...\n    # 0 from thread 3 received after 3.01364461 seconds\n    # Doing some unrelated things...\n\nThe L<method closed|/type/Channel#method_closed> returns a L<C<Promise>|/type/Promise> that\nwill be kept (and consequently will evaluate to True in a Boolean context)\nwhen the channel is closed.\n\nThe C<.poll> method can be used in combination with C<.receive> method, as a\ncaching mechanism where lack of value returned by C<.poll> is a signal that\nmore values need to be fetched and loaded into the channel:\n\n    =begin code :preamble<my $c; sub slowly-fetch-a-thing {};>\n    sub get-value {\n        return $c.poll // do { start replenish-cache; $c.receive };\n    }\n\n    sub replenish-cache {\n        for ^20 {\n            $c.send: $_ for slowly-fetch-a-thing();\n        }\n    }\n    =end code\n\nChannels can be used in place of the L<C<Supply>|/type/Supply> in the C<whenever> of a\nC<react> block described earlier:\n\n    =begin code\n    my $channel = Channel.new;\n    my $p = start {\n        react {\n            whenever $channel {\n                say $_;\n            }\n        }\n    }\n\n    await (^10).map: -> $r {\n        start {\n            sleep $r;\n            $channel.send($r);\n        }\n    }\n\n    $channel.close;\n    await $p;\n    =end code\n\nIt is also possible to obtain a L<C<Channel>|/type/Channel> from a L<C<Supply>|/type/Supply> using the\nL<Channel method|/type/Supply#method_Channel> which returns a L<C<Channel>|/type/Channel>\nwhich is fed by a C<tap> on the L<C<Supply>|/type/Supply>:\n\n    my $supplier = Supplier.new;\n    my $supply   = $supplier.Supply;\n    my $channel = $supply.Channel;\n\n    my $p = start {\n        react  {\n            whenever $channel -> $item {\n                say \"via Channel: $item\";\n            }\n        }\n    }\n\n    await (^10).map: -> $r {\n        start {\n            sleep $r;\n            $supplier.emit($r);\n        }\n    }\n\n    $supplier.done;\n    await $p;\n\nL<C<Channel>|/type/Channel> will return a different L<C<Channel>|/type/Channel> fed with the same data\neach time it is called.  This could be used, for instance, to fan-out a\nL<C<Supply>|/type/Supply> to one or more L<C<Channel>|/type/Channel>s to provide for different interfaces\nin a program.\n\n=head2 Proc::Async\n\nL<C<Proc::Async>|/type/Proc::Async> builds on the facilities described to run and interact with\nan external program asynchronously:\n\n    my $proc = Proc::Async.new('echo', 'foo', 'bar');\n\n    $proc.stdout.tap(-> $v { print \"Output: $v\" });\n    $proc.stderr.tap(-> $v { print \"Error:  $v\" });\n\n    say \"Starting...\";\n    my $promise = $proc.start;\n\n    await $promise;\n    say \"Done.\";\n\n    # Output:\n    # Starting...\n    # Output: foo bar\n    # Done.\n\nThe path to the command as well as any arguments to the command are\nsupplied to the constructor. The command will not be executed until\nL<start|/type/Proc::Async#method_start> is called, which will return\na L<C<Promise>|/type/Promise> that will be kept when the program exits. The standard\noutput and standard error of the program are available as L<C<Supply>|/type/Supply>\nobjects from the methods L<stdout|/type/Proc::Async#method_stdout>\nand L<stderr|/type/Proc::Async#method_stderr> respectively which can be\ntapped as required.\n\nIf you want to write to the standard input of the program\nyou can supply the C<:w> adverb to the constructor and use\nthe methods L<write|/type/Proc::Async#method_write>,\nL<print|/type/Proc::Async#method_print> or\nL<say|/type/Proc::Async#method_say> to write to the opened pipe once\nthe program has been started:\n\n    my $proc = Proc::Async.new(:w, 'grep', 'foo');\n\n    $proc.stdout.tap(-> $v { print \"Output: $v\" });\n\n    say \"Starting...\";\n    my $promise = $proc.start;\n\n    $proc.say(\"this line has foo\");\n    $proc.say(\"this one doesn't\");\n\n    $proc.close-stdin;\n    await $promise;\n    say \"Done.\";\n\n    # Output:\n    # Starting...\n    # Output: this line has foo\n    # Done.\n\nSome programs (such as C<grep> without a file argument in this\nexample, ) won't exit until their standard input is closed so\nL<close-stdin|/type/Proc::Async#method_close-stdin> can be called when\nyou are finished writing to allow the L<C<Promise>|/type/Promise> returned by C<start>\nto be kept.\n\n=head1 Low-level APIs\n\n=head2 Threads\n\nThe lowest level interface for concurrency is provided by L<C<Thread>|/type/Thread>. A\nthread can be thought of as a piece of code that may eventually be run\non a processor, the arrangement for which is made almost entirely by the\nvirtual machine and/or operating system. Threads should be considered,\nfor all intents, largely un-managed and their direct use should be\navoided in user code.\n\nA thread can either be created and then actually run later:\n\n    my $thread = Thread.new(code => { for  1 .. 10  -> $v { say $v }});\n    # ...\n    $thread.run;\n\nOr can be created and run at a single invocation:\n\n    my $thread = Thread.start({ for  1 .. 10  -> $v { say $v }});\n\nIn both cases the completion of the code encapsulated by the L<C<Thread>|/type/Thread>\nobject can be waited on with the C<finish> method which will block until\nthe thread completes:\n\n=for code :preamble<my $thread;>\n$thread.finish;\n\nBeyond that there are no further facilities for synchronization or resource\nsharing which is largely why it should be emphasized that threads are unlikely\nto be useful directly in user code.\n\n=head2 Schedulers\n\nThe next level of the concurrency API is supplied by classes that\nimplement the interface defined by the role L<C<Scheduler>|/type/Scheduler>.  The intent\nof the scheduler interface is to provide a mechanism to determine which\nresources to use to run a particular task and when to run it. The majority\nof the higher level concurrency APIs are built upon a scheduler and it\nmay not be necessary for user code to use them at all, although some\nmethods such as those found in L<C<Proc::Async>|/type/Proc::Async>, L<C<Promise>|/type/Promise> and L<C<Supply>|/type/Supply>\nallow you to explicitly supply a scheduler.\n\nThe current default global scheduler is available in the variable\nC<$*SCHEDULER>.\n\nThe primary interface of a scheduler (indeed the only method required\nby the L<C<Scheduler>|/type/Scheduler> interface) is the C<cue> method:\n\n     method cue(:&code, Instant :$at, :$in, :$every, :$times = 1; :&catch)\n\nThis will schedule the L<C<Callable>|/type/Callable> in C<&code> to be executed in the\nmanner determined by the adverbs (as documented in L<C<Scheduler>|/type/Scheduler>) using\nthe execution scheme as implemented by the scheduler. For example:\n\n     my $i = 0;\n     my $cancellation = $*SCHEDULER.cue({ say $i++}, every => 2 );\n     sleep 20;\n\nAssuming that the C<$*SCHEDULER> hasn't been changed from the default,\nwill print the numbers 0 to 10 approximately (i.e with operating system\nscheduling tolerances) every two seconds.  In this case the code will\nbe scheduled to run until the program ends normally, however the method\nreturns a L<C<Cancellation>|/type/Cancellation> object which can be used to cancel the scheduled\nexecution before normal completion:\n\n     my $i = 0;\n     my $cancellation = $*SCHEDULER.cue({ say $i++}, every => 2 );\n     sleep 10;\n     $cancellation.cancel;\n     sleep 10;\n\nshould only output 0 to 5.\n\nDespite the apparent advantage the L<C<Scheduler>|/type/Scheduler> interface provides over\nthat of L<C<Thread>|/type/Thread> all of functionality is available through higher level\ninterfaces and it shouldn't be necessary to use a scheduler directly,\nexcept perhaps in the cases mentioned above where a scheduler can be\nsupplied explicitly to certain methods.\n\nA library may wish to provide an alternative scheduler implementation if\nit has special requirements, for instance a UI library may want all code\nto be run within a single UI thread, or some custom priority mechanism\nmay be required, however the implementations provided as standard and\ndescribed below should suffice for most user code.\n\n=head3 ThreadPoolScheduler\n\nThe L<C<ThreadPoolScheduler>|/type/ThreadPoolScheduler> is the default scheduler, it maintains a pool\nof threads that are allocated on demand, creating new ones as necessary.\n\nRakudo allows the maximum number of threads allowed in the default scheduler\nto be set by the environment variable C<RAKUDO_MAX_THREADS> at the time\nthe program is started.\n\nIf the maximum is exceeded then C<cue> may queue the code until a thread\nbecomes available.\n\n=head3 CurrentThreadScheduler\n\nThe L<C<CurrentThreadScheduler>|/type/CurrentThreadScheduler> is a very simple scheduler that will always\nschedule code to be run straight away on the current thread. The implication\nis that C<cue> on this scheduler will block until the code finishes\nexecution, limiting its utility to certain special cases such as testing.\n\n=head2 Locks\n\nThe class L<C<Lock>|/type/Lock> provides the low level mechanism that protects\nshared data in a concurrent environment and is thus key to supporting\nthread-safety in the high level API, this is sometimes known as a\n\"Mutex\" in other programming languages.  Because the higher level classes\n(L<C<Promise>|/type/Promise>, L<C<Supply>|/type/Supply> and L<C<Channel>|/type/Channel>) use a L<C<Lock>|/type/Lock> where required it\nis unlikely that user code will need to use a L<C<Lock>|/type/Lock> directly.\n\nThe primary interface to L<C<Lock>|/type/Lock> is the method\nL<protect|/type/Lock#method_protect> which ensures that a block of code\n(commonly called a \"critical section\") is only executed in one thread\nat a time:\n\n    my $lock = Lock.new;\n\n    my $a = 0;\n\n    await (^10).map: {\n        start {\n            $lock.protect({\n                my $r = rand;\n                sleep $r;\n                $a++;\n            });\n        }\n    }\n\n    say $a; # OUTPUT: «10␤»\n\nC<protect> returns whatever the code block returns.\n\nBecause C<protect> will block any threads that are waiting to execute\nthe critical section the code should be as quick as possible.\n\n=head2 Lock::Async\n\nL<C<Lock::Async>|/type/Lock::Async> is a mutual exclusion mechanism much like\nLock, but it exposes its functionality through L<C<Promise>|/type/Promise>s, allowing the use of\nC<await> when waiting for a lock to become available, instead of blocking an\nentire thread.\n\nAnother difference is that it is not re-entrant, meaning that the lock is not\nconsidered available to code that is C<protect>ed by the lock.\n\nL<C<Lock::Async>|/type/Lock::Async> is more high-level than L<C<Lock>|/type/Lock>, but it is still considered a\nlow-level primitive. Higher-level primitives should be preferred over mutating\nshared data inside critical sections.\n\n=head1 Safety concerns\n\nSome shared data concurrency issues are less obvious than others.\nFor a good general write-up on this subject see this L<blog post|https://raku.github.io/CCR/Remaster/Jonathan%20Worthington/Racing-to-writeness-to-wrongness-leads.html>.\n\nOne particular issue of note is when container autovivification or extension\ntakes place.  When an L<C<Array>|/type/Array> or a L<C<Hash>|/type/Hash> entry is initially assigned the\nunderlying structure is altered and that operation is not async safe.  For\nexample, in this code:\n\n    my @array;\n    my $slot := @array[20];\n    $slot = 'foo';\n\nThe third line is the critical section as that is when the array is extended.\nThe simplest fix is to use a L<C<Lock>|/type/Lock> to protect the critical section.  A\npossibly better fix would be to refactor the code so that sharing a container\nis not necessary.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/containers.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Containers\n\n=SUBTITLE A low-level explanation of Raku containers\n\nThis section explains how raw data, variables and containers relate to each\nother in Raku. The different types of containers used in Raku are explained and\nthe actions applicable to them like assigning, binding and flattening. More\nadvanced topics like self-referential data, type constraints and custom\ncontainers are discussed at the end.\n\nFor a deeper discussion of the various kinds of I<ordered> containers in\nRaku, see the overview of L<lists, sequences, and arrays|/language/list>; for\nI<unordered> containers, see L<sets, bags, and mixes|/language/setbagmix>.\n\n=head1 What is a variable?\n\nSome people like to say \"everything is an object\", but in fact a variable is\nnot a user-exposed object in Raku.\n\nWhen the compiler encounters a variable scope declaration like C<my $x>, it\nregisters it in some internal symbol table. This internal symbol table is\nused to detect undeclared variables and to tie the code generation for the\nvariable to the correct scope.\n\nAt runtime, a variable appears as an entry in a I<lexical pad>, or\nI<lexpad> for short. This is a per-scope data structure that stores a\npointer for each variable.\n\nIn the case of C<my $x>, the lexpad entry for the variable C<$x> is a\npointer to an object of type L<C<Scalar>|/type/Scalar>, usually just called I<the\ncontainer>.\n\n=head1 Scalar containers\n\nAlthough objects of type L<C<Scalar>|/type/Scalar> are everywhere in Raku, you\nrarely see them directly as objects, because most operations I<decontainerize>,\nwhich means they act on the L<C<Scalar>|/type/Scalar> container's contents instead of the\ncontainer itself.\n\nIn code like\n\n    my $x = 42;\n    say $x;\n\nthe assignment C<$x = 42> stores a pointer to the L<C<Int>|/type/Int> object 42 in the\nscalar container to which the lexpad entry for C<$x> points.\n\nThe assignment operator asks the container on the left to store the value on\nits right. What exactly that means is up to the container type. For\nL<C<Scalar>|/type/Scalar> it means \"replace the previously stored value with the new one\".\n\nNote that subroutine signatures allow passing containers around:\n\n    sub f($a is rw) {\n        $a = 23;\n    }\n    my $x = 42;\n    f($x);\n    say $x;         # OUTPUT: «23␤»\n\nInside the subroutine, the lexpad entry for C<$a> points to the same\ncontainer that C<$x> points to outside the subroutine. Which is why\nassignment to C<$a> also modifies the contents of C<$x>.\n\nLikewise, a routine can return a container if it is marked as C<is rw>:\n\n    my $x = 23;\n    sub f() is rw { $x };\n    f() = 42;\n    say $x;         # OUTPUT: «42␤»\n\nFor explicit returns, C<return-rw> instead of C<return> must be used.\n\nReturning a container is how C<is rw> attribute accessors work. So\n\n    class A {\n        has $.attr is rw;\n    }\n\nis equivalent to\n\n    class A {\n        has $!attr;\n        method attr() is rw { $!attr }\n    }\n\nScalar containers are transparent to type checks and most kinds of read-only\naccesses. A C<.VAR> makes them visible:\n\n    my $x = 42;\n    say $x.^name;       # OUTPUT: «Int␤»\n    say $x.VAR.^name;   # OUTPUT: «Scalar␤»\n\nAnd C<is rw> on a parameter requires the presence of a writable Scalar\ncontainer:\n\n    sub f($x is rw) { say $x };\n    f 42;\n    CATCH { default { say .^name, ': ', .Str } };\n    # OUTPUT: «X::Parameter::RW: Parameter '$x' expected a writable container, but got Int value␤»\n\n=head1 Callable containers\n\nCallable containers provide a bridge between the syntax of a\nL<C<Routine>|/type/Routine> call and the actual call of the method\nL<CALL-ME|/type/Callable#method_CALL-ME> of the object that is stored in the\ncontainer. The sigil C<&> is required when declaring the container and has to be\nomitted when executing the L<C<Callable>|/type/Callable>. The default type constraint is\nL<C<Callable>|/type/Callable>.\n\n    my &callable = -> $ν { say \"$ν is \", $ν ~~ Int ?? \"whole\" !! \"not whole\" }\n    callable(⅓);   # OUTPUT: «0.333333 is not whole␤»\n    callable(3);   # OUTPUT: «3 is whole␤»\n\nThe sigil has to be provided when referring to the value stored in the\ncontainer. This in turn allows L<C<Routine>|/type/Routine>s to be used as\nL<arguments|/language/signatures#Constraining_signatures_of_Callables> to calls.\n\n    sub f() {}\n    my &g = sub {}\n    sub caller(&c1, &c2){ c1, c2 }\n    caller(&f, &g);\n\n=head1 Binding\n\nNext to assignment, Raku also supports I<binding> with the C<:=> operator.\nWhen binding a value or a container to a variable, the lexpad entry of the\nvariable is modified (and not just the container it points to). If you write\n\n    my $x := 42;\n\nthen the lexpad entry for C<$x> directly points to the L<C<Int>|/type/Int> 42. Which\nmeans that you cannot assign to it anymore:\n\n    my $x := 42;\n    $x = 23;\n    CATCH { default { say .^name, ': ', .Str } };\n    # OUTPUT: «X::AdHoc: Cannot assign to an immutable value␤»\n\nYou can also bind variables to other variables:\n\n    my $a = 0;\n    my $b = 0;\n    $a := $b;\n    $b = 42;\n    say $a;         # OUTPUT: «42␤»\n\nHere, after the initial binding, the lexpad entries for C<$a> and C<$b> both\npoint to the same scalar container, so assigning to one variable also\nchanges the contents of the other.\n\nYou've seen this situation before: it is exactly what happened with the\nsignature parameter marked as C<is rw>.\n\nX<|Language,\\ (container binding)>\nSigilless variables and parameters with the trait C<is raw> always\nbind (whether C<=> or C<:=> is used):\n\n    my $a = 42;\n    my \\b = $a;\n    b++;\n    say $a;         # OUTPUT: «43␤»\n\n    sub f($c is raw) { $c++ }\n    f($a);\n    say $a;         # OUTPUT: «44␤»\n\n=head1 Scalar containers and listy things\n\nThere are a number of positional container types with slightly different\nsemantics in Raku. The most basic one is L<C<List>|/type/List>, which\nis created by the comma operator.\n\n    say (1, 2, 3).^name;    # OUTPUT: «List␤»\n\nA list is immutable, which means you cannot change the number of elements\nin a list. But if one of the elements happens to be a scalar container,\nyou can still assign to it:\n\n    my $x = 42;\n    ($x, 1, 2)[0] = 23;\n    say $x;                 # OUTPUT: «23␤»\n    ($x, 1, 2)[1] = 23;     # Cannot modify an immutable value\n    CATCH { default { say .^name, ': ', .Str } };\n    # OUTPUT: «X::Assignment::RO: Cannot modify an immutable Int␤»\n\nSo the list doesn't care about whether its elements are values or\ncontainers, they just store and retrieve whatever was given to them.\n\nLists can also be lazy; in that case, elements at the end are generated on\ndemand from an iterator.\n\nAn L<C<Array>|/type/Array> is just like a list, except that it forces all its elements to\nbe containers, which means that you can always assign to elements:\n\n    my @a = 1, 2, 3;\n    @a[0] = 42;\n    say @a;         # OUTPUT: «[42 2 3]␤»\n\nC<@a> actually stores three scalar containers. C<@a[0]> returns one of\nthem, and the assignment operator replaces the integer value stored in that\ncontainer with the new one, C<42>.\n\n=head1 Assigning and binding to array variables\n\nAssignment to a scalar variable and to an array variable both do\nthe same thing: discard the old value(s), and enter some new value(s).\n\nNevertheless, it's easy to observe how different they are:\n\n    my $x = 42; say $x.^name;   # OUTPUT: «Int␤»\n    my @a = 42; say @a.^name;   # OUTPUT: «Array␤»\n\nThis is because the L<C<Scalar>|/type/Scalar> container type hides itself well, but L<C<Array>|/type/Array>\nmakes no such effort. Also assignment to an array variable is coercive, so\nyou can assign a non-array value to an array variable.\n\nTo place a non-L<C<Array>|/type/Array> into an array variable, binding works:\n\n    my @a := (1, 2, 3);\n    say @a.^name;               # OUTPUT: «List␤»\n\n=head1 Binding to array elements\n\nAs a curious side note, Raku supports binding to array elements:\n\n    my @a = (1, 2, 3);\n    @a[0] := my $x;\n    $x = 42;\n    say @a;                     # OUTPUT: «[42 2 3]␤»\n\nIf you've read and understood the previous explanations, it is now time to\nwonder how this can possibly work. After all, binding to a variable requires a\nlexpad entry for that variable, and while there is one for an array, there\naren't lexpad entries for each array element, because you cannot expand the\nlexpad at runtime.\n\nThe answer is that binding to array elements is recognized at the syntax\nlevel and instead of emitting code for a normal binding operation, a special\nmethod (called L<C<BIND-POS>|/routine/BIND-POS>) is called on the\narray. This method handles binding to array elements. There is also an\nequivalent method for binding to hash elements as well (called\nL<C<BIND-KEY>|/routine/BIND-KEY>)\n\nNote that, while supported, one should generally avoid directly binding\nuncontainerized things into array elements. Doing so may produce\ncounter-intuitive results when the array is used later.\n\n    my @a = (1, 2, 3);\n    @a[0] := 42;         # This is not recommended, use assignment instead.\n    my $b := 42;\n    @a[1] := $b;         # Nor is this.\n    @a[2] = $b;          # ...but this is fine.\n    @a[1, 2] := 1, 2;    # runtime error: X::Bind::Slice\n    CATCH { default { say .^name, ': ', .Str } };\n    # OUTPUT: «X::Bind::Slice: Cannot bind to Array slice␤»\n\nOperations that mix Lists and Arrays generally protect against such\na thing happening accidentally.\n\n=head1 Flattening, items and containers\n\nThe C<%> and C<@> sigils in Raku generally indicate multiple values\nto an iteration construct, whereas the C<$> sigil indicates only one value.\n\n    my @a = 1, 2, 3;\n    for @a { };         # 3 iterations\n    my $a = (1, 2, 3);\n    for $a { };         # 1 iteration\n\nC<@>-sigiled variables do not flatten in list context:\n\n    my @a = 1, 2, 3;\n    my @b = @a, 4, 5;\n    say @b.elems;               # OUTPUT: «3␤»\n\nThere are operations that flatten out sublists that are not inside a scalar\ncontainer: slurpy parameters (C<*@a>) and explicit calls to C<flat>:\n\n\n    my @a = 1, 2, 3;\n    say (flat @a, 4, 5).elems;  # OUTPUT: «5␤»\n\n    sub f(*@x) { @x.elems };\n    say f @a, 4, 5;             # OUTPUT: «5␤»\n\nYou can also use C<|> to create a L<C<Slip>|/type/Slip>, introducing a list into\nthe other.\n\n    my @l := 1, 2, (3, 4, (5, 6)), [7, 8, (9, 10)];\n    say (|@l, 11, 12);    # OUTPUT: «(1 2 (3 4 (5 6)) [7 8 (9 10)] 11 12)␤»\n    say (flat @l, 11, 12) # OUTPUT: «(1 2 3 4 5 6 7 8 (9 10) 11 12)␤»\n\nIn the first case, every element of C<@l> is I<slipped> as the corresponding\nelements of the resulting list. C<flat>, in the other hand, I<flattens> all\nelements including the elements of the included array, except for C«(9 10)».\n\nAs hinted above, scalar containers prevent that flattening:\n\n    sub f(*@x) { @x.elems };\n    my @a = 1, 2, 3;\n    say f $@a, 4, 5;            # OUTPUT: «3␤»\n\nThe C<@> character can also be used as a prefix to coerce the argument to a\nlist, thus removing a scalar container:\n\n    my $x = (1, 2, 3);\n    .say for @$x;               # 3 iterations\n\nHowever, the I<decont> operator C«<>» is more appropriate to decontainerize\nitems that aren't lists:\n\n    my $x = ^Inf .grep: *.is-prime;\n    say \"$_ is prime\" for @$x;  # WRONG! List keeps values, thus leaking memory\n    say \"$_ is prime\" for $x<>; # RIGHT. Simply decontainerize the Seq\n\n    my $y := ^Inf .grep: *.is-prime; # Even better; no Scalars involved at all\n\nMethods generally don't care whether their invocant is in a scalar, so\n\n    my $x = (1, 2, 3);\n    $x.map(*.say);              # 3 iterations\n\nmaps over a list of three elements, not of one.\n\n=head1 Self-referential data\n\nContainer types, including L<C<Array>|/type/Array> and L<C<Hash>|/type/Hash>, allow you to create\nself-referential structures.\n\n    my @a;\n    @a[0] = @a;\n    put @a.raku;\n    # OUTPUT: «((my @Array_75093712) = [@Array_75093712,])␤»\n\nAlthough Raku does not prevent you from creating and using self-referential\ndata, by doing so you may end up in a loop trying to dump the data. As a\nlast resort, you can use Promises to L<handle|/type/Promise#method_in> timeouts.\n\n=head1 Type constraints\n\nAny container can have a type constraint in the form of a L<type\nobject|/language/typesystem#Type_objects> or a\nL<subset|/language/typesystem#subset>. Both can be placed between a declarator\nand the variable name or after the trait L<of|/type/Variable#trait_of>.\nThe constraint is a property of the variable, not the container.\n\n    subset Three-letter of Str where .chars == 3;\n    my Three-letter $acronym = \"ÞFL\";\n\nIn this case, the type constraint is the (compile-type defined) subset\nC<Three-letter>.\n\nThe default type constraint of a L<C<Scalar>|/type/Scalar> container is L<C<Mu>|/type/Mu>.\nIntrospection of type constraints on containers is provided by C<.VAR.of>\nmethod, which for C<@> and C<%> sigiled variables gives the constraint for\nvalues:\n\n    my Str $x;\n    say $x.VAR.of;  # OUTPUT: «(Str)␤»\n    my Num @a;\n    say @a.VAR.of;  # OUTPUT: «(Num)␤»\n    my Int %h;\n    say %h.VAR.of;  # OUTPUT: «(Int)␤»\n\n=head2 Definedness constraints\n\nA container can also enforce a variable to be defined. Put a smiley in the\ndeclaration:\n\n    my Int:D $def = 3;\n    say $def;   # OUTPUT: «3␤»\n    $def = Int; # Typecheck failure\n=comment ^^^ fails at runtime, so xt/example-compilation still passes\n\nYou'll also need to initialize the variable in the declaration, it can't be\nleft undefined after all.\n\nIt's also possible to have this constraint enforced in all variables declared\nin a scope with the\nL<default defined variables pragma|/language/variables#Default_defined_variables_pragma>.\nPeople coming from other languages where variables are always defined will\nwant to have a look.\n\n=head1 Custom containers\n\nTo provide custom containers Raku employs the class L<C<Proxy>|/type/Proxy>. Its\nconstructor takes two arguments, C<FETCH> AND C<STORE>, that point to methods\nthat are called when values are fetched or stored from the container. Type\nchecks are not done by the container itself and other restrictions like\nreadonlyness can be broken. The returned value must therefore be of the same\ntype as the type of the variable it is bound to. We can use\nL<type captures|/language/signatures#Type_captures> to work with types in Raku.\n\n    sub lucky(::T $type) {\n        my T $c-value; # closure variable\n        return-rw Proxy.new(\n            FETCH => method () { $c-value },\n            STORE => method (T $new-value) {\n                X::OutOfRange.new(what => 'number', got => '13', range => '-∞..12, 14..∞').throw\n                    if $new-value == 13;\n                $c-value = $new-value;\n            }\n        );\n    }\n\n    my Int $a := lucky(Int);\n    say $a = 12;    # OUTPUT: «12␤»\n    say $a = 'FOO'; # X::TypeCheck::Binding\n    say $a = 13;    # X::OutOfRange\n    CATCH { default { say .^name, ': ', .Str } };\n\n=end pod\n"
  },
  {
    "path": "doc/Language/contexts.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Contexts and contextualizers\n\n=SUBTITLE What are contexts and how to switch into them\n\nContexts interpret the value of a container.\nIn Raku, we use the active context to coerce the value of a container into a type\nor class, or to decide what to do with it.\nUsually, a context receiving an object will, if necessary,\ncoerce the object by implicitly calling a specific method on it.\n\n=head1 X<Sink|Language,sink context>\n\nThe I<sink> context is equivalent to what other languages call C<void>\ncontext.  It is the context which does nothing with the\nresult or return of any code: a term, an operation or a block. In general, when this\ncontext consumes a value or variable a warning or error is issued because the value is being\nignored.  Mnemonics for I<sink> relate to being rid of something: water down a\nsink's drain; a ship sinking; a heatsink removing warmth.\n=begin code\nmy $sub = -> $a { $a² };\n$sub; # OUTPUT: «WARNINGS:␤Useless use of $sub in sink context (line 1)␤»\n=end code\n\nX<|Language,sinking>\nYou can force that sink context on L<C<Iterator>|/type/Iterator>s, by\nusing the L<C<sink-all>|/routine/sink-all> method. L<C<Proc>|/type/Proc>s can also\nbe L<sunk via the C<sink> method|/type/Proc#method_sink>, forcing them to raise\nan exception and not return anything.\n\nMost blocks will warn if evaluated in sink context; however,\nL<gather/take blocks|/language/control#gather/take> are explicitly\nevaluated in sink context, with values returned explicitly using C<take>:\n\n=for code\nmy @results = gather for 1..1 { ^10 .map: *.take };\nsay @results; # OUTPUT: «[0 1 2 3 4 5 6 7 8 9]␤»\n\nIn this example, C<for> is run in sink context, and within it, C<map> is too.\n Results are taken explicitly from the loop via gather/take.\n\nIn sink context, an object will call its C<sink> method if present:\n\n=begin code\nsub foo {\n    return [<a b c>] does role {\n        method sink { say \"sink called\" }\n    }\n}\nfoo; # OUTPUT: «sink called␤»\n=end code\n\n\n=head1 X<Number|Language,number context>\n\nThis context, and probably all other contexts except I<sink> above, are\nI<conversion> or I<interpretation> contexts in the sense that they take an\nuntyped or typed variable and duck-type it to whatever is needed to perform the\noperation. In some cases that will imply a conversion (from L<C<Str>|/type/Str> to\nL<C<Numeric>|/type/Numeric>, for instance); in other cases simply an interpretation\n(L<C<IntStr>|/type/IntStr> will be interpreted as L<C<Int>|/type/Int> or as\nL<C<Str>|/type/Str>).\n\nI<Number context> is called whenever we need to apply a numerical operation on a\nvariable.\n\n=begin code\nmy $stringone = \"1                 \";\nmy $stringthree = \"3                        \";\nsay $stringone + $stringthree; # OUTPUT: «4␤»\n=end code\n\nIn the code above, strings will be interpreted in numeric context as long as\nthere are only a few digits and no other characters. It can have any number of\nleading or trailing whitespace, however.\n\nNumeric context can be forced by using arithmetic operators such as C<+> or\nC<->. In that context, the L<C<Numeric>|/routine/Numeric> method will be called\nif available and the value returned used as the numeric value of the object.\n\n=begin code\nmy $t = True;\nmy $f = False;\nsay $t + $f;      # OUTPUT: «1␤»\nsay $t.Numeric;   # OUTPUT: «1␤»\nsay $f.Numeric;   # OUTPUT: «0␤»\nmy $list= <a b c>;\nsay True + $list; # OUTPUT: «4␤»\nsay +\"  \\n \";     # OUTPUT: «0␤»\n=end code\n\nWhitespace in any quantity will be converted to 0, as is shown in the last\nstatement. In the case of I<listy> things, the numeric value will be in general\nequivalent to C<.elems>; in some cases, like\nL<C<Thread.numeric>|/routine/Numeric#(Thread)_method_Numeric>, it will return a unique\nthread identifier.\n\n=head1 X<String|Language,string context>\n\nIn a I<string context>, values can be manipulated as strings. This context is\nused, for instance, for coercing non-string values so that they can be printed\nto standard output.\n\n=for code :preamble<my $very-complicated-and-hairy-object>\nput $very-complicated-and-hairy-object; # OUTPUT: something meaningful\n\nOr when smartmatching to a regular expression:\n\n    put 333444777 ~~ /(3+)/; # OUTPUT: «333␤»\n\nIn general, the L<C<Str> routine|/routine/Str> will be called on a variable to\ncontextualize it; since this method is inherited from L<C<Mu>|/type/Mu>, it is\nalways present, but it is not always guaranteed to work. In some core classes it\nwill issue a warning.\n\nL<C<~>|/routine/~> is the (unary) string contextualizer. As an operator, it\nconcatenates strings, but as a prefix operator it becomes the string context\noperator.\n\n=begin code\nmy @array = [ [1,2,3], [4,5,6]];\nsay ~@array; # OUTPUT: «1 2 3 4 5 6␤»\n=end code\n\nThis will happen also in a\nL<I<reduction>|/language/operators#Reduction_operators>\ncontext, when C<[~]> is applied to a list\n\n     say [~] [ 3, 5+6i, Set(<a b c>), [1,2,3] ]; # OUTPUT: «35+6ic a b1 2 3␤»\n\nIn that sense, empty lists or other containers will stringify to an empty\nstring:\n\n    say [~] [] ; # OUTPUT: «␤»\n\nSince\nL<C<~> acts also as buffer concatenation operator|/routine/~#(Operators)_infix_~>,\nit will have to check that every element is not empty, since a single empty\nbuffer in string context will behave as a string, thus yielding an error.\n\n    say [~] Buf.new(0x3,0x33), Buf.new(0x2,0x22);\n    # OUTPUT: «Buf:0x<03 33 02 22>␤»\n\nHowever,\n\n=begin code\nmy $non-empty = Buf.new(0x3, 0x33);\nmy $empty = [];\nmy $non-empty-also = Buf.new(0x2,0x22);\nsay [~] $non-empty, $empty, $non-empty-also;\n# OUTPUT: «Cannot use a Buf as a string, but you called the Stringy method on it\n=end code\n\nSince C<~> is putting in string context the second element of this list,\nL<C<~>|/routine/~#(Operators)_infix_~> is going to be\nusing the second form that applies to strings, thus yielding the shown error.\nSimply making sure that everything you concatenate is a buffer will avoid this\nproblem.\n\n=for code\nmy $non-empty = Buf.new(0x3, 0x33);\nmy $empty = Buf.new();\nmy $non-empty-also = Buf.new(0x2,0x22);\nsay [~] $non-empty, $empty, $non-empty-also; # OUTPUT: «Buf:0x<03 33 02 22>␤»\n\nIn general, a context will coerce a variable to a particular type by calling the\ncontextualizer; in the case of mixins, if the context class is mixed in, it will\nbehave in that way.\n\n    my $described-number = 1i but 'Unity in complex plane';\n    put $described-number; # OUTPUT: «Unity in complex plane␤»\n\nC<but> creates a mixin, which endows the complex number with a L<C<Str>|/type/Str> method.\nC<put> contextualizes it into a string, that is, it calls L<C<Str>|/type/Str>, the string\ncontextualizer, with the result shown above.\n\n=head1 X<Boolean|Language,Boolean context>\n\nThis context will force a variable to be interpreted as C<True> or C<False>.\n\n    say \"Hey\" if 7;  # OUTPUT: «Hey␤»\n    say \"Ahoy\" if \"\";\n\nThis context appears in expressions such as C<if> or C<while>, and is\nequivalent to calling C<so> on these values.\n\n=for code\nsay \"Hey\" if 7.so;          # OUTPUT: «Hey␤»\nsay \"Ahoy\" if not set().so; # OUTPUT: «Ahoy␤»\n\nIn general, non-zero, non-empty will be converted to C<True>; zero or empty\nwill be equivalent to C<False>. But C<.so> can be defined to return any Boolean\nvalue we want, so this is just a rule of thumb.\n\nThe L«C<?>|/language/operators#prefix_?» Boolean context operator\nand the L«C<!>|/language/operators#prefix_!» negated Boolean context\noperator will force the Boolean context on an object.\n\n=for code\nsay ? 0i;    # OUTPUT: «False␤»\nsay ! :true; # OUTPUT: «False␤»\n\n=head1 X<List|Language,list context>\n\nThere are actually several different\nL<list contexts|/language/list#List_contexts>, which are better explained in\nthat page. In general, the list contextualizer is the comma C<,>\n\n    say (3,).^name; # OUTPUT: «List␤»\n\nand the method called in that case is also C<.list>\n\n=for code\nAny.list.^name;   # OUTPUT: «List␤»\nsay 3.list.^name; # OUTPUT: «List␤»\nsay (^3).list;    # OUTPUT: «(0 1 2)␤»\n\n=head1 Item context\n\nItem or scalar context will deal with complex pieces of data as if they were\na single item. It is forced when you try to assign to a scalar variable\n\n=for code\nmy $scalar-context = <1 2 3>;\nsay \"→ $_\" for $scalar-context; # OUTPUT: «→ 1 2 3␤»\n\nIt can be induced using the C<$> operator, that acts as the contextualizer\noperator by calling C<item> as a method or routine\n\n=for code\n.say for $(1,2,3);      # OUTPUT: «(1 2 3)␤»\n.say for (1,2,3).item;  # OUTPUT: «(1 2 3)␤»\n.say for item( 1..3 );  # OUTPUT: «1..3␤»\n\nItemization affects only their behavior in list context; however, they will\nstill keep their L<C<Positional>|/type/Positional> role or other roles they might have:\n\n=for code\n$(1,2,3).elems.say;          # OUTPUT: «3␤»\nsay (1,2,3).item[2];         # OUTPUT: «3␤»\nsay $( key => 'value')<key>; # OUTPUT: «value␤»\n\nItemization I<containerizes> values in a data structure, keeping them, for\ninstance, from being flattened into the surrounding list or data structure:\n\n=for code\n.say for (1, $(2,3), 4).flat; # OUTPUT: «1␤(2 3)␤4␤»\nsay (1, $<a b>, 2).elems; # OUTPUT: «3␤»\n\n\nThe itemizer operator will call the C<.item> method on the object; it can also\n be called as a subroutine. Since\nL<that is a method inherited from C<Mu>|/type/Mu#method_item>, objects of any\n class can be itemized.\n\n\n=end pod\n"
  },
  {
    "path": "doc/Language/control.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Control flow\n\n=SUBTITLE Statements used to control the flow of execution\n\n=head1 X<Statements|Control flow,statements>\n\nRaku programs consist of one or more statements. Simple statements\nare separated by semicolons. The following program will print \"Hello\"\nand then \"World\" on the next line.\n\n    say \"Hello\";\n    say \"World\";\n\nIn most places where spaces appear in a statement, and before the\nsemicolon, they may be split up over many lines. Also, multiple statements\nmay appear on the same line. It would be awkward, but the above example could\nalso be written as:\n\n    say\n    \"Hello\"; say \"World\";\n\n=head1 X<Blocks|Control flow,blocks>\n\nLike many other languages, Raku uses C<blocks> enclosed by C<{> and C<}> to\nturn a sequence of statements into a\nL<C<Block>|/type/Block> that acts as a single one. It is OK\nto omit the semicolon between the last statement in a block and the closing\nC<}>.\n\n    { say \"Hello\"; say \"World\" }\n\nWhen a block stands alone as a statement, it will be entered immediately\nafter the previous statement finishes, and the statements inside it will be\nexecuted.\n\n    say 1;                    # OUTPUT: «1␤»\n    { say 2; say 3 };         # OUTPUT: «2␤3␤»\n    say 4;                    # OUTPUT: «4␤»\n\nUnless it stands alone as a statement, a block simply creates a closure. The\nstatements inside are not executed immediately. Closures are another topic\nand how they are used is explained\nL<elsewhere|/language/functions#Closures>. For now it is just\nimportant to understand when blocks run and when they do not:\n\n=for code\nsay \"We get here\";\n{ say \"then here.\" };\n{ say \"not here\"; 0; } or die;\n\nIn the above example, after running the first statement, the first block stands\nalone as a second statement, so we run the statement inside it. The second\nblock is a closure, so instead, it makes an object of type L<C<Block>|/type/Block> but does\nnot run it. Object instances are usually considered to be true, so the code\ndoes not die, even though that block would evaluate to 0, were it to be\nexecuted. The example does not say what to do with the L<C<Block>|/type/Block> object, so it\njust gets thrown away.\n\nMost of the flow control constructs covered below are just ways to tell Raku\nwhen, how, and how many times, to enter blocks like that second block.\n\nBefore we go into those, an important side-note on syntax: If there is\nnothing (or nothing but comments) on a line after a closing curly brace where\nyou would normally put semicolon, then you do not need the semicolon:\n\n    # All three of these lines can appear as a group, as is, in a program\n    { 42.say }                # OUTPUT: «42␤»\n    { 43.say }                # OUTPUT: «43␤»\n    { 42.say }; { 43.say }    # OUTPUT: «42␤43␤»\n\n...but:\n\n=begin code :skip-test<syntax error>\n{ 42.say }  { 43.say }    # Syntax error\n{ 42.say; } { 43.say }    # Also a syntax error, of course\n=end code\n\nSo, be careful when you backspace in a line-wrapping editor:\n\n=begin code :skip-test<syntax error>\n{ \"Without semicolons line-wrapping can be a bit treacherous.\".say } \\\n{ 43.say } # Syntax error\n=end code\n\nYou have to watch out for this in most languages anyway to prevent things\nfrom getting accidentally commented out. Many of the examples below may\nhave unnecessary semicolons for clarity.\n\nClass bodies behave like simple blocks for any top level expression; same goes\nto roles and other packages, like grammars (which are actually classes)\nor modules.\n\n=begin code :skip-test<dies deliberately>\nclass C {\n    say \"I live\";\n    die \"I will never live!\"\n};\nmy $c = C.new;                              │\n# OUTPUT: Fails and writes «I live␤I will never live!␤\n=end code\n\nThis block will first run the first statement, and then C<die> printing the\nsecond statement. C<$c> will never get a value.\n\n=head1 X<Phasers|Control flow,Phasers>\n\nBlocks may have I<phasers>: special labeled blocks that break their execution\ninto phases that run in particular phases. See the page\nL<phasers|/language/phasers> for the details.\n\n=head1 X<do|Control flow,do>\n\nThe simplest way to run a block where it cannot be a stand-alone statement\nis by writing C<do> before it:\n\n=for code\n# This dies half of the time\ndo { say \"Heads I win, tails I die.\"; Bool.pick } or die; say \"I win.\";\n\nNote that you need a space between the C<do> and the block.\n\nThe whole C<do {...}> evaluates to the final value of the block.  The block\nwill be run when that value is needed in order to evaluate the rest of the\nexpression.  So:\n\n    False and do { 42.say };\n\n...will not say 42.  However, the block is only evaluated once each time\nthe expression it is contained in is evaluated:\n\n    # This says \"(..1 ..2 ..3)\" not \"(..1 ...2 ....3)\"\n    my $f = \".\"; say do { $f ~= \".\" } X~ 1, 2, 3;\n\nIn other words, it follows the same\nL<reification|/language/glossary#Reify> rules as everything else.\n\nTechnically, C<do> is a loop which runs exactly one iteration.\n\nA C<do> may also be used on a bare statement (without curly braces)\nbut this is mainly just useful for avoiding the syntactical need to\nparenthesize a statement if it is the last thing in an expression:\n\n=for code\n3, do if 1 { 2 }  ; # OUTPUT: «(3, 2)␤»\n3,   (if 1 { 2 }) ; # OUTPUT: «(3, 2)␤»\n=for code :skip-test<syntax error>\n3,    if 1 { 2 }  ; # Syntax error\n\nAs a consequence, C<do> does not run blocks that, by their syntax, must\nbe functions. For example, if C«->» is used to specify a\nL<signature|/language/syntax#Block_declaration>, C<do> treats these as\nsingle-expression statements.\n\nThus, adding C«->» to our first example prevents the closure from\nbeing evaluated:\n\n=for code\n# This never dies and never prints \"Heads I win, tails I die.\"\ndo -> { say \"Heads I win, tails I die.\"; Bool.pick } or die; say \"I win.\";\n\n=head1 X<start|Control flow,start>\n\nThe simplest way to run a statement or block B<asynchronously> is by writing C<start>\nbefore it:\n\n=for code\nstart { sleep 1; say \"done\" }\nsay \"working\";\n# working, done\n\nNote that you need a space between the C<start> and the block. In the example\nabove, the C<start> block is in sink context since it's not assigned to a\nvariable. From version 6.d, these sunk blocks have an exception handler\nattached:\n\n=for code\nstart { die \"We're dead\"; }\nsay \"working\";\nsleep 10;\n\nThis code will print C<Unhandled exception in code scheduled on thread 4 We're\ndead> in version 6.d, while it will simply get out after waiting for 10 seconds\nin version 6.c.\n\nThe C<start {...}> immediately returns a L<C<Promise>|/type/Promise> that can be safely ignored\nif you are not interested in the result of the block. If you B<are> interested\nin the final value of the block, you can call the C<.result> method on the\nreturned promise. So:\n\n    my $promise = start { sleep 10; 42 }\n    # ... do other stuff\n    say \"The result is $promise.result()\";\n\nIf the code inside the block has not finished, the call to C<.result> will\nwait until it is done.\n\nA C<start> used on a bare statement is useful when the only thing to do\nasynchronously is a subroutine or method:\n\n    sub get42 { 42 }\n    my $promise = start get42;\n    say $promise.result; # OUTPUT: «42␤»\n\nNote that start code does not have access to the special\nvariables L«C<$!>|/syntax/$!» and L«C<$/>|/syntax/$$SOLIDUS» of its outer\nblock, but receives new ones, so every asynchronous task has its\nper-task state.\n\nThus, C<try> expressions and regex matches executed in the\nasynchronous task have their per-task state.\n\n    'a' ~~ /a/; # $/ is set to ｢a｣\n    try die;    # $! is defined now with an anonymous AdHoc exception\n    # as a code block\n    await start { say $! }; # OUTPUT: «Nil␤»\n    await start { say $/ }; # OUTPUT: «Nil␤»\n    # as a single statement\n    await start $!.say;     # OUTPUT: «Nil␤»\n    await start $/.say;     # OUTPUT: «Nil␤»\n\n=head1 X<if|Control flow,if>\n\nTo conditionally run a block of code, use an C<if> followed by a condition.\nThe condition, an expression, will be evaluated immediately after the\nstatement before the C<if> finishes. The block attached to the condition will\nonly be evaluated if the condition means C<True> when coerced to L<C<Bool>|/type/Bool>.\nUnlike some languages the condition does not have to be parenthesized,\ninstead the C<{> and C<}> around the block are mandatory:\n\n=for code\nif 1 { \"1 is true\".say }  ; # says \"1 is true\"\n=for code :skip-test<syntax error>\nif 1   \"1 is true\".say    ; # syntax error, missing block\n=for code\nif 0 { \"0 is true\".say }  ; # does not say anything, because 0 is false\n=for code\nif 42.say and 0 { 43.say }; # says \"42\" but does not say \"43\"\n\nThere is also a form of C<if> called a \"statement modifier\" form. In this\ncase, the C<if> and the condition come after the code you want to run\nconditionally. Do note that the condition is still always evaluated first:\n\n    43.say if 42.say and 0;     # says \"42\" but does not say \"43\"\n    43.say if 42.say and 1;     # says \"42\" and then says \"43\"\n    say \"It is easier to read code when 'if's are kept on left of screen\"\n        if True;                # says the above, because it is true\n    { 43.say } if True;         # says \"43\" as well\n\nThe statement modifier form is probably best used sparingly.\n\nThe C<if> statement itself will either L<C<Slip>|/type/Slip> us an empty list, if\nit does not run the block, or it will return the value which the block produces:\n\n    my $d = 0; say (1, (if 0 { $d += 42; 2; }), 3, $d); # says \"(1 3 0)\"\n    my $c = 0; say (1, (if 1 { $c += 42; 2; }), 3, $c); # says \"(1 2 3 42)\"\n    say (1, (if 1 { 2, 2 }), 3);         # does not slip, says \"(1 (2 2) 3)\"\n\nFor the statement modifier it is the same, except you have the value\nof the statement instead of a block:\n\n    say (1, (42 if True) , 2); # says \"(1 42 2)\"\n    say (1, (42 if False), 2); # says \"(1 2)\"\n    say (1,  42 if False , 2); # says \"(1 42)\" because \"if False, 2\" is true\n\nThe C<if> does not change the topic (C<$_>) by default. In order to access\nthe value which the conditional expression produced, you have to ask\nfor it more strongly:\n\n    $_ = 1; if 42 { $_.say }                ; # says \"1\"\n    $_ = 1; if 42 -> $_ { $_.say }          ; # says \"42\"\n    $_ = 1; if 42 -> $a { $_.say;  $a.say } ; # says \"1\" then says \"42\"\n    $_ = 1; if 42       { $_.say; $^a.say } ; # says \"1\" then says \"42\"\n\nThis is especially useful for patterns of the kind\n\"if something does not evaluate to False, do something with it\":\n\n    sub get-user-id($username) { #`(return 0 if no such username exists) }\n\n    if prompt 'Enter username: ' -> $username {\n        if get-user-id($username) -> $user-id {\n            say \"Found id $user-id for name $username\";\n        }\n    }\n\nHere C<$username> and C<$user-id> are only defined inside\ntheir respective C<if> block that guarantees their being C<True>.\nThis gives this solution an advantage\nover the more conventional C<my $username = …; if $username {…}>.\n\nCompare L<C<with>|/language/control#with>, which tests\nfor definedness rather than truth, and topicalizes by default.\n(The second C<if> in the above example could be replaced by C<with> if the routine\nC<get-user-id> returned L<C<Nil>|/type/Nil> rather than 0 for nonexistent usernames.)\n\n=head2 X<C<else/elsif>|Control flow,else elsif>\n\nA compound conditional may be produced by following an C<if> conditional\nwith C<else> to provide an alternative block to run when the conditional\nexpression is false:\n\n=for code\nif 0 { say \"no\" } else { say \"yes\" }   ; # says \"yes\"\nif 0 { say \"no\" } else{ say \"yes\" }    ; # says \"yes\", space is not required\n\nThe C<else> cannot be separated from the conditional statement by a\nsemicolon, but as a special case, it is OK to have a newline.\n\n=for code :skip-test<syntax error>\nif 0 { say \"no\" }; else { say \"yes\" }  ; # syntax error\n=for code\nif 0 { say \"no\" }\nelse { say \"yes\" }                     ; # says \"yes\"\n\nAdditional conditions may be sandwiched between the C<if> and the C<else> using\nC<elsif>. An extra condition will only be evaluated if all the conditions\nbefore it were false, and only the block next to the first true condition will\nbe run. You can end with an C<elsif> instead of an C<else> if you want.\n\n    if 0 { say \"no\" } elsif False { say \"NO\" } else { say \"yes\" } # says \"yes\"\n    if 0 { say \"no\" } elsif True { say \"YES\" } else { say \"yes\" } # says \"YES\"\n\n    if 0 { say \"no\" } elsif False { say \"NO\" } # does not say anything\n\n    sub right { \"Right!\".say; True }\n    sub wrong { \"Wrong!\".say; False }\n    if wrong() { say \"no\" } elsif right() { say \"yes\" } else { say \"maybe\" }\n    # The above says \"Wrong!\" then says \"Right!\" then says \"yes\"\n\nYou cannot use the statement modifier form with C<else> or C<elsif>:\n\n=for code :skip-test<syntax error>\n42.say if 0 else { 43.say }            # syntax error\n\nAll the same rules for semicolons and newlines apply, consistently\n\n=for code :skip-test<syntax error>\nif 0 { say 0 }; elsif 1 { say 1 }  else { say \"how?\" } ; # syntax error\nif 0 { say 0 }  elsif 1 { say 1 }; else { say \"how?\" } ; # syntax error\n\n=for code\nif 0 { say 0 }  elsif 1 { say 1 }  else { say \"how?\" } ; # says \"1\"\n\n    if 0 { say 0 } elsif 1 { say 1 }\n    else { say \"how?\" }                                    ; # says \"1\"\n\n    if 0 { say 0 }\n    elsif 1 { say 1 } else { say \"how?\" }                  ; # says \"1\"\n\n    if        0 { say \"no\" }\n    elsif False { say \"NO\" }\n    else        { say \"yes\" }                              ; # says \"yes\"\n\nThe whole thing either L<C<Slip>|/type/Slip>s us an empty list (if no blocks\nwere run) or returns the value produced by the block that did run:\n\n    my $d = 0; say (1,\n                    (if 0 { $d += 42; \"two\"; } elsif False { $d += 43; 2; }),\n                    3, $d); # says \"(1 3 0)\"\n    my $c = 0; say (1,\n                    (if 0 { $c += 42; \"two\"; } else { $c += 43; 2; }),\n                    3, $c); # says \"(1 2 3 43)\"\n\nIt's possible to obtain the value of the previous expression inside an\nC<else>, which could be from C<if> or the last C<elsif> if any are\npresent:\n\n    $_ = 1; if 0     { } else -> $a { \"$_ $a\".say } ; # says \"1 0\"\n    $_ = 1; if False { } else -> $a { \"$_ $a\".say } ; # says \"1 False\"\n\n    if False { } elsif 0 { } else -> $a { $a.say }  ; # says \"0\"\n\n=head1 X<C<unless>|Control flow,unless>\n\nWhen you get sick of typing \"if not (X)\" you may use C<unless> to invert\nthe sense of a conditional statement. You cannot use C<else> or C<elsif>\nwith C<unless> because that ends up getting confusing. Other than those\ntwo differences C<unless> works the same as L<if|#if>:\n\n=for code\nunless 1 { \"1 is false\".say }  ; # does not say anything, since 1 is true\n=for code :skip-test<syntax error>\nunless 1   \"1 is false\".say    ; # syntax error, missing block\n=for code\nunless 0 { \"0 is false\".say }  ; # says \"0 is false\"\n\n    unless 42.say and 1 { 43.say } ; # says \"42\" but does not say \"43\"\n    43.say unless 42.say and 0;      # says \"42\" and then says \"43\"\n    43.say unless 42.say and 1;      # says \"42\" but does not say \"43\"\n\n    $_ = 1; unless 0 { $_.say }           ; # says \"1\"\n    $_ = 1; unless 0 -> $_ { $_.say }     ; # says \"0\"\n    $_ = 1; unless False -> $a { $a.say } ; # says \"False\"\n\n    my $c = 0; say (1, (unless 0 { $c += 42; 2; }), 3, $c); # says \"(1 2 3 42)\"\n    my $d = 0; say (1, (unless 1 { $d += 42; 2; }), 3, $d); # says \"(1 3 0)\"\n\n=head1 X<C<with orwith without>|Control flow,with orwith without>\n\nThe C<with> statement is like C<if>, but tests for definedness rather than\ntruth, and it topicalizes on the condition, much like C<given>:\n\n    with \"abc\".index(\"a\") { .say }      # prints 0\n\nSimilarly to C<elsif>, C<orwith> may be used to chain definedness tests:\n\n    # The below code says \"Found 'a' at 0\"\n    my $s = \"abc\";\n    with   $s.index(\"a\") { say \"Found 'a' at $_\" }\n    orwith $s.index(\"b\") { say \"Found 'b' at $_\" }\n    orwith $s.index(\"c\") { say \"Found 'c' at $_\" }\n    else                 { say \"Didn't find 'a', 'b' or 'c'\" }\n\nYou may intermix C<if>-based and C<with>-based clauses.\n\n    # This says \"Yes\"\n    if 0 { say \"No\" } orwith Nil { say \"No\" } orwith 0 { say \"Yes\" };\n\nAs with C<unless>, you may use C<without> to check for undefinedness,\nbut you may not add an C<else> clause:\n\n    my $answer = Any;\n    without $answer { warn \"Got: {$_.raku}\" }\n\nThere are also C<with> and C<without> statement modifiers:\n\n    my $answer = (Any, True).roll;\n    say 42 with $answer;\n    warn \"undefined answer\" without $answer;\n\nAs with the other chainable constructs, an C<else> completing a\nC<with/if>..C<orwith/elsif> chain will itself topicalize to the value\nof the prior (failed) condition's topic (either the topic of C<with>\nor the final C<orwith> or C<elsif>).\n\nIn the case of an C<else> following a C<with> or C<orwith>,\ntopicalizing a value guaranteed to be undefined may seem useless. But\nit makes for a useful idiom when used in conjunction with operations\nthat may fail, because L<C<Failure>|/type/Failure> values are always\nundefined:\n\n=begin code\nsub may_fail( --> Numeric:D ) {\n  my $value = (^10).pick || fail \"Zero is unacceptable\";\n  fail \"Odd is also not okay\" if $value % 2;\n  return $value;\n}\n\nwith may_fail() -> $value { # defined, so didn't fail\n  say \"I know $value isn't zero or odd.\"\n} else { # undefined, so failed, and the Failure is the topic\n  say \"Uh-oh: {.exception.message}.\"\n}\n=end code\n\nNote that while topicalizing a L<C<Failure>|/type/Failure> marks it\nL<C<handled>|/type/Failure#method_handled>—so you can use the\nC<with>/C<else> to proceed safely with execution—it doesn't make the\nI<Failure value itself> safe. Even within the C<else> clause, if you\ntry to use the value directly, it will result in your C<else> clause\nitself failing (or, in Rakudo, \"promoting\" the Failure into a thrown\nexception).\n\nBut as seen above, you I<can> use the methods of a handled L<C<Failure>|/type/Failure>\nobject the C<else> topicalizes, such as\nL<C<exception>|/type/Failure#method_exception>, if you wish to provide\ndiagnostics or interrogate the underlying\nL<C<Exception>|/type/Exception>.\n\n=head1 X<when|Control flow,when>\n\nThe C<when> block is similar to an C<if> block and either or both can be used in\nan outer block; they also both have a \"statement modifier\" form. But there is a\ndifference in how following code in the same, outer block is handled: When the\nC<when> block is executed, control is passed to the enclosing block and\nfollowing statements are ignored; but when the C<if> block is executed,\nfollowing statements are executed. N<There are other ways to modify their\ndefault behavior; they are discussed in other sections.> The following\nexamples should illustrate the C<if> or C<when> block's default behavior\nassuming no special exit or other side effect statements are included in the\nC<if> or C<when> blocks:\n\n=begin code\n{\n    if X {...} # if X is true in Boolean context, block is executed\n    # following statements are executed regardless\n}\n{\n    when X {...} # if X is true in Boolean context, block is executed\n                 # and control passes to the outer block\n    # following statements are NOT executed\n}\n=end code\n\nShould the C<if> and C<when> blocks above appear at file scope, following\nstatements would be executed in each case.\n\nThere is one other feature C<when> has that C<if> doesn't: the C<when>'s\nBoolean context test defaults to C<$_ ~~> while the C<if>'s does not. That has\nan effect on how one uses the X in the C<when> block without a value for C<$_>\n(it's L<C<Any>|/type/Any> in that case and L<C<Any>|/type/Any> smartmatches on C<True>: C<Any ~~ True>\nyields C<True>). Consider the following:\n\n=begin code\n{\n    my $a = 1;\n    my $b = True;\n    when $a    { say 'a' }; # no output\n    when so $a { say 'a' }  # a (\"so $a\" 'so' coerces $a to Boolean context True\n                            # which matches with Any)\n    when $b    { say 'b' }; # no output (this statement won't be run)\n}\n=end code\n\nFinally, C<when>'s statement modifier form does not affect execution\nof following statements either inside or outside of another block:\n\n=begin code\nsay \"foo\" when X; # if X is true statement is executed\n                  # following statements are not affected\n=end code\n\nSince a successful match will exit the block, the behavior of this piece of\ncode:\n=begin code\n$_ = True;\nmy $a;\n{\n    $a = do when .so { \"foo\" }\n};\nsay $a; # OUTPUT: «(Any)␤»\n=end code\n\nis explained since the C<do> block is abandoned before any value is stored or\nprocessed. However, in this case:\n=begin code\n$_ = False;\nmy $a;\n{\n    $a = do when .so { \"foo\" }\n};\nsay $a; # OUTPUT: «False␤»\n=end code\nthe block is not abandoned since the comparison is false, so C<$a> will actually\nget a value.\n\n=head1 X<for|Control flow,for>\n\nThe C<for> loop iterates over a list, running the statements inside a\nL<C<Block>|/type/Block> once on each iteration. If the block takes parameters, the\nelements of the list are provided as arguments. By default, the block takes one\nparameter, C<$_>:\n\n    my @foo = 1..3;\n    for @foo { $_.print } # prints each value contained in @foo\n    for @foo { .print }   # same thing, because .print implies a $_ argument\n    for @foo { 42.print } # prints 42 as many times as @foo has elements\n\nPointy block syntax or a L<placeholder|/language/variables#The_^_twigil>\nmay be used to name the parameter:\n\n    my @foo = 1..3;\n    for @foo -> $item { print $item }\n    for @foo { print $^item }            # same thing\n\nMultiple parameters can be declared, in which case the iterator takes\nas many elements from the list as needed before running the block.\n\n    my @foo = 1..3;\n    for @foo.kv -> $idx, $val { say \"$idx: $val\" }\n    my %hash = <a b c> Z=> 1,2,3;\n    for %hash.kv -> $key, $val { say \"$key => $val\" }\n    for 1, 1.1, 2, 2.1 { say \"$^x < $^y\" }  # OUTPUT: «1 < 1.1␤2 < 2.1␤»\n\nParameters of a pointy block can have default values, allowing the code to\nhandle lists with missing elements.\n\n    my @list = 1,2,3,4;\n    for @list -> $a, $b = 'N/A', $c = 'N/A' {\n        say \"$a $b $c\"\n    }\n    # OUTPUT: «1 2 3␤4 N/A N/A␤»\n\nWhen no parameters are specified for a C<for> loop's block, C<when> can be used\nwithin it similarly to how it's used in a C<given> block:\n\n    # A solution for FizzBuzz:\n    for 1..100 {\n        when * %% 15 { say 'FizzBuzz' }\n        when * %% 3  { say 'Fizz' }\n        when * %% 5  { say 'Buzz' }\n        default      { say $_ }\n    }\n\nIf the postfix form of C<for> is used, a block is not required and the topic is\nset for the statement list.\n\n    say „I $_ butterflies!“ for <♥ ♥ ♥>;\n    # OUTPUT: «I ♥ butterflies!␤I ♥ butterflies!␤I ♥ butterflies!␤»\n\nA C<for> may be used on lazy lists – it will only take elements from the\nlist when they are needed, so to read a file line by line, you could\nuse:\n\n=for code\nfor $*IN.lines -> $ln { $ln.say }\n\nIteration variables are always lexical, so you don't need to use C<my> to give\nthem the appropriate scope. Also, they are read-only aliases. If you need them\nto be writable, use C«<->» instead of C«->». Alternatively, you can add\nthe L«C«is rw»|/language/signatures#Parameter_traits_and_modifiers» trait; this performs\na binding operation so assigning to the parameter changes the value of the\nvariable at the caller side. If instead you want to modify copies of the\narguments within the block, add\nL«C«is copy»|/language/signatures#Parameter_traits_and_modifiers».\n\n=begin code\nmy @foo = 1..3;\nfor @foo <-> $value {\n    $value = $value %% 2 ?? \"Even\" !! \"Odd\"\n}\n\nsay @foo; # OUTPUT: «[Odd Even Odd]␤»\n\n@foo = 1..3;\nfor @foo -> $value is rw {\n    $value = $value %% 2 ?? \"Even\" !! \"Odd\"\n}\n\nsay @foo; # OUTPUT: «[Odd Even Odd]␤»\n\n@foo = 1..3;\nmy @bar;\nfor @foo -> $value is copy {\n    $value = $value %% 2 ?? \"Even\" !! \"Odd\";\n    @bar.push: $value\n}\n\nsay @foo; # OUTPUT: «[1 2 3]␤»\nsay @bar; # OUTPUT: «[Odd Even Odd]␤»\n=end code\n\nThis rule also applies to the topic variable C«$_», which by default is a\nread-write alias; it will become read-only if it's used in a C«->» loop.\n\n    my @foo = 1..3;\n    for @foo -> $_ { $_.say }\n\n    # Error: ...require mutable arguments\n    for @foo -> $_ { $_++ }\n\nA C<for> loop can produce a L<C<List>|/type/List> of the values produced by each run of the\nattached block. To capture these values, put the for loop in parenthesis or\nassign them to an array:\n\n    (for 1, 2, 3 { $_ * 2 }).say;              # OUTPUT: «(2 4 6)␤»\n    my @a = do for 1, 2, 3 { $_ * 2 }; @a.say; # OUTPUT: «[2 4 6]␤»\n    my @b = (for 1, 2, 3 { $_ * 2 }); @b.say;  # OUTPUT: «[2 4 6]␤»\n\nThis implies that, if the results of the loop are not assigned, they will be\nin a L<sink context|/language/contexts#Sink>:\n\n=for code\nclass Sunk {\n    has $.titanic;\n    method sink {\n        say \"Sinking $!titanic\";\n    }\n}\nSunk.new( :titanic($_) ) for ^3;\nfor 1 {\n    say \"About to sink\";\n    Sunk.new( :titanic($_) );\n}\n# OUTPUT:\n# Sinking 0\n# Sinking 1\n# Sinking 2\n# About to sink\n# Sinking 1\n\n\nThe first loop creates three elements but they are in a sink context, so its\nC<sink> method is called. In the second loop, its last statement will be in a\nsink context, so it will be also sunk (from version 6.d).\n\nThe C<Empty> constant will act as a no-op for a loop:\n\n=for code\nsay \"Not here\" for Empty;\n\nWill not do anything. This constant is\nL<equivalent to an empty Slip or List|/syntax/Empty>.\n\nUndefined values will behave in the same way:\n\n=for code\nmy @array := Empty;\n.say for @array;\nsay @array; # OUTPUT: «()␤»\n\nAssigning C<Empty> will effectively undefine an L<C<Array>|/type/Array>, using C<for> over an\nundefined array will not even enter the loop, as shown, effectively behaving in\nthe same way as above when C<Empty> was used directly.\n\nWith C<hyper> and C<race>, the C<for> loop is potentially iterated in parallel.\nSee also the documentation for C<hyper> and C<race> in class L<C<Map>|/type/Map>.\n\n=for code\nmy $primes_h = hyper for ^10_000 -> $number { $number if $number.is-prime };\nsay $primes_h.elems;   # OUTPUT: «1229␤»\nsay $primes_h.tail: 5; # OUTPUT: «(9931 9941 9949 9967 9973)␤»\n\nwith C<hyper> the order of elements is preserved.\n\n=for code\nmy $primes_r = race for ^10_000 -> $number { $number if $number.is-prime };\nsay $primes_r.elems; # OUTPUT: «1229␤»\n\nUnlike C<hyper>, C<race> does not preserve the order of elements.\n\n=head1 X<gather/take|Control flow,gather take>\n\nC<gather> is a statement or block prefix that returns a L<sequence|/type/Seq>\nof values. The values come from calls to L<take|/type/Mu#routine_take> in the\ndynamic scope of the C<gather> code. In the following example, we implement\na subroutine to compute the factors of an integer with C<gather> (note that the\nfactors are not generated in order):\n\n    sub factors( Int:D \\n ) {\n        my $k = 1;\n        gather {\n            while $k**2 < n {\n                if n %% $k {\n                    take $k;\n                    take n div $k;\n                }\n                $k++;\n            }\n            take $k if $k**2 == n;\n        }\n    }\n\n    say factors(36); # OUTPUT: «1, 36, 2, 18, 3, 12, 4, 9, 6␤»\n\nThe C<gather/take> combination can generate values lazily, depending on\ncontext.\nBinding to a scalar or sigilless container will force laziness.\nIf you want to\nforce lazy evaluation use the L<lazy|/type/Iterable#method_lazy> subroutine or\nmethod.  For example:\n\n    my @vals = lazy gather {\n        take 1;\n        say \"Produced a value\";\n        take 2;\n    }\n    say @vals[0];\n    say 'between consumption of two values';\n    say @vals[1];\n\n    # OUTPUT:\n    # 1\n    # between consumption of two values\n    # Produced a value\n    # 2\n\nC<gather/take> is scoped dynamically, so you can call C<take> from subs or\nmethods that are called from within C<gather>:\n\n    sub weird(@elems, :$direction = 'forward') {\n        my %direction = (\n            forward  => sub { take $_ for @elems },\n            backward => sub { take $_ for @elems.reverse },\n            random   => sub { take $_ for @elems.pick(*) },\n        );\n        return gather %direction{$direction}();\n    }\n\n    say weird(<a b c>, :direction<backward> );          # OUTPUT: «(c b a)␤»\n\nIf values need to be mutable on the caller side, use\nL<take-rw|/type/Mu#sub_take-rw>.\n\nNote that the L<C<Seq>|/type/Seq> created by C<gather/take> may be coerced to another type.\nAn example with assignment to a hash:\n\n    my %h = gather { take \"foo\" => 1; take \"bar\" => 2};\n    say %h;                   # OUTPUT: «{bar => 2, foo => 1}␤»\n\nB<Note>: C<gather/take> must not be used to collect results from C<react/whenever>.\nThe C<whenever> block is not run from the thread that runs the C<gather/react>, but\nthe thread that runs the C<emit>. On this thread, there is no handler for the\ncontrol exception thrown by C<take>, causing it to error out.\n\n=head1 X<supply/emit|Control flow,supply emit>\n\nThe keyword C<supply> creates a L<Supply object|/type/Supply> which is an\nL<on-demand supply|/language/concurrency#index-entry-supply_(on-demand)>\nthat you can tap. It pairs with C<emit>, which can be used anywhere from within\nC<supply> prefixed code.\n\nUsing the L<C<emit method>|/type/Mu#method_emit> or the\nL<C<emit routine>|/type/independent-routines#sub_emit> passes the invocant\nto the enclosing\nL<supply|/language/concurrency#index-entry-supply_(on-demand)>:\n\n    my $supply = supply {\n        .emit for \"foo\", 42, .5;\n    }\n    $supply.tap: {\n        say \"received {.^name} ($_)\";\n    }\n\n    # OUTPUT:\n    # received Str (foo)\n    # received Int (42)\n    # received Rat (0.5)\n\nSee also: L<C<tap>|/routine/tap> and L<C<Supplier>|/type/Supplier>.\n\nX<|Other languages,switch (given)>\nX<|Other languages,case statements (given)>\n=head1 X<given|Control flow,given>\n\nThe C<given> statement is Raku's topicalizing keyword in a similar way that\nC<switch> topicalizes in languages such as C. In other words, C<given>\nsets C<$_> inside the following block. The keywords for individual cases\nare C<when> and C<default>. The usual idiom looks like this:\n\n    my $var = (Any, 21, any <answer lie>).pick;\n    given $var {\n        when 21 { say $_ * 2 }\n        when 'lie' { .say }\n        default { say 'default' }\n    }\n\nThe C<given> statement is often used alone:\n\n    given 42 { .say; .Numeric; }\n\nThis is a lot more understandable than:\n\n    { .say; .Numeric; }(42)\n\n\n=head2 X<default and when|Control flow,default when>\n\nA block containing a C<default> statement will be left immediately\nwhen the sub-block after the C<default> statement is left. It is\nas though the rest of the statements in the block were skipped.\n\n    given 42 {\n        \"This says\".say;\n        $_ == 42 and ( default { \"This says, too\".say; 43; } );\n        \"This never says\".say;\n    }\n    # The above block evaluates to 43\n\nA C<when> statement will also do this (but a C<when> statement modifier\nwill I<not>.)\n\nIn addition, C<when> statements C<smartmatch> the topic (C<$_>) against\na supplied expression such that it is possible to check against values,\nregular expressions, and types when specifying a match.\n\n    for 42, 43, \"foo\", 44, \"bar\" {\n        when Int { .say }\n        when /:i ^Bar/ { .say }\n        default  { say \"Not an Int or a Bar\" }\n    }\n    # OUTPUT: «42␤43␤Not an Int or a Bar␤44␤Bar␤»\n\nIn this form, the C<given>/C<when> construct acts much like a set of\nC<if>/C<elsif>/C<else> statements. Be careful with the order of the\nC<when> statements. The following code says C<\"Int\"> not C<42>.\n\n    given 42 {\n        when Int { say \"Int\" }\n        when 42  { say 42 }\n        default  { say \"huh?\" }\n    }\n    # OUTPUT: «Int␤»\n\nWhen a C<when> statement or C<default> statement causes the outer\nblock to return, nesting C<when> or C<default> blocks do not count\nas the outer block, so you can nest these statements and still\nbe in the same \"switch\" just so long as you do not open a new block:\n\n    given 42 {\n        when Int {\n          when 42  { say 42 }\n          say \"Int\"\n        }\n        default  { say \"huh?\" }\n    }\n    # OUTPUT: «42␤»\n\nC<when> statements can smartmatch\nagainst L<Signatures|/language/syntax#Signature_literals>.\n\n=head2 X<proceed|Control flow,proceed> and X<succeed|Control flow,succeed>\n\nBoth C<proceed> and C<succeed> are meant to be used only from inside C<when>\nor C<default> blocks.\n\nThe C<proceed> statement will immediately leave the C<when> or C<default>\nblock, skipping the rest of the statements, and resuming after the block.\nThis prevents the C<when> or C<default> from exiting the outer block.\n\n=for code\ngiven * {\n    default {\n        proceed;\n        \"This never says\".say\n    }\n}\n\"This says\".say;\n\nThis is most often used to enter multiple C<when> blocks. C<proceed> will\nresume matching after a successful match, like so:\n\n    given 42 {\n        when Int   { say \"Int\"; proceed }\n        when 42    { say 42 }\n        when 40..* { say \"greater than 40\" }\n        default    { say \"huh?\" }\n    }\n    # OUTPUT: «Int␤»\n    # OUTPUT: «42␤»\n\nNote that the C<when 40..*> match didn't occur. For this to match\nsuch cases as well, one would need a C<proceed> in the C<when 42> block.\n\nThis is not like a C<C> C<switch> statement, because the C<proceed> does\nnot merely enter the directly following block, it attempts to match\nthe C<given> value once more, consider this code:\n\n    given 42 {\n        when Int { \"Int\".say; proceed }\n        when 43  { 43.say }\n        when 42  { 42.say }\n        default  { \"got change for an existential answer?\".say }\n    }\n    # OUTPUT: «Int␤»\n    # OUTPUT: «42␤»\n\n...which matches the L<C<Int>|/type/Int>, skips C<43> since the value doesn't match, matches\nC<42> since this is the next positive match, but doesn't enter the\nC<default> block since the C<when 42> block doesn't contain a C<proceed>.\n\nBy contrast, the C<succeed> keyword short-circuits execution and exits the\nentire C<given> block at that point. It may also take an argument to\nspecify a final value for the block.\n\n    say do given 42 {\n        when Int {\n            succeed \"Found\";\n            say \"never this!\";\n        }\n        when 42 { say 42 }\n        default { say \"dunno?\" }\n    }\n    # OUTPUT: «Found␤»\n\nIf you are not inside a when or default block, it is an error to try\nto use C<proceed> or C<succeed>.Also remember, the C<when> statement\nmodifier form does not cause any blocks to be left, and any C<succeed>\nor C<proceed> in such a statement applies to the surrounding clause,\nif there is one:\n\n    given 42 {\n        { say \"This says\" } when Int;\n        \"This says too\".say;\n        when * > 41 {\n           { \"And this says\".say; proceed } when * > 41;\n           \"This never says\".say;\n        }\n        \"This also says\".say;\n    }\n    # OUTPUT: «This says␤This says too␤And this says␤This also says␤»\n\n=head2 X<given as a statement|Control flow,given statement>\n\nC<given> can follow a statement to set the topic in the statement it follows.\n\n    .say given \"foo\";\n    # OUTPUT: «foo␤»\n\n    printf \"%s %02i.%02i.%i\",\n            <Mo Tu We Th Fr Sa Su>[.day-of-week - 1],\n            .day,\n            .month,\n            .year\n        given DateTime.now;\n    # OUTPUT: «Sa 03.06.2016»\n\n=head1 X<loop|Control flow,loop>\n\nThe C<loop> statement takes three statements in parentheses separated by C<;>\nthat take the roles of initializer, conditional and incrementer, respectively.\nThe initializer is executed once before the conditional is first tested. In case\nthe initializer involves a variable declaration, the variable is declared as a\nlexical variable in the loop's I<outer or containing> scope so that it can be\nused in code following the loop statement. The conditional is executed before\neach iteration and coerced to L<C<Bool>|/type/Bool>; if C<False> the loop is stopped. The\nincrementer is executed after each iteration, and before the conditional is\ntested again.\n\n    loop (my $i = 0; $i < 10; $i++) {       # A typical loop\n        say $i;\n    }\n\n    my @str = \"However Long\".comb;          # Our very own .chars routine:\n    loop (my $l = 0;;) {                    # Declare $l in outer scope\n        last if !@str[$l++]                 # and count chars until we hit\n    }                                       # an undefined element (Any)\n    say \"The string is {--$l} chars long.\";\n\nThe infinite loop does not require parentheses.\n\n=for code\nloop { say 'forever' }\n\nThe C<loop> statement may be used to produce values from the result of each\nrun of the attached block if it appears in lists:\n\n    (loop ( my $i = 0; $i++ < 3;) { $i * 2 }).say;               # OUTPUT: «(2 4 6)␤»\n    my @a = (loop ( my $j = 0; $j++ < 3;) { $j * 2 }); @a.say;   # OUTPUT: «[2 4 6]␤»\n    my @b = do loop ( my $k = 0; $k++ < 3;) { $k * 2 }; @b.say;  # same thing\n\nUnlike a C<for> loop, one should not rely on whether returned values are\nproduced lazily. It would probably be best to use C<eager> to guarantee that a\nloop whose return value may be used actually runs:\n\n    sub heads-in-a-row {\n        (eager loop (; 2.rand < 1;) { \"heads\".say })\n    }\n\n=head1 X<while, until|Control flow,while until>\n\nThe C<while> statement executes the block as long as its condition is\ntrue. So\n\n    my $x = 1;\n    while $x < 4 {\n        print $x++;\n    }\n    print \"\\n\";\n\n    # OUTPUT: «123␤»\n\nSimilarly, the C<until> statement executes the block as long as the\nexpression is false.\n\n    my $x = 1;\n    until $x > 3 {\n        print $x++;\n    }\n    print \"\\n\";\n\n    # OUTPUT: «123␤»\n\nThe condition for C<while> or C<until> can be parenthesized, but there\nmust be a space between the keyword and the opening parenthesis of the\ncondition.\n\nBoth C<while> and C<until> can be used as statement modifiers. E. g.\n\n   my $x = 42;\n   $x-- while $x > 12\n\nSee L<C<next>|#next>, L<C<last>|#last>, and related below for ways to\nfine-tune loop control.  Also see C<repeat/while> and C<repeat/until> for\nother loop syntax.\n\nAll these forms may produce a return value the same way C<loop> does.\n\n=head1 X<repeat/while, repeat/until|Control flow,repeat>\n\nExecutes the block I<at least once> and, if the condition allows, repeats\nthat execution. This differs from C<while>/C<until> in that the condition\nis evaluated at the end of the loop, even if it appears at the front.\n\n    my $x = -42;\n    repeat {\n        $x++;\n    } while $x < 5;\n    $x.say; # OUTPUT: «5␤»\n\n    repeat {\n        $x++;\n    } while $x < 5;\n    $x.say; # OUTPUT: «6␤»\n\n    repeat while $x < 10 {\n        $x++;\n    }\n    $x.say; # OUTPUT: «10␤»\n\n    repeat while $x < 10 {\n        $x++;\n    }\n    $x.say; # OUTPUT: «11␤»\n\n    repeat {\n        $x++;\n    } until $x >= 15;\n    $x.say; # OUTPUT: «15␤»\n\n    repeat {\n        $x++;\n    } until $x >= 15;\n    $x.say; # OUTPUT: «16␤»\n\n    repeat until $x >= 20 {\n        $x++;\n    }\n    $x.say; # OUTPUT: «20␤»\n\n    repeat until $x >= 20 {\n        $x++;\n    }\n    $x.say; # OUTPUT: «21␤»\n\nAll these forms may produce a return value the same way C<loop> does.\n\n=head1 X<once|Control flow,once>\n\nA block or statement prefixed with C<once> will be executed exactly once,\neven if placed inside a loop or a recursive routine.\n\n    my $guard;\n    loop {\n        once $guard = 3;\n        last if $guard-- <= 0;\n        once { put 'once' };\n        print 'many'\n    } # OUTPUT: «once␤manymanymany»\n\nThis works per \"clone\" of the containing code object, so:\n\n    ({ once 42.say } xx 3).map: {$_(), $_()}; # says 42 thrice\n\nNote that this is B<not> a thread-safe construct when the same clone of the same\nblock is run by multiple threads. Also remember that methods only have one\nclone per class, not per object.\n\n\n=head1 LABELs\n\nC<while>, C<until>, C<loop> and C<for> loops can all take a label, which can be\nused to identify them for C<next>, C<last>, and C<redo>. Nested loops are\nsupported, for instance:\n\n    OUTAHERE: while True  {\n        for 1,2,3 -> $n {\n            last OUTAHERE if $n == 2;\n        }\n    }\n\nLabels can be used also within nested loops to name each loop, for instance:\n\n=begin code\nOUTAHERE:\nloop ( my $i = 1; True; $i++ ) {\n  OUTFOR:\n    for 1,2,3 -> $n {\n      # exits the for loop before its natural end\n      last OUTFOR if $n == 2;\n  }\n\n  # exits the infinite loop\n  last OUTAHERE if $i >= 2;\n}\n=end code\n\n=head1 X<next|Control flow,next>\n\nThe C<next> command starts the next iteration of the loop. So the code\n\n=begin code\n\nmy @x = 1, 2, 3, 4, 5;\nfor @x -> $x {\n    next if $x == 3;\n    print $x;\n}\n=end code\n\nprints \"1245\".\n\nYou can also use C<next> in a C<map>: the above example then looks\nlike:\n\n=begin code\nmy @x = 1, 2, 3, 4, 5;\nprint @x.map: -> $x {\n    next if $x == 3;\n    $x\n}\n=end code\n\nprints \"1 2 4 5\" because a space is added between entries of a L<C<Seq>|/type/Seq>\nwhen it is stringified.  Note that that C<print> was not put inside\nthe block of the C<map>, as it generally considered bad practice to\nrun a C<map> for its side-effects (in this case, the C<print>.\n\nIf the L<C<NEXT> phaser|/language/phasers#NEXT> is present, it runs\nbefore the next iteration:\n\n=begin code\nmy Int $i = 0;\nwhile ($i < 10) {\n  if ($i % 2 == 0) {\n    next;\n  }\n\n  say \"$i is odd.\";\n\n  NEXT {\n    $i++;\n  }\n}\n# OUTPUT: «1 is odd.␤3 is odd.␤5 is odd.␤7 is odd.␤9 is odd.␤»\n=end code\n\nIn version 6.e.PREVIEW (available as of the 2021.07 Rakudo compiler\nrelease), it is also possible to return a value with the C<next>\nstatement.  This is particularly useful when using it in a C<map>:\n\n=begin code\nmy @x = 1, 2, 3, 4, 5;\nprint @x.map: -> $x {\n    next 42 if $x == 3;\n    $x\n}\n=end code\n\nprints \"1 2 42 4 5\".\n\nIn a L<whenever|/language/concurrency#whenever>\nblock, C<next> immediately exits the block for the current value:\n\n    react {\n        whenever Supply.interval(1) {\n            next if .is-prime;\n            say $_;\n            done if $_ == 4;\n        }\n    }\n\nprints \"0\", \"1\" and \"4\" - integers from 0 to 4 with primes skipped.\n\n*Since version 6.d, the C<next> command in a loop that collects its\nlast statement values returns C<Empty> for the iterations they run on.*\n\n=head1 X<last|Control flow,last>\n\nThe C<last> command immediately exits the loop in question.\n\n=begin code\nmy @x = 1, 2, 3, 4, 5;\nfor @x -> $x {\n    last if $x == 3;\n    print $x;\n}\n=end code\n\nprints \"12\".\n\nYou can also use C<last> in a C<map>: the above example then looks\nlike:\n\n=begin code\nmy @x = 1, 2, 3, 4, 5;\nprint @x.map: -> $x {\n    last if $x == 3;\n    $x\n}\n=end code\n\nprints \"1 2\" because a space is added between entries of a L<C<Seq>|/type/Seq> when\nit is stringified.  Note that that C<print> was not put inside the\nblock of the C<map>, as it generally considered bad practice to run\na C<map> for its side-effects (in this case, the C<print>.\n\nIf the L<C<LAST> phaser|/language/phasers#LAST> is present, it runs\nbefore exiting the loop:\n\n=begin code\nmy Int $i = 1;\nwhile ($i < 10) {\n  if ($i % 5 == 0) {\n    last;\n  }\n\n  LAST {\n    say \"The last number was $i.\";\n  }\n  NEXT {\n    $i++;\n  }\n}\n# OUTPUT: «The last number was 5.␤»\n=end code\n\nSince version 6.d, the C<last> command in a loop that collects its last\nstatement values returns C<Empty> for the iterations they run on.\n\nIn version 6.e.PREVIEW (available as of the 2021.07 Rakudo compiler\nrelease), it is also possible to return a value with the C<last>\nstatement.  This is particularly useful when using it in a C<map>:\n\n=begin code\nmy @x = 1, 2, 3, 4, 5;\nprint @x.map: -> $x {\n    last 42 if $x == 3;\n    $x\n}\n=end code\n\nprint \"1 2 42\".\n\n=head1 X<redo|Control flow,redo>\n\nThe C<redo> command restarts the loop block without evaluating the\nconditional again.\n\n=for code\nfor 1..5 -> $current-level {\n    state $total-attempts = 0;\n    $total-attempts++;\n    print(\"Entering #$current-level. \");\n    if $total-attempts %% 3 {\n        redo;\n    }\n}\n# OUTPUT: «Entering #1... Entering #2... Entering #3... Entering #3... Entering #4... Entering #5... Entering #5... »\n\n=head1 X<return|Control flow,return>\n\nThe sub C<return> will stop execution of a subroutine or method, run all\nrelevant L<phasers|/language/phasers#Block_phasers> and provide the\ngiven return value to the caller. The default return value is L<C<Nil>|/type/Nil>. If\na return L<type constraint|/language/signatures#Constraining_return_types> is\nprovided it will be checked unless the return value is L<C<Nil>|/type/Nil>. If the\ntype check fails the exception\nL<C<X::TypeCheck::Return>|/type/X::TypeCheck::Return> is thrown. If it\npasses a control exception is raised and can be caught with\nL<CONTROL|/language/phasers#CONTROL>.\n\nAny C<return> in a block is tied to the first L<C<Routine>|/type/Routine> in the outer\nlexical scope of that block, no matter how deeply nested. Please note\nthat a C<return> in the root of a package will fail at runtime. A\nC<return> in a block that is evaluated lazily (e.g. inside C<map>) may\nfind the outer lexical routine gone by the time the block is executed.\nIn almost any case C<last> is the better alternative. Please check\nL<the functions documentation|/language/functions#Return_values> for\nmore information on how return values are handled and produced.\n\n=head1 X<return-rw|Control flow,return-rw>\n\nThe sub C<return> will return values, not containers. Those are\nimmutable and will lead to runtime errors when attempted to be mutated.\n\n    sub s(){ my $a = 41; return $a };\n    say ++s();\n    CATCH { default { say .^name, ': ', .Str } };\n    # OUTPUT: «X::Multi::NoMatch.new(dispatcher …\n\nTo return a mutable container, use C<return-rw>.\n\n    sub s(){ my $a = 41; return-rw $a };\n    say ++s();\n    # OUTPUT: «42␤»\n\nThe same rules as for C<return> regarding phasers and control exceptions apply.\n\n=head1 X<fail|Control flow,fail>\n\nLeaves the current routine and returns the provided\nL<C<Exception>|/type/Exception> or L<C<Str>|/type/Str> wrapped inside a\nL<C<Failure>|/type/Failure>, after all relevant\nL<phasers|/language/phasers#Block_phasers> are executed. If the caller\nactivated fatal exceptions via the pragma C<use fatal;>, the exception is\nthrown instead of being returned as a L<C<Failure>|/type/Failure>.\n\n    sub f { fail \"WELP!\" };\n    say f;\n    CATCH { default { say .^name, ': ', .Str } }\n    # OUTPUT: «X::AdHoc: WELP!␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Language/create-cli.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"tutorial\")\n\n=TITLE Command line interface\n\n=SUBTITLE Creating your own CLI in Raku\n\nX<|Programs,command line arguments>\n=head1 Command line interface - an overview\n\nThe default command line interface of Raku scripts consists of three parts:\n\n=head2 Parsing the command line parameters into a L<C<Capture>|/type/Capture>\n\nThis looks at the values in L<@*ARGS|/language/variables#index-entry-@*ARGS>,\ninterprets these according to some policy, and creates a L<C<Capture>|/type/Capture>\nobject out of that. An alternative way of parsing may be provided by the developer\nor installed using a module.\n\n=head2 Calling a provided C<MAIN> subroutine using that capture\n\nStandard L<multi dispatch|/language/functions#Multi-dispatch>\nis used to call the C<MAIN> subroutine with the generated L<C<Capture>|/type/Capture> object.\nThis means that your C<MAIN> subroutine may be a C<multi sub>, each candidate\nof which is responsible for some part of processing the given command line\narguments.\n\n=head2 Creating / showing usage information if calling C<MAIN> failed\n\nIf multi dispatch failed, then the user of the script should be informed as\nwell as possible as to why it failed. By default, this is done by inspecting\nthe signature of each C<MAIN> candidate sub, and any associated Pod information.\nThe result is then shown to the user on STDERR (or on STDOUT if C<--help>\nwas specified). An alternative way of generating the usage information may\nbe provided by the developer or installed using a module.\n\nX<|Programs,MAIN>\n=head1 sub MAIN\n\nThe sub with the special name C<MAIN> will be executed after all relevant entry\nphasers (C<BEGIN>, C<CHECK>, C<INIT>, C<PRE>, C<ENTER>) have been run and\nthe L<mainline|/language/glossary#Mainline> of the script has been\nexecuted. No error will occur if there is no C<MAIN> sub: your script will\nthen just have to do the work, such as argument parsing, in the mainline of\nthe script.\n\nAny normal exit from the C<MAIN> sub will result in an exit code of C<0>,\nindicating success. Any return value of the C<MAIN> sub will be ignored.\nIf an exception is thrown that is not handled inside the C<MAIN> sub, then the\nexit code will be C<1>. If the dispatch to C<MAIN> failed, a usage message\nwill be displayed on STDERR and the exit code will be C<2>.\n\nThe command line parameters are present in the C<@*ARGS> dynamic variable\nand may be altered in the mainline of the script before the C<MAIN> unit is\ncalled.\n\nThe signature of (the candidates of the multi) sub C<MAIN> determines which\ncandidate will actually be called using the standard\nL<multi dispatch|/language/glossary#Multi-dispatch> semantics.\n\nA simple example:\n\n    # inside file 'hello.raku'\n    sub MAIN($name) {\n        say \"Hello $name, how are you?\"\n    }\n\nIf you call that script without any parameters, you get the following\nusage message:\n\n=begin code :lang<shell>\n$ raku hello.raku\nUsage:\n  hello.raku <name>\n=end code\n\nHowever, if you give a default value for the parameter, running the script\neither with or without specifying a name will always work:\n\n    # inside file 'hello.raku'\n    sub MAIN($name = 'bashful') {\n        say \"Hello $name, how are you?\"\n    }\n\n=begin code :lang<shell>\n$ raku hello.raku\nHello bashful, how are you?\n=end code\n\n=begin code :lang<shell>\n$ raku hello.raku Liz\nHello Liz, how are you?\n=end code\n\nAnother way to do this is to make C<sub MAIN> a C<multi>:\n\n    # inside file 'hello.raku'\n    multi MAIN()      { say \"Hello bashful, how are you?\" }\n    multi MAIN($name) { say \"Hello $name, how are you?\"   }\n\nWhich would give the same output as the examples above. Whether you should\nuse either method to achieve the desired goal is entirely up to you.\n\nIf you want to pass an indeterminate number of parameters to be dealt with in\nC<sub MAIN>, you can use L<slurpy parameters|/language/signatures#Slurpy_parameters>:\n\n    # inside file 'hello-all.raku'\n    sub MAIN(*@all) { for @all -> $name { say \"Hello, \" ~ $name } }\n\n=begin code :lang<shell>\n$ raku hello-all.raku peter paul mary\nHello, peter\nHello, paul\nHello, mary\n=end code\n\n=head2 Multiple named parameters, and C<where> clauses\n\nA more complicated example using a single positional and multiple\nnamed parameters, and also showing that C<where> clauses can also be applied\nto C<MAIN> arguments:\n\n=for code :method<False>\n# inside \"frobnicate.raku\"\nsub MAIN(\n  Str   $file where *.IO.f = 'file.dat',\n  Int  :$length = 24,\n  Bool :$verbose\n) {\n    say $length if $length.defined;\n    say $file   if $file.defined;\n    say 'Verbosity ', ($verbose ?? 'on' !! 'off');\n}\n\nThe clause C<where *.IO.f> checks that the string C<$file> corresponds to the name of a file that actually exists.\nThe part C<= 'file.dat'> specifies a default value for C<$file> in case no argument for it is given.\n\nIf a file C<file.dat> is present, a call with no arguments will work this way:\n=begin code :lang<shell>\n$ raku frobnicate.raku\n24\nfile.dat\nVerbosity off\n=end code\n\nOr this way with C<--verbose>:\n\n=begin code :lang<shell>\n$ raku frobnicate.raku --verbose\n24\nfile.dat\nVerbosity on\n=end code\n\nIf the file C<file.dat> is not present, or you've specified another filename\nthat doesn't exist, you would get the standard usage message created from\nintrospection of the C<MAIN> sub:\n\n=begin code :lang<shell>\n$ raku frobnicate.raku doesnotexist.dat\nUsage:\n  frobnicate.raku [--length=<Int>] [--verbose] [<file>]\n=end code\n\nSuch usage messages are generated completely automatically for you.\nIf they seem too terse, you can easily add more information to them.\n\n=head2 Improve usage messages with rakudoc comments\n\nThere's an easy way to make the autogenerated usage\nmessage better by providing hints using pod features:\n\n=for code :method<False>\n# inside \"frobnicate.raku\"\nsub MAIN(\n  Str   $file where *.IO.f = 'file.dat',  #= an existing file to frobnicate\n  Int  :$length = 24,                     #= length needed for frobnication\n  Bool :$verbose,                         #= required verbosity\n) {\n    say $length if $length.defined;\n    say $file   if $file.defined;\n    say 'Verbosity ', ($verbose ?? 'on' !! 'off');\n}\n\nWhich would improve the usage message like this:\n\n=begin code :lang<shell>\n$ raku frobnicate.raku doesnotexist.dat\nUsage:\n  frobnicate.raku [--length=<Int>] [--verbose] [<file>]\n\n    [<file>]          an existing file to frobnicate\n    --length=<Int>    length needed for frobnication\n    --verbose         required verbosity\n=end code\n\n=head2 Command lines and usage messages: more examples\n\nFrom release 2021.03, values to single named arguments can be separated by\nspaces too. Consider a C<demo> program with the following source:\n\n    subset name of Any where Str|True;\n    subset port of Str;\n    multi MAIN(\n        $file,\n        name :$profile,    #= Write profile information to a file\n        port :$debug-port, #= Listen for debugger connections on the specified port\n        Bool :v($verbose), #= Display verbose output\n\n    ) {}\n    multi MAIN(\"--process-files\", *@images) {}\n\nThis program generates the following usage message:\n\n=begin code :lang<text>\nUsage:\n  demo [--profile[=name]] [--debug-port=<port>] [-v] <file>\n  demo --process-files [<images> ...]\n\n    --profile[=name]       Write profile information to a file\n    --debug-port=<port>    Listen for debugger connections on the specified port\n    -v                     Display verbose output\n=end code\n\nThe following are valid ways to call C<demo>:\n\n=for code :lang<text>\ndemo --profile ~/foo\ndemo --profile=/tmp/bar ~/foo\ndemo --debug-port 4242 ~/foo\ndemo --debug-port=4242 ~/foo\ndemo -v ~/foo\ndemo --process-files *.jpg\n\nThese, however, are not valid\n\n=for code :lang<text>\ndemo --profile /tmp/bar ~/foo\ndemo --debug-port ~/foo\n\nThe first is invalid because C</tmp/bar> and C<~/foo> are both parsed as\npositional arguments, which means C<demo> was called with too many\npositional arguments.  The second is invalid because C<~/foo> is parsed\nas an argument to C<--debug-port>, and thus C<demo> lacks the required\npositional argument.\n\nHere's how it works; with Raku distinguishing between three types of options:\n\n=item Boolean options (like C<-v>), which I<never> take an argument; they\n   are ether present or absent.\n=item Options with a mandatory argument (like C<--debug-port>), which\n   always take an argument.  If you give them an argument with C<=>,\n   they will use that; if not, they'll take the following argument.\n=item Options with an optional argument (like C<--profile>), which are\n   valid both with and without an argument.  You can I<only> give these\n   arguments an option with the C<=> syntax; if there is a space after\n   the option, that means it was called without an argument.\n\nAnd here's the signature that produces each type of argument:\n\n=item Boolean options: A L<C<Bool>|/type/Bool> type constraint.\n=item Options with a mandatory argument: A type that does not\n    L<C<.ACCEPT>|/routine/ACCEPTS> a L<C<Bool>|/type/Bool>.\n=item Options with an optional argument: A type that C<.ACCEPTS> a\n   C<True> (because passing an option without an argument is equivalent\n   to passing C<True>)\n\n=head2 Aliases for named parameters\n\nAs any other subroutine, C<MAIN> can define\nL<aliases|/language/signatures#Argument_aliases> for its named parameters.\nIn particular, this can be used to define single-letter alternative names.\n\n=for code :method<False>\nsub MAIN(\n  Str   $file where *.IO.f = 'file.dat',  #= an existing file to frobnicate\n  Int  :l(:$length) = 24,                 #= length needed for frobnication\n  Bool :v(:$verbose),                     #= required verbosity\n) {\n    say $length if $length.defined;\n    say $file   if $file.defined;\n    say 'Verbosity ', ($verbose ?? 'on' !! 'off');\n}\n\nIn which case, these aliases will also be listed as alternatives with C<--help>:\n\n=begin code :lang<text>\nUsage:\n  frobnicate.raku [--size|--length=<Int>] [--verbose] [<file>]\n\n    [<file>]                 an existing file to frobnicate\n    -l|--length=<Int>        length needed for frobnication\n    -v|--verbose             required verbosity\n=end code\n\n=head2 Named arrays\n\nThe MAIN subroutine can also use a different kind of named parameter: the named array.\nThis enables, for instance, providing two different short arrays as arguments on a\ncommand line.\n\nDeclare a named-array parameter with C<:@> in sub MAIN's signature:\n\n    # inside file 'named-array.raku'\n    sub MAIN(:@n) {\n        .raku.say for @n\n    }\n\nYou can use this on the command line by repeating the named-array\nparameter with different values each time.\n\n=begin code :lang<shell>\n$ raku named-array.raku --n=foo --n=23 --n=6.3 --n=3e8 --n=2+2i --n=bar\n\"foo\"\nIntStr.new(23, \"23\")\nRatStr.new(6.3, \"6.3\")\nNumStr.new(300000000e0, \"3e8\")\nComplexStr.new(<2+2i>, \"2+2i\")\n\"bar\"\n=end code\n\n=head2 Enumerations\n\nL<C<Enumeration>|/type/Enumeration>s can be used in signatures with arguments converted\nautomatically to its corresponding C<enum> symbol:\n\n=begin code\nenum Flag  (\n    FLAG_FOO => 0b001,\n    FLAG_BAR => 0b010,\n    FLAG_BAZ => 0b100,\n);\n\nsub MAIN(Flag $flag = FLAG_FOO) {\n    say \"Flagging $flag with value $flag.value()\";\n}\n=end code\n\nThis will work correctly with\n\n=for code :lang<text>\nraku MAIN-enum.raku FLAG_BAZ\n# OUTPUT: «Flagging FLAG_BAZ with value 4␤»\n\nbut will die if called with something that is not a C<Flag>.\n\n\n=head2 X<C<%*SUB-MAIN-OPTS>|Variables,%*SUB-MAIN-OPTS>\n\nIt's possible to alter how arguments are processed before they're passed\nto C<sub MAIN {}> by setting options in the C<%*SUB-MAIN-OPTS> hash. Due to\nthe nature of dynamic variables, it is required to set up the\nC<%*SUB-MAIN-OPTS> hash and fill it with the appropriate settings.\nFor instance:\n\n    my %*SUB-MAIN-OPTS =\n      :named-anywhere,             # allow named variables at any location\n      :bundling,                   # allow bundling of named arguments\n      :coerce-allomorphs-to(Int),  # coerce allomorphic arguments to given type\n      :allow-no,                   # allow --no-foo as alternative to --/foo\n      :numeric-suffix-as-value,    # allow -j2 as alternative to --j=2\n    ;\n    sub MAIN ($a, $b, :$c, :$d) {\n        say \"Accepted!\"\n    }\n\nAvailable options are:\n\n=head3 X<C<named-anywhere>|Reference,named-anywhere>\n\nBy default, named arguments passed to the program (i.e., C<MAIN>)\ncannot appear after any positional argument. However, if\nC«%*SUB-MAIN-OPTS<named-anywhere>» is set to a true value, named arguments\ncan be specified anywhere, even after positional parameter. For example,\nthe above program can be called with:\n\n=begin code :lang<shell>\n$ raku example.raku 1 --c=2 3 --d=4\n=end code\n\n=head3 X<C<bundling>|Programs,command-line argument bundling>\n\nWhen C«%*SUB-MAIN-OPTS<bundling>» is set to a true value, single letter named\narguments can be bundled together with a single dash. The following two\ncommands are then equivalent:\n\n=begin code :lang<shell>\n$ raku example.raku -a -b -c\n$ raku example.raku -abc\n=end code\n\nBundled arguments can be understood as flags, that can neither be negated, nor\nassigned a value though:\n\n=begin code :lang<shell>\n$ raku example.raku -/a       # OK\n$ raku example.raku -a=asdf   # OK\n$ raku example.raku -abc=asdf # Error\n$ raku example.raku -/abc     # Error\n=end code\n\nThis option is only available starting in the 2020.10 release of the\nRakudo compiler.\n\n=head3 X<C<coerce-allomorphs-to>|Programs,command-line argument coercion>\n\nWhen C«%*SUB-MAIN-OPTS<coerce-allomorphs-to>» is set to a specific type,\nthen any L<allomorphic|/type/Allomorph> values will be coerced to that\ntype.  This can be helpful in any dispatch issues to C<MAIN>.\n\nThis option is only available starting in the 2020.12 release of the\nRakudo compiler.\n\n=head3 X<C<allow-no>|Programs,allow no- to negate>\n\nWhen C«%*SUB-MAIN-OPTS<allow-no>» is set to a true value, then negation\nof arguments on the command line can also be indicated by using the\nC<no-> instead of C</>.\n\n=begin code :lang<shell>\n$ raku example.raku --/foo    # named argument \"foo\" is False\n$ raku example.raku --no-foo  # same\n=end code\n\nThis option is only available starting in the 2022.12 release of\nthe Rakudo compiler.\n\n=head3 X<C<numeric-suffix-as-value>|Programs,simpler way for numeric values>\n\nWhen C«%*SUB-MAIN-OPTS<numeric-suffix-as-value>» is set to a true value,\nthen single letter arguments can have a numeric value specified as a suffix.\n\n=begin code :lang<shell>\n$ raku example.raku --j=2  # named argument \"j\" is 2\n$ raku example.raku -j2    # same\n=end code\n\nThis option is only available starting in the 2022.12 release of\nthe Rakudo compiler.\n\n=head2 X<C<is hidden-from-USAGE>|Reference,hidden-from-USAGE>\n\nSometimes you want to exclude a C<MAIN> candidate from being shown in any\nautomatically generated usage message. This can be achieved by adding\na C<hidden-from-USAGE> trait to the specification of the C<MAIN> candidate\nyou do not want to show. Expanding on an earlier example:\n\n    # inside file 'hello.raku'\n    multi MAIN() is hidden-from-USAGE {\n        say \"Hello bashful, how are you?\"\n    }\n    multi MAIN($name) {  #= the name by which you would like to be called\n        say \"Hello $name, how are you?\"\n    }\n\nSo, if you would call this script with just a named variable, you would get\nthe following usage:\n\n=begin code :lang<shell>\n$ raku hello.raku --verbose\nUsage:\n  hello.raku <name> -- the name by which you would like to be called\n=end code\n\nWithout the C<hidden-from-USAGE> trait on the first candidate, it would have\nlooked like this:\n\n=begin code :lang<shell>\n$ raku hello.raku --verbose\nUsage:\n  hello.raku\n  hello.raku <name> -- the name by which you would like to be called\n=end code\n\nWhich, although technically correct, doesn't read as well.\n\n=head1 X<Unit-scoped definition of C<MAIN>|Reference,unit (MAIN)>\n\nIf the entire program body resides within C<MAIN>, you can use the C<unit>\ndeclarator as follows (adapting an earlier example):\n\n=begin code :solo\nunit sub MAIN(\n  Str   $file where *.IO.f = 'file.dat',\n  Int  :$length = 24,\n  Bool :$verbose,\n);  # <- note semicolon here\n\nsay $length if $length.defined;\nsay $file   if $file.defined;\nsay 'Verbosity ', ($verbose ?? 'on' !! 'off');\n# rest of script is part of MAIN\n=end code\n\nNote that this is only appropriate if you can get by with just a single\n(only) C<sub MAIN>.\n\n=head2 X<sub USAGE|Tutorial,USAGE> and X<C«$*USAGE»|Tutorial,$*USAGE>\n\nIf no multi candidate of C<MAIN> is found for the given command line\nparameters, the sub C<USAGE> is called. If no such method is found,\nthe compiler will output a default usage message.\n\nIn the following example, we print a custom usage message via\na L<Q string|/language/quoting>\n(with the C<:c|/language/quoting#Interpolating_closures> flag enabling interpolation of curly braces,\nand the C<:to|/language/quoting#Heredocs:_:to> flag for stating it all as a heredoc):\n\n    #|(is it the answer)\n    multi MAIN(Int $i) { say $i == 42 ?? 'answer' !! 'dunno' }\n    #|(divide two numbers)\n    multi MAIN($a, $b){ say $a/$b }\n\n    sub USAGE() {\n        print Q:c:to/EOH/;\n        Usage: {$*PROGRAM-NAME} [number]\n\n        Prints the answer or 'dunno'.\n    EOH\n    }\n\nThe default usage message is available inside C<sub USAGE> via the read-only\nC<$*USAGE> variable. It will be generated based on available C<sub MAIN>\ncandidates and their parameters. As shown before, you can specify an\nadditional extended description for each candidate using a\nC<#|(...)> Pod block to set L«C<WHY>|/routine/WHY».\n\n\n=head1 Intercepting usage message generation (2018.10, v6.d and later)\n\nYou can replace or augment the default way of usage message generation\n(after a failed dispatch to MAIN) by supplying a C<GENERATE-USAGE> subroutine\nyourself, or by importing one from any of the\nL<Getopt|https://raku.land/?q=getopt> modules available in the\necosystem.\n\n=head2 X<sub GENERATE-USAGE|Subroutines,GENERATE-USAGE>\n\nThe C<GENERATE-USAGE> subroutine should accept a L<C<Callable>|/type/Callable> representing the\nC<MAIN> subroutine that didn't get executed because the dispatch failed.\nThis can be used for introspection. All the other parameters are the\nparameters that were set up to be sent to C<MAIN>. It should return the\nstring of the usage information you want to be shown to the user. An example\nthat will just recreate the L<C<Capture>|/type/Capture> that was created from processing the\narguments:\n\n    sub GENERATE-USAGE(&main, |capture) {\n        capture<foo>:exists\n          ?? \"You're not allowed to specify a --foo\"\n          !! &*GENERATE-USAGE(&main, |capture)\n    }\n\nYou can also use multi subroutines to create the same effect:\n\n    multi GENERATE-USAGE(&main, :$foo!) {\n        \"You're not allowed to specify a --foo\"\n    }\n    multi GENERATE-USAGE(&main, |capture) {\n        &*GENERATE-USAGE(&main, |capture)\n    }\n\nNote that the dynamic variable\nL<C<&*GENERATE-USAGE>|/language/variables#&*GENERATE-USAGE> is available to\nperform the default usage message generation so you don't have to reinvent the\nwhole wheel if you don't want to.\n\n\n=head1 Intercepting CLI argument parsing (2018.10, v6.d and later)\n\nYou can replace or augment the default way of argument parsing by supplying an\nC<ARGS-TO-CAPTURE> subroutine yourself, or by importing one from any of\nthe L<Getopt|https://raku.land/?q=getopt> modules available\nin the ecosystem.\n\n=head2 X<sub ARGS-TO-CAPTURE|Subroutines,ARGS-TO-CAPTURE>\n\nThe C<ARGS-TO-CAPTURE> subroutine should accept two parameters: a\nL<C<Callable>|/type/Callable> representing the C<MAIN> unit to be executed (so it\ncan be introspected if necessary) and an array with the arguments from the\ncommand line. It should return a L<C<Capture>|/type/Capture> object that will be\nused to dispatch the C<MAIN> unit. The following is a B<very> contrived example\nthat will create a L<C<Capture>|/type/Capture> depending on some keyword that was entered (which\ncan be handy during testing of a command line interface of a script):\n\n    sub ARGS-TO-CAPTURE(&main, @args --> Capture) {\n        # if we only specified \"frobnicate\" as an argument\n        @args == 1 && @args[0] eq 'frobnicate'\n          # then dispatch as MAIN(\"foo\",\"bar\",verbose => 2)\n          ?? Capture.new( list => <foo bar>, hash => { verbose => 2 } )\n          # otherwise, use default processing of args\n          !! &*ARGS-TO-CAPTURE(&main, @args)\n    }\n\nNote that the dynamic variable\nL<C<&*ARGS-TO-CAPTURE>|/language/variables#&*ARGS-TO-CAPTURE> is available to\nperform the default command line arguments to L<C<Capture>|/type/Capture> processing so you don't\nhave to reinvent the whole wheel if you don't want to.\n\n=head2 X<sub RUN-MAIN|Subroutines,RUN-MAIN>\n\n    sub RUN-MAIN(&main, $mainline, :$in-as-argsfiles)\n\nThis routine allows complete control over the handling of C<MAIN>. It gets a\nL<C<Callable>|/type/Callable> that is the C<MAIN> that should be executed, the return value of the\nmainline execution and an additional named variable: C<:in-as-argsfiles> which\nwill be C<True> if STDIN should be treated as C<$*ARGFILES>.\n\nIf C<RUN-MAIN> is not provided, a default one will be run that looks for\nsubroutines of the old interface, such as C<MAIN_HELPER> and C<USAGE>. If\nfound, it will execute following the \"old\" semantics.\n\n=begin code\nclass Hero {\n    has @!inventory;\n    has Str $.name;\n    submethod BUILD( :$name, :@inventory ) {\n        $!name = $name;\n        @!inventory = @inventory\n    }\n}\n\nsub new-main($name, *@stuff ) {\n    Hero.new(:name($name), :inventory(@stuff) ).raku.say\n}\n\nRUN-MAIN( &new-main, Nil );\n=end code\n\nThis will print the name (first argument) of the generated object.\n\n\n=head1 Intercepting MAIN calling (before 2018.10, v6.e)\n\nAn older interface enabled one to intercept the calling to C<MAIN> completely.\nThis depended on the existence of a C<MAIN_HELPER> subroutine that would be\ncalled if a C<MAIN> subroutine was found in the mainline of a program.\n\nThis interface was never documented. However, any programs using this\nundocumented interface will continue to function until C<v6.e>. From v6.d\nonward, the use of the undocumented API will cause a C<DEPRECATED> message.\n\nEcosystem modules can provide both the new and the old interface for\ncompatibility with older versions of Perl 6 and Raku: if a newer Raku recognizes\nthe new (documented) interface, it will use that. If there is no new\ninterface subroutine available, but the old C<MAIN_HELPER> interface is,\nthen it will use the old interface.\n\nIf a module developer decides to only offer a module for C<v6.d> or higher,\nthen the support for the old interface can be removed from the module.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/distributions/configuration-structure.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Modules\") :category(\"tutorial\")\n\n=TITLE Distributing modules: the configuration and structure\n\n=SUBTITLE How to structure and configure Raku modules for distribution\n\n=head1 Preparing the module\n\nFor a module to work in any of the ecosystems, it needs to follow a certain\nstructure.\n\nWe strongly suggest that you use some of the\nL<Module builder and authoring tools|/language/distributions/tools>\nthat are available.\n\n=head1 Quick Overview using C<fez>\n\nTo create a skeleton, run the commands:\n\n=begin code :lang<text>\nfez init MyNew::Module\n\n# Will create the following:\n# MyNew--Module/\n# ├── lib\n# │   └── MyNew\n# │       └── Module.rakumod\n# ├── META6.json\n# └── t\n#     └── 00-use.rakutest\n=end code\n\nIf you need to add new modules, classes, resources, build-depends, or depends you may use the following (respectively,\nthese resources will automatically be added to META6.json):\n\n=begin code :lang<text>\nfez module My::New::Module\nfez module --class My::New::Module\nfez resource xyz\nfez depends --build Build::Dependency\nfez depends Runtime::Dependency\n=end code\n\n=head1 Full Explanation\n\nEven if you're intending to use fez or an equivalent (and you should), the\nfollowing can be useful reading before releasing a module, so that, as you\ndevelop your module, you will be aware of the requirements and customs\nregarding how a module is structured.\n\nThe META6.json file specifies the various metadata of your project and\ntheir uses; this has various sections that align with the filesystem of\nyour module, so the following sections will step through the filesystem\nand the META6.json file in parallel; some sections belong only to one\nor the other, but many belong to both.  The filesystem items will be\nreferred to as C<file> or C<directory>, and the META6.json sections\nwill be referred to as a C<key> or a C<section>.\n\n=head2 The module root directory and META6.json file\n\nThe attributes in this file are analyzed by the\nL<C<META6>|https://github.com/jonathanstowe/META6> class. They are divided into\noptional, mandatory and I<customary>. Mandatory are the ones you need to insert\ninto your file, and customary are those used by the current Raku ecosystem and\npossibly displayed on the module page if it's published, but you have no\nobligation to use it.\n\nCreate a project directory named after your module. For\nexample, if your module is C<Vortex::TotalPerspective>, then create a\nproject directory named C<Vortex-TotalPerspective>.\n\nMake your project directory look like this:\n\n=begin code :lang<text>\nVortex-TotalPerspective/\n├── META6.json\n├── LICENSE\n├── README.md\n├── lib\n│   └── Vortex\n│       └── TotalPerspective.rakumod\n└── bin\n│    └── vortex\n└── t\n    └── basic.rakutest\n=end code\n\nMake your X<C<META6.json>|Reference,META6.json> file look something like this:\n\n=begin code :allow<R> :lang<javascript>\n{\n    \"name\" : \"Vortex::TotalPerspective\",\n    \"description\" : \"Wonderful simulation to get some perspective.\",\n    \"source-url\" : \"git://github.com/R<you>/Vortex-TotalPerspective.git\"\n    \"auth\" : \"github:SomeAuthor\",\n    \"authors\" : [ \"R<Your Name>\" ],\n    \"tags\": [\n      \"Vortex\", \"Total\", \"Perspective\"\n    ],\n    \"depends\" : [ ],\n    \"build-depends\" : [ ],\n    \"test-depends\" : [ ],\n    \"license\" : \"Artistic-2.0\",\n\n    \"version\" : \"0.0.1\",\n    \"api\"  : \"1\",\n    \"raku\" : \"6.c\",\n\n    \"provides\" : {\n        \"Vortex::TotalPerspective\" : \"lib/Vortex/TotalPerspective.rakumod\"\n    },\n    \"resources\" : [ ],\n}\n=end code\n\nThere are more fields described in the\nL<C<META> design documents|https://github.com/Raku/old-design-docs/blob/master/S22-package-format.pod#META6.json>,\nbut not all of these are\nimplemented by existing package managers. Hence you should stick to the fields\ndescribed in the above example block to ensure compatibility with existing\npackage managers such as C<zef>. You can also check\nL<Moritz Lenz's repository of all modules for examples|https://github.com/moritz/perl6-all-modules/search?l=JSON&q=META6.json&type=>,\nbut bear in mind that some of them might use fields, such as C<source-type>\nabove, which are currently ignored.\n\n=head3 The C<name> key\n\nThe C<name> key is compulsory, and C<zef> will fail if you do not include it.\nEven if you have created a META6.json file just to express the dependencies\nfor a series of scripts, this section must be included.\n\n=head3 The C<description> key\n\nThe C<description> field is also mandatory, and includes a short\ndescription of the module.\n\n=head3 The C<source-url> key\n\nC<source-url> indicates the URL of the repository where the module is\ndeveloped; this is one of the customary modules if you are going to publish it\nin the module ecosystem. The current module ecosystem will link this URL from\nthe project description. N<Some old modules also provide a C<source-type> field,\nwhich was used to indicate the kind of source control system, generally C<git>,\nwhich can be used to download the module. However, this field is nowadays\nignored by C<zef> and the rest of the tools.>\n\nSee also the C<auth> section, below.\n\n=head3 The C<auth> and C<authors> sections\n\nThe C<authors> section includes a list of all the module authors. In\nthe case there is only one author, a single element list must be\nsupplied. This field is optional.\n\nThe C<auth> section identifies the author in GitHub or other repository\nhosting site, such as Bitbucket or GitLab. This field is I<customary>,\nsince it's used to identify the author in the ecosystem, and opens the\npossibility of having modules with the same name and different authors.\n\n=head3 The C<tags> section\n\nThe C<tags> section is also optional. It is used to describe\nthe module in the Raku ecosystem.\n\n=head3 The C<depends>, C<build-depends>, and C<test-depends> sections\n\nThe C<depends>, C<build-depends>, and C<test-depends> sections include different modules that\nare used in those phases of the of installation. All are optional, but\nif present must contain the required modules for those\nphases. These dependencies might optionally use\nL<C<Version>|/type/Version> specification strings; C<zef> will check for the\npresence and versions of these modules and install or upgrade them if needed.\n\n=for code :lang<JSON>\n//...\n\"depends\": [\n       \"URI\",\n       \"File::Temp\",\n       \"JSON::Fast\",\n       \"Pod::To::BigPage:ver<0.5.0+>\",\n       \"Pod::To::HTML:ver<0.6.1+>\",\n       \"OO::Monitors\",\n       \"File::Find\",\n       \"Test::META\"\n],\n//...\n\nAdditionally, C<depends> can be either an array as above or a hash that uses two\nkeys, C<runtime> and C<build>, whose function should be self-descriptive, and\nwhich are used, for instance,\nL<in C<Inline::Python>|https://github.com/niner/Inline-Python/blob/master/META6.json>:\n\n=for code :lang<JSON>\n//...\n\"depends\" : {\n        \"build\": {\n            \"requires\": [\n                \"Distribution::Builder::MakeFromJSON\",\n                {\n                    \"from\" : \"bin\",\n                    \"name\" : {\n                        \"by-distro.name\" : {\n                            \"macosx\" : \"python2.7-config\",\n                            \"debian\" : \"python2.7-config\",\n                            \"\" : \"python2-config\"\n                        }\n                    }\n                }\n            ]\n        },\n        \"runtime\": {\n            \"requires\": [\n                \"python2.7:from<native>\"\n            ]\n        }\n}, // ...\n\nIn general, the array form will be more than enough for most cases.\n\n=head3 The C<README.md> file\n\nThe C<README.md> file is a\nL<markdown-formatted|https://help.github.com/articles/markdown-basics/>\ntext file, which will later be automatically rendered as HTML by GitHub/GitLab for modules kept\nin those places, or by L<raku.land|https://raku.land> website for modules\naccessible with L<zef|/language/faq#Is_there_a_repository_of_third_party_library_modules_for_Raku?>.\n\n=head3 The C<LICENSE> file and key\n\n=item Regarding the C<LICENSE> file, if you have no other preference,\nyou might just use the same one that Rakudo Raku uses. Just\ncopy/paste the raw form of L<its license|https://github.com/rakudo/rakudo/blob/master/LICENSE>\ninto your own C<LICENSE> file.\n\n=item The license field in META6.json\nshould be one of the standardized names listed here:\nL<https://spdx.org/licenses/>. In the case of the B<Artistic 2.0> license, which\n    is what many of our ecosystem modules use, its identifier is\n    C<Artistic-2.0>. Having standardized identifiers make it easy for humans\n    and computers alike to know which license was actually used by looking at\n    the metadata!\n\n=item If you can't find your license on C<spdx.org> or you use your own license,\nyou should put the license's name in the license field. For more details see\nL<https://github.com/Raku/old-design-docs/blob/master/S22-package-format.pod#license>.\n\n=head2 The versioning keys\n\n=head3 The C<version> key\n\nFor choosing a version numbering scheme, try and use \"major.minor.patch\" (see\nL<the spec on versioning|https://github.com/Raku/old-design-docs/blob/master/S11-modules.pod#Versioning> for\nfurther details). This will go into the C<version> key of C<META6.json>. This\nfield is optional, but used by installation to match against installed version,\nif one exists.\n\n=head3 The C<api> key\n\nOptionally, you can set an C<api> field. Incrementing this indicates\nthat the interface provided by your module is not backwards compatible\nwith a previous version. You can use it if you want to adhere to\nL<Semantic Versioning|https://semver.org>. A best practice is to simply\nkeep the C<api> field to the same value as your major version number. A\ndependency can then depend on your module by including an C<:api> part,\nwhich will ensure backwards incompatible releases will not be pulled in.\n\n=head3 The C<raku> key\n\nSet C<raku> version to the minimum Raku version your module works with. This\nfield is mandatory. Use C<6.c> if your module is valid for Christmas release and\nnewer ones, use C<6.d> if it requires, at least the Diwali version.\n\n=head2 The C<provides> section and the C<lib> directory\n\nIf your project contains other modules that help the main module do\nits job, they should go in your lib directory like so:\n\n=begin code :lang<text>\nlib\n└── Vortex\n    ├── TotalPerspective.rakumod\n    └── TotalPerspective\n        ├── FairyCake.rakumod\n        └── Gargravarr.rakumod\n=end code\n\nIn the C<provides> section, include all the namespaces provided by your\ndistribution and that you wish to be installed; only module files that are\nexplicitly included here will be installed and available with C<use> or\nC<require> in other programs. This field is mandatory.\n\nIn the C<provides> object (object in the JSON sense), the key is the module\nname, the value is the path from the module root to the file in the lib/\ndirectory.\n\n=head2 The C<bin> directory\n\nPrograms and scripts that you need in the C<$PATH> for execution need\nto be included in the C<bin> directory; these will be copied to whatever\ndirectory your installed Rakudo distribution has allotted for executables;\ntypically this will be C</path/to/installation/share/perl6/site/bin/>, a folder\nthat should be available in C<$PATH>. I<Note: the perl6 path component predates the\nlanguage name change.>\n\n=head2 The C<resources> directory and section\n\nThe C<resources> section is optional, but if present, should contain a list\nof the files in your C<resources> directory that you wish to be installed.\nThese will be installed with hashed names alongside your library files.\n\nIf you have any additional files (such as templates or a dynamic\nlibrary) that you wish to have installed so you can access them at\nruntime, they should be placed in a C<resources> subdirectory of your project, e.g.:\n\n=begin code :lang<text>\nresources\n└── templates\n        └── default-template.mustache\n=end code\n\nThe file must then be referenced in C<META6.json> (see below for more on\nC<META6.json>) so that the distribution path can be provided to the program.\n\n=begin code :lang<javascript>\n{\n    \"name\" : \"Vortex::TotalPerspective\",\n    \"provides\" : {\n        \"Vortex::TotalPerspective\" : \"lib/Vortex/TotalPerspective.rakumod\"\n    },\n    \"resources\": [ \"templates/default-template.mustache\"]\n}\n=end code\n\nThe additional file can then be accessed inside module code; see the section\non the %?RESOURCES variable, below.\n\n=head3 X<The C<$?DISTRIBUTION> variable|Modules,%?DISTRIBUTION>\n\nThe L<C<$?DISTRIBUTION>|/syntax/$?DISTRIBUTION> variable\nis only populated within files listed in the C<provides>\nsection (usually those in the C<lib> directory).  If you\nwant to use it outside that (i.e. in your tests), you'll\nneed to provide a L<C<Routine>|/type/Routine> that returns it.\n\n=head3 X<The C<%?RESOURCES> variable|Modules,%?RESOURCES>\n\nNote the\nexample here is returning a L<C<Distribution::Resource>|/type/Distribution::Resource> object. It should\nB<not> be considered as a path to an object in the filesystem.\n\n=begin code\nmy $template-text = %?RESOURCES<templates/default-template.mustache>.slurp;\n=end code\n\nB<Note>: Accessing these files via C<%?RESOURCES> is B<not>\ngetting their installed locations or an L<C<IO>|/type/IO> class: You are accessing a L<C<Distribution::Resource>|/type/Distribution::Resource>.\nobject indexed on the name provided.  It's important to be careful in\nhow you use these to avoid embedding the filename at compile-time\nwhich might be different than the location the file is in at runtime.\n\nThe L<C<$?RESOURCES>|/syntax/$?RESOURCES> variable\nis only populated within files listed in the C<provides>\nsection (usually those in the C<lib> directory).  If you\nwant to use it outside that (i.e. in your tests), you'll\nneed to provide a L<C<Routine>|/type/Routine> that returns it.\n\nAn example of how to use this might be:\n\n=begin code\nsub     MyModule-resources(*@resources) is export(:tests) {\n        for @resources -> $resource-filename {\n                my $resource = %?RESOURCES{$resource-filename};\n                # Just some error-checking code\n                if $resource !~~ Distribution::Resource {\n                        note \"Could not find resource '$resource-filename' in distribution\";\n                        say qx{ls -laF ; ls -laF resources ; cat META6.json};\n                        say \"Resource is: \" ~ $resource.raku;\n                        say \"Resource keys are: \" ~ %?RESOURCES.keys.raku;\n                }\n        }\n\n        return %?RESOURCES;\n}\n=end code\n\n...and then to use it in your code:\n\n=begin code :skip-test<incomplete example>\nuse     TOP :tests :DEFAULT;    # Note that the :tests here matches the \"is export\" above\n\nmy $resource-name = 'templates/default-template.mustache';\nmy $resources = MyModule-resources($resource-name);\nmy $resource = $resources{$resource-name};\nmy $file_handle = $resource.open();\n=end code\n\nThe above will produce quite a bit of debugging output if\nthe resource isn't found (but will continue regardless).\nThis can be handy when running in a remote location, such\nas a GitHub action.\n\n=head2 The C<t> directory, and testing your module\n\nIf you don't yet have any tests, you can leave out the C<t>\ndirectory and C<basic.rakutest> file for now. For more information on how to write\ntests (for now), you might have a look at how other modules use\nL<C<Test>|/type/Test>.\n\nThe L<C<Test::META> module| https://github.com/jonathanstowe/Test-META/> can\nhelp\nyou check the correctness of the META6.json file; this module will check for all\nthe mandatory fields and that the type used for all of them is correct.\n\nIf you want to test your module you can use the following command to install the\nmodule directly from the module folder you just created.\n\n=begin code :lang<shell>\nzef install ./your-module-folder\n=end code\n\nNote that doing so precompiles and installs your module. If you make changes to\nthe source, you'll need to re-install the module.\n(See C<use lib> L<pragma|/language/pragmas#lib>, C<-I>\ncommand line switch, or C<RAKULIB> environment variable, to include a path to your\nmodule source while developing it, so you don't have to install it at all).\n\nSee also the C<test-depends> section, above.\n\n=head2 Documenting your modules\n\nTo document your modules, use L<Raku Pod|/language/pod> markup inside them.\nModule documentation is most appreciated and will be especially important once\nthe Raku module directory (or some other site) begins rendering Pod docs as\nHTML for easy browsing. If you have extra docs (in addition to the Pod docs in\nyour module(s)), create a C<doc> directory for them. Follow the same folder\nstructure as the C<lib> directory like so:\n\n=begin code :lang<text>\ndoc\n└── Vortex\n    └── TotalPerspective.rakudoc\n=end code\nN<Note, described above is a minimal project directory. If your project\ncontains scripts that you'd like distributed along with your module(s),\nput them in a C<bin> directory. If you'd like a graphical logo to\nappear next to your module at the module directory, create a\nC<logotype> directory and put into it a C<logo_32x32.png> file. At some\npoint, you might also consider adding C<CONTRIBUTORS>, C<NEWS>,\nC<TODO>, or other files.>\n\n=head2 Build hooks\n\nIf your module requires extra processing during installation to fully\nintegrate with and use non-Raku operating system resources, you may\nneed to add a X<C<Build.rakumod>|Reference,Build.rakumod> file (a \"build hook\") to the top-level directory. It will\nbe used by the C<zef> installer as the first step in the installation process.\nSee the README for C<zef> for a brief example. Also see various usage scenarios in existing\necosystem modules such as C<zef> itself.\n\n\n=head1 Documentation about Modules\n\n=item1 L<Using Modules: An Introduction|/language/using-modules/introduction>\n=item2 L<Using Modules: Finding and Installing|/language/using-modules/finding-installing>\n=item2 L<Using Modules: The Code|/language/using-modules/code>\n\n=item1 L<Making Modules: Introduction|/language/making-modules/introduction>\n=item2 L<Making Modules: The Code|/language/making-modules/code>\n\nWant to distribute your modules?\n=item1 L<Distributions: An introduction|/language/distributions/introduction>\n=item2 L<Distributions: The Configuration and Structure|/language/distributions/configuration-structure> (this page)\n=item2 L<Distributions: The Tools|/language/distributions/tools>\n=item2 L<Distributions: Testing|/language/distributions/testing>\n=item2 L<Distributions: Uploading|/language/distributions/uploading>\n\n\n=end pod\n"
  },
  {
    "path": "doc/Language/distributions/introduction.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Modules\") :category(\"tutorial\")\n\n=TITLE Distributions: an introduction\n\n=SUBTITLE Distributions and how they work\n\n=head2 Terminology\n\nThis is a point in the Raku journey where we need to get specific with some of\nthe terminology, so here are some of the terms which will be used:\n\n=item1 B<compunit>: A compilation unit, or compunit for short, is a piece of\nRaku code that is analyzed and compiled as a single unit. Typically, this\ncomes from a source file on disk, but what's inside an EVAL also counts as\nsuch.\n\n=item1 B<script>: A script refers to a compilation unit that is provided to\nRaku as the entry point for execution. In an invocation like raku foo.raku,\nwe say that foo.raku is first compiled and then executed. In Rakudo Raku, in\nthis case, the results of the compilation only exist in memory.\n\n=item1 B<module>: A module refers to a compilation unit that is used by a\nscript, or by another module used from a script. A module must also be\ncompiled before it can be made use of. (There is nothing preventing a given\nsource file serving as both a script and a module depending on how it is used).\n\n=item1 B<distribution>: A distribution is a set of zero or more scripts and\nmodules that are released together, along with some metadata and potentially\nresources and tests.\n\n=head2 Basic structure\n\nModule distributions (in the I<set of related source files> sense) in Raku\nhave the same structure as any distribution in the Perl family of languages:\nthere is a main project directory containing a C<README> and a C<LICENSE> file,\na C<lib> directory for the source files, which may be individually referred to\nas modules and/or may themselves define modules with the C<module> keyword N<As\nL<synopsis S11|https://github.com/Raku/old-design-docs/blob/master/S11-modules.pod#Units> says: Confusing? Yes it\nis.> , a C<t> directory for tests, and possibly a C<bin> directory for\nexecutable programs and scripts.\n\nSee L<filename extensions|/language/filename-extensions> for current and historic\nextensions for various file types.\n\n=head1 Distributions\n\nIt is important in this section to repeat the note at the beginning of this\ndocument, namely that there is a difference between a B<Raku> C<distribution>,\nwhich approximates a I<module> in other languages, and a B<Raku>\nL<module declaration|/language/syntax#package,_module,_class,_role,_and_grammar_declaration>.\nThe reason for this is that a single file may contain a number of C<class>,\nC<module>, C<role> etc declarations, or these declarations may be spread between\ndifferent files. In addition, when a C<distribution> is published (see\nL<Distributing modules|/language/distributions/introduction>) it may be\nnecessary to provide access to other resources, such as callable utilities.\n\nB<Raku> also allows for a single distribution to provide multiple C<module>s\nthat can be C<use>d (or C<require>d etc). The information about a distribution\nis contained in the C<META6.json> file in the distribution's root directory. See\nbelow for more about C<META6.json>. Each entity that the B<distribution> allows\nto be C<use>d (or C<require>d etc), also called a C<module>, is placed in the\nC<provides> section of the C<META6.json> (as specified below).\n\nIt should also be noted that when writing the C<depends> section of the\nC<META6.json> file, it is the name of the B<distribution> that is listed, not\nthe name of the C<module> that is desired. Although, for very many entities,\nthe name of the I<distribution> and the name of the I<module> are the same.\nAnother global effect of the C<depends> list in a distribution made available to\nthe Ecosystem, is that package managers, e.g. C<zef>, can look for C<module>\nnames in all distributions available.\n\nGiven this arrangement, the B<rakudo> compiler, or a package manager such as\nB<zef>, can obtain all the information needed about each C<module> from a\nC<META6.json> file in a directory.\n\n=head2 Contact information\n\nTo discuss module development in general, or if your module would\nfill a need in the ecosystem, naming, etc., you can use the\nL<#raku on irc.libera.chat|irc://irc.libera.chat/#raku> IRC channel.\n\nA repository to discuss tooling issues is available at\nL<https://github.com/Raku/toolchain-bikeshed>.\n\n\n=head1 Documentation about Modules\n\n=item1 L<Using Modules: An Introduction|/language/using-modules/introduction>\n=item2 L<Using Modules: Finding and Installing|/language/using-modules/finding-installing>\n=item2 L<Using Modules: The Code|/language/using-modules/code>\n\n=item1 L<Making Modules: Introduction|/language/making-modules/introduction>\n=item2 L<Making Modules: The Code|/language/making-modules/code>\n\nWant to distribute your modules?\n=item1 L<Distributions: An introduction|/language/distributions/introduction> (this page)\n=item2 L<Distributions: The Configuration and Structure|/language/distributions/configuration-structure>\n=item2 L<Distributions: The Tools|/language/distributions/tools>\n=item2 L<Distributions: Testing|/language/distributions/testing>\n=item2 L<Distributions: Uploading|/language/distributions/uploading>\n\n\n=end pod\n"
  },
  {
    "path": "doc/Language/distributions/testing.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Modules\") :category(\"tutorial\")\n\n=TITLE Distributions: testing\n\n=SUBTITLE Testing your distribution of modules\n\n=item L<General guide to testing|/language/testing>\n\nA testing program such as B<Perl>'s C<prove> or the B<Raku>\nequivalent L<prove6|https://raku.land/zef:leont/App::Prove6> can be\nrun in the root directory of the B<distribution> as, e.g.,\n\n=for code :lang<shell>\nprove -e 'raku -I.'\n\nor\n\n=for code :lang<shell>\nprove6 -I.\n\nIn both cases, the testing program looks for a directory C<t/> and runs the test\nprograms there (see L<Testing|/language/testing>).\n\nThe parameter B<-I.>, rather than B<-Ilib>, in the examples above is significant\nbecause then the compiler will inspect the C<META6.json> file in the root\ndirectory of the B<distribution>.\n\nIf you are just beginning to develop a module (or series of modules), and you\nhave not decided what to call or where to place the code (perhaps splitting it\ninto several C<*.rakumod> files), but assuming all the module files are under\nthe C<lib/> directory, then it is possible to use\n\n=for code :lang<shell>\nprove6 -Ilib\n\nThis is deceptive. A distribution may pass all the tests based on local files,\nand it may pass release steps, but the distribution (and the\nmodules/classes/roles it contains) may not be automatically installed. To give a\ncommon example, but not the only way this problem can manifest itself, if the\ndistribution is listed in the C<depends> section of another distribution, and a\nuser is trying to install the other distribution using C<zef> (or a package\nmanager using the same testing regime), perhaps using a CLI command C<zef\ninstall --deps-only .>, then C<zef> arranges for the tests of the dependent\nmodules based on B<-I.> and not C<-Ilib>. This will lead to B<rakudo> errors\ncomplaining about the absence of named B<compunits> unless the B<META6.json>\nfile is correct.\n\n=head1 The C<use-ok> Test\n\nThe most basic test that should be run for each C<compunit> that is defined for\nthe distribution is\n\n=for code :preamble<use Test>\nuse-ok 'MyModule';\n\nassuming inside C<META6.json> there is a line such as\n\n=for code :lang<json>\nprovides: { \"MyModule\": \"lib/MyModule.rakumod\" },\n\n=head1 The C<meta-ok> test\n\nIt is also highly recommended to use the C<Test::META> C<meta-ok> test, which\nverifies the validity of the C<META6.json> file. If you wish to add a\ndistribution (containing modules) to the C<Ecosystem>, then this test will be applied to the\ndistribution.\n\n=head1 Extended Tests\n\nSince C<meta-ok> only needs to be tested by the developer/maintainer of a\ndistribution, it can be within a set of extended tests in another directory, e.g.\nC</xt>. This is because C<prove6>, for example, only runs the tests in C<t/> by\ndefault. Then to run the extended tests:\n\n=for code :lang<shell>\nprove6 -I. xt/\n\nIndeed it is becoming common practice by B<Raku> community developers to place\nthe extensive testing of a distribution in C<xt/> and to put minimal I<sanity>\ntests in C<t/>. Extensive testing is essential for development and quality\ncontrol, but it can slow down the installation of popular distributions.\n\nAn alternative to placing the C<meta-ok> test in an extended test directory, but\nto ensure that it is only run when a developer or maintainer wants to, is to\nmake the test dependent on an environment variable, e.g., in\nC<t/99-author-test.rakutest> there is the following code\n\n=begin code\nuse Test;\n\nplan 1;\n\nif ?%*ENV<AUTHOR_TESTING> {\n    require Test::META <&meta-ok>;\n    meta-ok;\n    done-testing;\n} else {\n    skip-rest \"Skipping author test\";\n    exit;\n}\n=end code\n\nThen when the distribution is being tested by the developer, use\n\n=for code :lang<shell>\n    AUTHOR_TESTING=1 prove6 -I.\n\n\n=head1 Non-Core Testing Tools\n\nSome community modules for testing module quality:\n\n=item L<Test::META|https://raku.land/zef:jonathanstowe/Test::META>      Test your META6.json file\n=item L<Test::Output|https://raku.land/zef:raku-community-modules/Test::Output>  Test the output to STDOUT and STDERR your program generates\n=item L<Test::Screen|https://raku.land/github:skids/Proc::Screen>  Use B<GNU screen> to test full screen VT applications\n=item L<Test::When|https://raku.land/zef:raku-community-modules/Test::When>  Control when your tests are run (author testing, online testing, etc.)\n\nSee also L<Distributions: Tools|/language/distributions/tools> for a general list of module-related tooling.\n\n\n=head1 Documentation about Modules\n\n=item1 L<Using Modules: An Introduction|/language/using-modules/introduction>\n=item2 L<Using Modules: Finding and Installing|/language/using-modules/finding-installing>\n=item2 L<Using Modules: The Code|/language/using-modules/code>\n\n=item1 L<Making Modules: Introduction|/language/making-modules/introduction>\n=item2 L<Making Modules: The Code|/language/making-modules/code>\n\nWant to distribute your modules?\n=item1 L<Distributions: An introduction|/language/distributions/introduction>\n=item2 L<Distributions: The Configuration and Structure|/language/distributions/configuration-structure>\n=item2 L<Distributions: The Tools|/language/distributions/tools>\n=item2 L<Distributions: Testing|/language/distributions/testing> (this page)\n=item2 L<Distributions: Uploading|/language/distributions/uploading>\n\n\n=end pod\n"
  },
  {
    "path": "doc/Language/distributions/tools.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Modules\") :category(\"tutorial\")\n\n=TITLE Distributions: the tools\n\n=SUBTITLE What can help you write/test/improve your distributions of modules\n\nHere is a list of distributions that you can find in the Raku ecosystem\nwhich aim to make the experience of developing Raku modules\nmore fun.\n\n=head1 Distribution builder and authoring tools\n\nSome distributions and tools to help you with generating files that are part\nof a distribution of modules.\n\n=item L<App::Mi6|https://raku.land/zef:skaji/App::Mi6>     Minimal authoring tool for Raku\n=item L<META6|https://raku.land/zef:jonathanstowe/META6>        Do things with Raku C<META> files\n=item L<rakudoc|https://raku.land/zef:coke/rakudoc>        Generate documentation end-products\n\n=head1 Distribution Testing Tools\n\n=head2 Core Distributions\n\n=item L«C<Test>|/type/Test»    Test routines (see L<tutorial|/language/testing>)\n\n=head2 Non-Core Distributions\n\nSome community modules for testing module quality:\n\n=item L<Test::META|https://raku.land/zef:jonathanstowe/Test::META>      Test your META6.json file\n=item L<Test::Output|https://raku.land/zef:raku-community-modules/Test::Output>  Test the output to STDOUT and STDERR your program generates\n=item L<Test::Screen|https://raku.land/github:skids/Proc::Screen>  Use B<GNU screen> to test full screen VT applications\n=item L<Test::When|https://raku.land/zef:raku-community-modules/Test::When>  Control when your tests are run (author testing, online testing, etc.)\n\n=head1 Sample distributions\n\nDistributions that exist only as minimalist examples, tests for installers,\nor skeletons.\n\n=item L<Foo|https://raku.land/github:ugexe/Foo> A module with two distributions of different versions\n\nSee also L<Other Foo Modules|https://raku.land/?q=Foo>\n\n=head1 Useful Core Modules\n\nThe Rakudo implementation has a few modules included you may want to use; please\nnote that the implementation is not part of the Raku specification and thus\nmight be subject to change without prior notice. The following is a list of\nthem, along with links to their source code.\n\nX<|Modules,CompUnit (Rakudo classes)>\n=head2 C<CompUnit::*> modules and roles\n\nThese modules are mostly used by distribution build tools, and are not intended\nto be used (at least until version 6.c) by the final user.\n\n=item L«C<CompUnit::Repository::Staging>|https://github.com/rakudo/rakudo/blob/main/lib/CompUnit/Repository/Staging.rakumod».\n=item L<C<CompUnit::Repository::(FileSystem|Installation|AbsolutePath|Unknown|NQP|Perl6|RepositoryRegistry)>|https://github.com/rakudo/rakudo/blob/main/src/core.c/CompUnit/RepositoryRegistry.rakumod>.\n\n=head2 Other modules\n\n=item L«C<Pod::To::Text>|https://github.com/rakudo/rakudo/blob/main/lib/Pod/To/Text.rakumod»    Used by several external modules\n=item L«C<experimental>|https://github.com/rakudo/rakudo/blob/main/lib/experimental.rakumod»\n(L<documentation|/language/pragmas#experimental>)\n=item L«C<newline>|https://github.com/rakudo/rakudo/blob/main/lib/newline.rakumod»\n\n=head1 C<NativeCall> Assistance Tools\n\n=head2 Core modules\n\n=item L«C<NativeCall>|https://github.com/rakudo/rakudo/blob/main/lib/NativeCall.rakumod»    Native Calling Interface (L<docs|/language/nativecall>)\n=item L«C<NativeCall::Types>|https://github.com/rakudo/rakudo/blob/main/lib/NativeCall/Types.rakumod»    Used by C<NativeCall>\n=item L«C<NativeCall::Compiler::GNU>|https://github.com/rakudo/rakudo/blob/main/lib/NativeCall/Compiler/GNU.rakumod»    Used by C<NativeCall>\n=item L«C<NativeCall::Compiler::MSVC>|https://github.com/rakudo/rakudo/blob/main/lib/NativeCall/Compiler/MSVC.rakumod»    Used by C<NativeCall>\n\n=head2 Non-Core Modules\n\nHere some modules to help you work with NativeCall (for calling non-Raku libraries).\n\n=item L<NativeHelpers::Array|https://raku.land/zef:jonathanstowe/NativeHelpers::Array>  Provides routines to deal with CArray\n=item L<App::GPTrixie|https://raku.land/github:Skarsnik/App::GPTrixie>                Generate NativeCall code from C headers file\n=item L<NativeCall::TypeDiag|https://raku.land/github:Skarsnik/NativeCall::TypeDiag>  Provides routines to test your CStruct\n\n\n\n=head1 Documentation about Modules\n\n=item1 L<Using Modules: An Introduction|/language/using-modules/introduction>\n=item2 L<Using Modules: Finding and Installing|/language/using-modules/finding-installing>\n=item2 L<Using Modules: The Code|/language/using-modules/code>\n\n=item1 L<Making Modules: Introduction|/language/making-modules/introduction>\n=item2 L<Making Modules: The Code|/language/making-modules/code>\n\nWant to distribute your modules?\n=item1 L<Distributions: An introduction|/language/distributions/introduction>\n=item2 L<Distributions: The Configuration and Structure|/language/distributions/configuration-structure>\n=item2 L<Distributions: The Tools|/language/distributions/tools> (this page)\n=item2 L<Distributions: Testing|/language/distributions/testing>\n=item2 L<Distributions: Uploading|/language/distributions/uploading>\n\n\n=end pod\n"
  },
  {
    "path": "doc/Language/distributions/uploading.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Modules\") :category(\"tutorial\")\n\n=TITLE Distributions: uploading\n\n=SUBTITLE How to upload your distribution to the ecosystem\n\nIf you've written a Raku module and would like to share it with the\ncommunity, we'd be delighted to have it listed in the\nL<Raku modules directory|https://raku.land>. C<:)>\n\nThe B<zef ecosystem> uses the L<C<fez> module uploader|https://raku.land/zef:tony-o/fez>\nutility. Use of the C<fez> command is the way to distribute your module.\n\nThe process of sharing your module consists of two steps, preparing the module,\nand uploading the module to one of the ecosystems mentioned above.\n\nMore details on preparing your module can be found on the pages linked from\nL<Distributions: An Introduction|/language/distributions/introduction>.\n\n=head2 Upload your module to zef ecosystem\n\nIf you want to use the I<zef> ecosystem then you need to register your username\nusing C<fez>.\n\n=item Install fez if you haven't done so already\n\n=begin code :lang<shell>\nzef install fez\n=end code\n\n=item Register your user with zef's ecosystem\n\n=begin code :lang<shell>\nfez register\n>>= Email: your@email.com\n>>= Username: username\n>>= Password:\n>>= registration successful, requesting auth key\n>>= login successful, you can now upload dists\n=end code\n\n=item Now you can upload your module!\n\nBefore doing the following, ensure your C<META6.json> file's C<auth> matches C«zef:<username>» and then:\n\n=begin code :lang<shell>\nfez upload\n>>= Vortex::TotalPerspective:ver<0.1.2>:auth<zef:username> looks OK\n>>= Hey! You did it! Your dist will be indexed shortly\n=end code\n\n=head3 Versioning and fez\n\n=item To prevent changes to a versioned distribution (remember a distribution may contain more than\none module), only B<one> upload of a distribution per version is permitted. If a developer makes changes to\ncode in a repository, the changes will not be reflected in the C<fez> system. So changes to code must be\naccompanied by a bump in the version number and the new version uploaded to C<fez>.\n\nB<That's it! Thanks for contributing to the Raku community!>\n\nIf you'd like to try out installing your module, use the X<zef|Reference,zef> module\ninstaller tool which is included with Rakudo Star Raku:\n\n=begin code :lang<shell>\nzef install Vortex::TotalPerspective\n=end code\n\nThis will download your module to its own working directory (C<~/.zef>),\nbuild it there, and install the module into your local Raku installation\ndirectory.\n\nTo use C<Vortex::TotalPerspective> from your scripts, just write\nC<use Vortex::TotalPerspective>, and your Raku implementation will\nknow where to look for the module file(s).\n\n=head2 Deprecated ecosystems\n\nThere have been three ways to distribute a module, but the CPAN and P6C ways\nhave been deprecated; please use the zef/fez method instead.  However, no\nmatter the method, all modules will be indexed on the L<raku.land|https://raku.land> website.\n\n\n=head1 Documentation about Modules\n\n=item1 L<Using Modules: An Introduction|/language/using-modules/introduction>\n=item2 L<Using Modules: Finding and Installing|/language/using-modules/finding-installing>\n=item2 L<Using Modules: The Code|/language/using-modules/code>\n\n=item1 L<Making Modules: Introduction|/language/making-modules/introduction>\n=item2 L<Making Modules: The Code|/language/making-modules/code>\n\nWant to distribute your modules?\n=item1 L<Distributions: An introduction|/language/distributions/introduction>\n=item2 L<Distributions: The Configuration and Structure|/language/distributions/configuration-structure>\n=item2 L<Distributions: The Tools|/language/distributions/tools>\n=item2 L<Distributions: Testing|/language/distributions/testing>\n=item2 L<Distributions: Uploading|/language/distributions/uploading> (this page)\n\n\n=end pod\n\n"
  },
  {
    "path": "doc/Language/enumeration.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Enumeration\n\n=SUBTITLE An example using the enum type\n\nThe C<enum> type is much more complex in Raku than in some other languages,\nand the details are found in L<its type description|/language/typesystem#enum>.\n\nThis short document will give a simple example of its use as is the usual\npractice in C-like languages.\n\nSay we have a program that needs to write to various directories; we want a\nfunction that, given a directory name, tests it for (1) its existence and (2)\nwhether it can be written to by the user of the program; this implies that there\nare three possible states from the user perspective: either you can write\n(C<CanWrite>), or there is no directory (C<NoDir>) or the directory exists, but\nyou cannot write (C<NoWrite>). The results of the test will determine what\nactions the program takes next.\n\n=begin code\nenum DirStat <CanWrite NoDir NoWrite>;\nsub check-dir-status($dir --> DirStat) {\n    if $dir.IO.d {\n        # dir exists, can the program user write to it?\n        my $f = \"$dir/.tmp\";\n        spurt $f, \"some text\";\n        CATCH {\n            # unable to write for some reason\n            return NoWrite;\n        }\n        # if we get here we must have successfully written to the dir\n        unlink $f;\n        return CanWrite;\n    }\n    # if we get here the dir must not exist\n    return NoDir;\n}\n\n# test each of three directories by a non-root user\nmy @dirs = (\n    '/tmp',  # normally writable by any user\n    '/',     # writable only by root\n    '~/tmp'  # a non-existent dir in the user's home dir\n);\nfor @dirs -> $dir {\n    my $stat = check-dir-status $dir;\n    say \"status of dir '$dir': $stat\";\n    if $stat ~~ CanWrite {\n        say \"  user can write to dir: $dir\";\n    }\n}\n# output\n#   status of dir '/tmp': CanWrite\n#     user can write to dir: /tmp\n#   status of dir '/': NoWrite\n#   status of dir '~/tmp': NoDir\n=end code\n\n=end pod\n"
  },
  {
    "path": "doc/Language/exceptions.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Exceptions\n\n=SUBTITLE Using exceptions in Raku\n\nExceptions in Raku are objects that hold information about errors. An\nerror can be, for example, the unexpected receiving of data or a network\nconnection no longer available, or a missing file. The information that\nan exception object stores is, for instance, a human-readable message\nabout the error condition, the backtrace of the raising of the error,\nand so on.\n\nAll built-in exceptions inherit from L<C<Exception>|/type/Exception>, which\nprovides some basic behavior, including the storage of a backtrace and an\ninterface for the backtrace printer.\n\n=head1 Typed exceptions\n\nTyped exceptions are intended for use to indicate any of several\npredefined error conditions. Each of these provides information\nabout the error, and when thrown may be caught by code intended\nto handle that kind of error. L<C<Exception>|/type/Exception>s\ncan be delayed, that is, generated for handling but not thrown,\nby wrapping them in a L<C<Failure>|/type/Failure> object.\n\nFor example, if while executing C<.frobnicate> on an object, a needed path\nC<foo/bar> becomes unavailable, then an\nL<C<X::IO::DoesNotExist>|/type/X::IO::DoesNotExist> exception can be thrown:\n\n=begin code\nmethod frobnicate($path) {\n    X::IO::DoesNotExist.new(:$path, :trying(\"frobnicate\")).throw\n      unless $path.IO.e;\n    # do the actual frobnication\n}\n=end code\n\n=begin code :preamble<sub frobnicate() {}>\nfrobnicate(\"foo/bar\");\n# OUTPUT: «Failed to find 'foo/bar' while trying to do '.frobnicate'\n#          in block <unit> at my-script.raku:1»\n=end code\n\nNote how the object has provided the backtrace with information about what\nwent wrong. A user of the code can now more easily find and correct the\nproblem.\n\nInstead of calling the C<.throw> method on the L<C<X::IO::DoesNotExist>|/type/X::IO::DoesNotExist>\nobject, one can also use that object as a parameter to C<die>:\n\n=begin code :preamble<my $path>\ndie X::IO::DoesNotExist.new(:$path, :trying(\"frobnicate\"));\n=end code\n\n=head1 I<Ad hoc> exceptions\n\nIf you call L<C<.throw>|/type/Exception#method_throw>,\nL<C<die>|/type/Exception#routine_die>, or\nL<C<fail>|/type/Exception#routine_fail> on an argument that is not\nsome type of L<C<Exception>|/type/Exception>, then that argument gets wrapped in an\nL<C<X::AdHoc>|/type/X::AdHoc> object which is then used by the call.\n\nFor example, you can call L<C<die>|/type/Exception#routine_die>\non a string describing the error, and that string will become the\nC<message> of the L<C<X::AdHoc>|/type/X::AdHoc> exception:\n\n    die \"oops, something went wrong\";\n    # OUTPUT: «oops, something went wrong in block <unit> at my-script.raku:1␤»\n\nIt is worth noting that C<die> prints the error message to the standard error\nC<$*ERR>.\n\nL<C<X::AdHoc>|/type/X::AdHoc> is an L<C<Exception>|/type/Exception> type like any\nother, but the intent is for use as a default type; it should not\nbe used in cases for which specific L<C<Exception>|/type/Exception> types have already\nbeen provided.  It's probably not helpful to have a specific catch\nhandler for the type of L<C<X::AdHoc>|/type/X::AdHoc>.\n\n=head1 X<Catching exceptions|Language,CATCH>\n\nIt's possible to handle exceptional circumstances by supplying a C<CATCH> block:\n\n=begin code :preamble<my $path>\nCATCH {\n    when X::IO { $*ERR.say: \"some kind of IO exception was caught!\" }\n}\nX::IO::DoesNotExist.new(:$path, :trying(\"frobnicate\")).throw\n\n# OUTPUT: «some kind of IO exception was caught!»\n=end code\n\nHere, we are saying that if any exception of type L<C<X::IO>|/type/X::IO> occurs, then the\nmessage C<some kind of IO exception was caught!> will be sent to I<stderr>,\nwhich is what C<$*ERR.say> does, getting displayed on whatever constitutes the\nstandard error device in that moment, which will probably be the console by\ndefault.\n\nNote that the match target is a role. To allow user defined exceptions\nto match in the same manner, they must implement the given role. Just\nexisting in the same namespace will make them look alike but won't match\nin a C<CATCH> block.\n\nA C<CATCH> block places any exception thrown in its topic variable\n(C<$_>), thus it's possible to catch and handle various categories of\nexceptions inside a C<when> block. To handle all exceptions, use a\nC<default> statement. This example prints out almost the same\ninformation as the normal backtrace printer. Note that the I<dot>\nmethods apply to C<$_>, which holds the\nL<C<Exception>|/type/Exception> within the C<CATCH> block.\n\n    CATCH {\n         default {\n             $*ERR.say: .message;\n             for .backtrace.reverse {\n                 next if .file.starts-with('SETTING::');\n                 next unless .subname;\n                 $*ERR.say: \"  in block {.subname} at {.file} line {.line}\";\n             }\n         }\n    }\n\nWhile this is a very common pattern, it is not strictly necessary to use\nC<default> or C<when> in a C<CATCH> block. This is done to prevent the\ncontrol flow from reaching the end of the block where, unless the\nexception has been L<resumed|#Resuming_of_exceptions>, the exception\nwill continue to be thrown.  Allowing this can be used for logging\npurposes, for instance:\n\n=for code\n# In the outermost block of a script...\nmy IO::Handle:D $log = open sprintf('logs/%d-%d.txt', $*INIT-INSTANT, $*PID), :a;\nCATCH { $log.printf: \"[%d] Died with %s: %s$?NL\", now, .^name, .message }\nEND   { $log.close }\n\nThe C<CATCH> block semantics apply to the B<entire> lexical scope\nin which it is defined, B<regardless> of where it is defined inside that\nlexical scope.  It is therefore advised to put any C<CATCH> block at the\nstart of the lexical scope to which they apply so that the casual reader\nof the code can immediately see that there is something special going on.\n\n=head2 Exception handlers and enclosing blocks\n\nAfter a CATCH has handled the exception, the block enclosing the C<CATCH> block\nis exited.\n\nIn other words, even when the exception is handled successfully, the I<rest of\nthe code> in the enclosing block will never be executed.\n\n  die \"something went wrong ...\";\n\n  CATCH {\n      # will definitely catch all the exception\n      default { .Str.say; }\n  }\n\n  say \"This won't be said.\";   # but this line will be never reached since\n                               # the enclosing block will be exited immediately\n  # OUTPUT: «something went wrong ...␤»\n\nCompare with this:\n\n  {\n\n    CATCH {\n        default { .Str.say; }\n    }\n\n    die \"something went wrong ...\";\n\n  }\n\n  say \"Hi! I am at the outer block!\"; # OUTPUT: «Hi! I am at the outer block!␤»\n\nSee L<Resuming of exceptions|/language/exceptions#Resuming_of_exceptions>, for\nhow to return control back to where the exception originated.\n\n=head1 X<C<try> blocks|Language,try blocks>\n\nA C<try> block is a normal block which implicitly turns on the\nL<C<use fatal> pragma|/language/pragmas#fatal> and\nincludes an implicit C<CATCH> block that drops the exception, which\nmeans you can use it to contain them. Caught exceptions are stored\ninside the C<$!> variable, which holds a value of type L<C<Exception>|/type/Exception>.\n(Note that immediately after a C<try> block, if no L<C<Exception>|/type/Exception>\nhad been thrown, then C<$!> will be undefined.)\n\nA normal block like this one will simply fail:\n\n=for code\n{\n    my $x = +\"a\";\n    say $x.^name;\n} # OUTPUT: «Failure␤»\n\nHowever, a C<try> block will contain the exception and put it into the\nC<$!> variable:\n\n=begin code\ntry {\n    my $x = +\"a\";\n    say $x.^name;\n}\n\nif $! { say \"Something failed!\" } # OUTPUT: «Something failed!␤»\nsay $!.^name;                     # OUTPUT: «X::Str::Numeric␤»\n=end code\n\nAny exception that is thrown in such a block will be caught by a\nC<CATCH> block, either implicit or provided by the user. In the latter\ncase, any unhandled exception will be rethrown. If you choose not to\nhandle the exception, they will be contained by the block.\n\n=begin code\ntry {\n    die \"Tough luck\";\n    say \"Not gonna happen\";\n}\n\ntry {\n    fail \"FUBAR\";\n}\n=end code\n\nX<|Tutorial,resume (Exceptions)>\nIn both C<try> blocks above, exceptions will be contained within the\nblock, but the C<say> statement will not be run. We can handle them,\nthough:\n\n    class E is Exception { method message() { \"Just stop already!\" } }\n\n    try {\n        E.new.throw; # this will be local\n\n        say \"This won't be said.\";\n    }\n\n    say \"I'm alive!\";\n\n    try {\n        # NOTE: Raku allows you to place the CATCH block anywhere in the\n        # scope of the enclosing block. Some prefer it at the top for\n        # visibility, others at the end.\n        CATCH {\n            when X::AdHoc { .Str.say; .resume }\n        }\n\n        die \"No, I expect you to DIE Mr. Bond!\";\n\n        say \"I'm immortal.\";\n\n        E.new.throw;\n\n        say \"No, you don't!\";\n    }\n\nWhich would output:\n\n    =begin code :lang<text>\n    I'm alive!\n    No, I expect you to DIE Mr. Bond!\n    I'm immortal.\n    Just stop already!\n      in block <unit> at exception.raku line 21\n    =end code\n\nThis is because the C<CATCH> block is handling just the L<C<X::AdHoc>|/type/X::AdHoc> exception\nthrown by the C<die> statement, but not the C<E> exception. In the\nabsence of a C<CATCH> block, all exceptions will be contained and\ndropped, as indicated above. C<resume> will resume execution right after\nthe exception has been thrown; in this case, in the C<die> statement.\nPlease consult the section on\nL<resuming of exceptions|/language/exceptions#Resuming_of_exceptions>\nfor more information on this.\n\nA C<try> block is a normal block and as such, uses its last statement\nas its return value. We can therefore use it as a right-hand\nside.\n\n=begin code\nsay try { +\"99999\" } // \"oh no\"; # OUTPUT: «99999␤»\nsay try { +\"hello\" } // \"oh no\"; # OUTPUT: «oh no␤»\n=end code\n\nTry blocks support C<else> blocks indirectly by returning the return\nvalue of the expression or L<C<Nil>|/type/Nil> if an exception was thrown.\n\n    with try +\"♥\" {\n        say \"this is my number: $_\"\n    } else {\n        say \"not my number!\"\n    }\n    # OUTPUT: «not my number!␤»\n\nC<try> can also be used with a statement instead of a block, that is, as a\nL<statement prefix|/language/statement-prefixes#try>:\n\n=begin code\nsay try \"some-filename.txt\".IO.slurp // \"sane default\";\n# OUTPUT: «sane default␤»\n=end code\n\nWhat C<try> actually causes is, via the C<use fatal> pragma, an immediate throw\nof the exceptions that happen within its scope, but by doing so the C<CATCH>\nblock is invoked from the point where the exception is thrown, which defines its\nscope.\n\n=begin code\nmy $error-code = \"333\";\nsub bad-sub {\n    die \"Something bad happened\";\n}\ntry {\n    my $error-code = \"111\";\n    bad-sub;\n\n    CATCH {\n        default {\n            say \"Error $error-code \", .^name, ': ',.Str\n        }\n    }\n}\n# OUTPUT: «Error 111 X::AdHoc: Something bad happened␤»\n=end code\n\n\n=head1 Throwing exceptions\n\nExceptions can be thrown explicitly with the L<C<die>|/type/Exception#routine_die>\nroutine and with the L<C<.throw>|/type/Exception#method_throw>\nmethod of an L<C<Exception>|/type/Exception> object. In addition,\nunhandled L<C<Failure>|/type/Failure> objects will throw when garbage-collected.\n\nThis example throws an L<C<X::AdHoc>|/type/X::AdHoc> exception, catches it and allows the code\nto continue from the point of the exception by calling the C<.resume> method.\n\n    {\n        X::AdHoc.new(:payload<foo>).throw;\n        \"OHAI\".say;\n        CATCH {\n            when X::AdHoc { .resume }\n        }\n    }\n\n    \"OBAI\".say;\n\n    # OUTPUT: «OHAI␤OBAI␤»\n\nIf the C<CATCH> block doesn't match the exception thrown, then the\nexception's payload is passed on to the backtrace printing mechanism.\n\n    {\n        X::AdHoc.new(:payload<foo>).throw;\n        \"OHAI\".say;\n        CATCH {  }\n    }\n\n    \"OBAI\".say;\n\n    # OUTPUT: «foo\n    #          in block <unit> at my-script.raku:1»\n\nThis next example doesn't resume from the point of the exception. Instead,\nit continues after the enclosing block, since the exception is caught, and then\ncontrol continues after the C<CATCH> block.\n\n    {\n        X::AdHoc.new(:payload<foo>).throw;\n        \"OHAI\".say;\n        CATCH {\n            when X::AdHoc { }\n        }\n    }\n\n    \"OBAI\".say;\n\n    # OUTPUT: «OBAI␤»\n\nC<throw> can be viewed as the method form of C<die>, just that in this\nparticular case, the sub and method forms of the routine have different\nnames.\n\n=head1 Delaying exceptions as failures\n\nAs noted above in L<I<Ad hoc> exceptions|/language/exceptions#Ad_hoc_exceptions>,\nin addition to L<C<throw>|/routine/throw> and L<C<die>|/routine/die>, you can also\ncall L<C<fail>|/routine/fail> on an exception in order to handle it later.\nThis is a usual thing to do if you want to return the exception to the caller\nfor them to handle.\n\nIf the resulting L<C<Failure>|/type/Failure> object is returned into sink\ncontext (that is, not handled), it's the same as if you had called C<die> or\nC<throw>. If it is instead returned into Boolean context or checked for\ndefinedness, then it is considered \"handled\" and does not throw. If it is\nassigned to a variable, the throw is delayed until the variable is\ngarbage-collected if it hasn't been handled before that time.\n\nFor example, assuming you don't have permission to create a new directory at\nthe root level, then C<mkdir \"/test\"> will return a L<C<Failure>|/type/Failure>:\n\n    mkdir \"/test\";              # Returns Failure into sink context, acts like die()\n    my $result = mkdir \"/test\"; # throws when garbage-collected unless handled by then\n    so mkdir \"/test\";           # Failure \"handled\", doesn't die\n    if mkdir \"/test\" {          # Failure also \"handled\", doesn't die\n        ...                     # mkdir was successful\n    }\n    unless mkdir \"/test\" {\n        ...                     # Here we can handle the Failure (for real)\n    }\n\n=head1 Resuming of exceptions\n\nExceptions interrupt control flow and divert it away from the statement\nfollowing the statement that threw it. Any exception handled by the\nuser can be resumed and control flow will continue with the statement\nfollowing the statement that threw the exception. To do so, call the\nmethod C<.resume> on the exception object.\n\n    CATCH { when X::AdHoc { .resume } }         # this is step 2\n\n    die \"We leave control after this.\";         # this is step 1\n\n    say \"We have continued with control flow.\"; # this is step 3\n\nResuming will occur right after the statement that has caused the exception, and\nin the innermost call frame:\n\n=begin code\nsub bad-sub {\n    die \"Something bad happened\";\n    return \"not returning\";\n}\n\n{\n    my $return = bad-sub;\n    say \"Returned $return\";\n    CATCH {\n        default {\n            say \"Error \", .^name, ': ', .Str;\n            $return = '0';\n            .resume;\n        }\n    }\n}\n# OUTPUT:\n# Error X::AdHoc: Something bad happened\n# Returned not returning\n=end code\n\nIn this case, C<.resume> is getting to the C<return> statement that happens\nright after the C<die> statement. Please note that the assignment to C<$return>\nis taking no effect, since the C<CATCH> statement is happening I<inside> the\ncall to C<bad-sub>, which, via the C<return> statement, assigns the C<not\nreturning> value to it.\n\n=head1 Uncaught exceptions\n\nIf an exception is thrown and not caught, it causes the program to exit with a\nnon-zero status code, and typically prints a message to the standard error\nstream of the program. This message is obtained by calling the C<gist> method\non the exception object. You can use this to suppress the default behavior of\nprinting a backtrace along with the message:\n\n    class X::WithoutLineNumber is X::AdHoc {\n        multi method gist(X::WithoutLineNumber:D:) {\n            $.payload\n        }\n    }\n    die X::WithoutLineNumber.new(payload => \"message\")\n\n    # prints \"message\\n\" to $*ERR and exits, no backtrace\n\n=head1 Control exceptions\n\nControl exceptions are raised when throwing an Exception which does the\nL<C<X::Control>|/type/X::Control> role (since Rakudo 2019.03). They are\nusually thrown by certain L<keywords|/language/phasers#CONTROL> and are\nhandled either automatically or by the appropriate L<phaser|/language/phasers#Loop_phasers>.\nAny unhandled control exception is converted to a normal exception.\n\n=begin code\n{ return; CATCH { default { $*ERR.say: .^name, ': ', .Str } } }\n# OUTPUT: «X::ControlFlow::Return: Attempt to return outside of any Routine␤»\n# was CX::Return\n=end code\n\n=end pod\n"
  },
  {
    "path": "doc/Language/experimental.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"advanced\")\n\n=TITLE Experimental features\n\n=SUBTITLE Preview of upcoming new language features available for user evaluation\n\nDuring Raku development, new features are often made available for\nusers as experimental before their design is completed. Eventually\nthese features may be made part of the Raku specification. To use these\nfeatures, one uses the C<experimental> pragma in program source code, for\nexample, like this:\n\n    use experimental :macros;\n\nThese are the features that, for the time being, are experimental.\n\n=head2 X<B<pack>|Language,pack>\n\nPack is a feature that allows binary serialization of general data structures,\nand is inherited from\nL<Perl's pack|http://perldoc.perl.org/functions/pack.html>.\nThe C<pack> order creates a L<C<Buf>|/type/Buf> by packing data structures in a certain\nway given by a I<packing string> with the options shown\nL<in the description of C<unpack>|/type/Blob#routine_unpack>. You turn it on by\ninserting this pragma at the beginning of your program:\n\n    use experimental :pack;\n\nFor instance, we can pack numbers interpreting them as hexadecimal (C<H>) with\nthe pattern repeating until there are no more elements (C<*>):\n\n=for code\nuse experimental :pack;\nsay pack(\"H*\", \"414243\").contents;#  OUTPUT: «(65 66 67)␤»\n\nThere is a corresponding C<unpack> routine that does exactly the opposite.\n\n=for code\nuse experimental :pack;\nmy $buf=Buf.new(65,66,67);\nsay $buf.unpack(\"H*\"); # OUTPUT: «414243␤»\n\n\nNot all of the symbols above are guaranteed to be implemented, and the roadmap\ndoes not include a fixed date for getting out of that stage.\n\nPlease see also documentation for L<C<pack>|/type/Blob#sub_pack> and\nL<C<unpack>|/type/Blob#routine_unpack> in the L<C<Blob>|/type/Blob> page.\n\n=head2 X<B<macros>|Language,macros>\n\nL<Macros|https://en.wikipedia.org/wiki/Macro_(computer_science)> are\ncode-generating routines, that generate code in compile time, before the program\nis executed. In Raku its use is still experimental and it needs to be turned\non via the pragma\n\n    use experimental :macros;\n\nMacro processing happens during parsing time. A macro generates an abstract\nsyntax tree, which is grafted into the program syntax tree. C<quasi> is the\nroutine that performs this task.\n\n=begin code\nuse experimental :macros;\nmacro does-nothing() {\n    quasi {}\n};\ndoes-nothing; # OUTPUT: «»\n=end code\n\nX<|Language,quasi (macros)>\nMacros are a kind of routine, so they can take arguments in exactly the same\nway, and act also in almost the same way.\n\n=begin code\nuse experimental :macros;\nmacro is-mighty( $who ) {\n    quasi { \"$who is mighty!\"}\n};\nsay is-mighty \"Freija\"; # OUTPUT: « \"Freija\" is mighty!␤»\n=end code\n\nX<|Language,unquoting (macros)>\nX<|Language,{{{}}} (macros)>\n\"Almost\" accounts for the fact that the argument is inserted as a literal,\nincluding the quotes. Please note that we can also eliminate the parentheses for\na macro call, following the same rules as a routine. You can use the unquoting\nconstruct C<{{{}}}> to get rid of this kind of thing:\n\n=begin code\nuse experimental :macros;\nmacro is-mighty( $who ) {\n    quasi { {{{$who}}} ~ \" is mighty!\"}\n};\nsay is-mighty \"Freija\";  # OUTPUT: «Freija is mighty!␤»\n=end code\n\nSince macro expansion happens at parse time, care must be taken when using\nexternal variables in them:\n\n=begin code\nuse experimental :macros;\nmy $called;\nmacro called() {\n    $called++;\n    quasi { \"Called\" }\n};\nsay called() ~ \" $called times\";\nsay called() ~ \" $called times\"; # OUTPUT: «Called 2 times␤Called 2 times␤»\n=end code\n\nSince macros are expanded at parse time, C<$called> will be the result when runtime\nstarts, which is already C<2>, as printed. Initializing C<$called> with 0,\nhowever, will make this print C<Called 0 times> since that initialization is run\nI<after> the parse phase, when the macros are expanded.\n\nMacros are terribly useful when complicated, computed initializations need to be\ndone. However, they are still in the I<experimental> nursery for a good reason.\nAlthough the features shown above are not very likely to change, anything, even\ntheir very presence, might change at any one time depending in necessities, so\nit would be best to keep them away from production code. Meanwhile, taking a\nlook at\nL<this article by Masak|https://perl6advent.wordpress.com/2012/12/23/day-23-macros/>\nas well as\nL<C<007>|https://github.com/masak/007>, a new macro language, might provide\na glimpse into the things to come.\n\n=head2 X<B<cached>|Language,:cached>\n\nThe following pragma:\n\n    use experimental :cached;\n\nturns on the C<is cached> trait, which stores the result of a routine call,\nreturning the same value if called with the same arguments.\n\nIt can be used when heavy calculations are involved, as in this sample that uses\nL<amicable numbers|https://perl6advent.wordpress.com/2018/12/25/calling-numbers-names/#more-7528>,\ntaken from the 2018 Advent Calendar:\n\n=begin code\nuse experimental :cached;\n\nsub aliquot-parts( $number ) is cached {\n    (^$number).grep: $number %% *;\n}\n\nsub infix:<amic>( $m, $n ) {\n    $m == aliquot-parts($n).sum &&\n    $n == aliquot-parts($m).sum;\n}\n\n# Taken from https://en.wikipedia.org/wiki/Amicable_numbers\nmy @numbers = [2620, 2924, 5020, 5564, 6232, 6368, 66928, 66992];\n\nsay \"Aliquot parts of $_ are \", aliquot-parts $_ for @numbers;\n\nfor @numbers X @numbers -> @pair {\n    say \"@pair[0] and @pair[1] are \",\n        @pair[0] amic @pair[1]??\" \"!!\"not \", \"amicable\";\n}\n=end code\n\nThis code caches the computation of the I<aliquot parts>, so that when the\nC<amic> operator is called, it's only computed once; as a matter of fact, the\nfirst loop which prints these aliquot parts will be the only one that actually\nperform the computation.\n\nSee also\nL<the description of the trait|/routine/is%20cached> for additional information and examples.\n\nB<Note>: This feature is not thread-safe.\n\n=head2 X<B<rakuast>|Language,:rakuast>\n\nThe pragma:\n\n    use experimental :rakuast;\n\nmakes the L<C<RakuAST>|/type/RakuAST> package and its classes available for\nuse in language versions B<before> C<6.e>.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/faq.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"reference\")\n\n=TITLE FAQ\n\n=SUBTITLE Frequently asked questions about Raku\n\n=head1 General\n\nX<|Reference,Raku and Perl 6 (FAQ)>\n=head2 What's the difference between Raku, Rakudo and Perl 6?\n\nProperly speaking, L<Rakudo|https://rakudo.org/> is an implementation of Raku.\nIt's currently the one that's being developed, but there have been other\nimplementations in the past and there will likely be others in the future.\nRaku is the definition of the language. When talking about the current\ninterpreter, Rakudo and Raku can be used interchangeably.  \"Perl 6\" is the\nname that was used for \"Raku\" before October 2019.\n\n=head2 When was Raku released?\n\nThe Rakudo 2015.12 implementation version was released on December 25th 2015,\nwhich implemented the v6.c Raku specification, released at the same time.\n\n=head2 Is there a Raku version 6.0.0?\n\nNo. The first stable language specification version is v6.c\n(\"Christmas\"). Future versions of the spec may have point releases (e.g.,\nv6.d.2) or major releases (e.g., v6.e).\n\nRunning C<raku -v> will display the language version your compiler\nimplements, e.g.:\n\n=for code :lang<shell>\n$ raku -v\nWelcome to Rakudo™ v2022.04.\nImplementing the Raku® Programming Language v6.d.\nBuilt on MoarVM version 2022.04.\n\nX<|Reference,v6.d (FAQ)>\n=head2 When was v6.d released?\n\nThe v6.d Specification was released on\nL<Diwali 2018|https://en.wikipedia.org/wiki/Diwali>,\nwhich was November 6–7 2018, in a\nconvenient timezone. 6.d was enabled by default in the Rakudo compiler\nrelease of 2018.11.\n\nThe vast majority of 6.d features were already implemented and available\nin the Rakudo compiler without requiring any special pragmas, as they\ndid not conflict with the 6.c specification. A smaller set of features\nand behaviors is available automatically if you have the C<use\nv6.d> pragma at the top of the file. The rest of about 3100 new\ncommits to the language specification simply clarify previously\nundefined behavior.\n\nX<|Reference,Rakudo Star DMG binary installer (FAQ)>\nX<|Reference,Rakudo Star MSI binary installer (FAQ)>\nX<|Reference,Rakudo Star docker image (FAQ)>\nX<|Reference,Rakudo Star for Linux (FAQ)>\nX<|Reference,Rakudo Star for Windows (FAQ)>\nX<|Reference,Rakudo Star for Mac (FAQ)>\n=head2 As a Raku user, what should I install?\n\nMac users can use the latest Rakudo Star DMG binary installer at\nL<https://rakudo.org/downloads/star>\n\nWindows users can use the Rakudo Star MSI binary installer. You will\nneed Windows Git and Strawberry Perl to use zef to install library\nmodules.\n\nLinux users probably want to download Rakudo Star and follow the\ncompilation instructions at L<https://www.rakudo.org/downloads/>.\n\nThere should be Linux and Mac binaries available from vendors and third\nparties, although vendor versions may be outdated. Versions before\nRakudo release of 2015.12 should be avoided.\n\nThere's an official Rakudo Star docker image at\nL<https://hub.docker.com/_/rakudo-star/>\n\nX<|Reference,rakubrew (FAQ)>\nX<|Reference,rakudobrew (FAQ)>\n=head2 As an advanced user I want to track Rakudo development.\n\nAn option is to clone L<the repository|https://github.com/rakudo/rakudo> and\nbuild it. This will install work in progress which is minimally-tested and\nmay contain severe bugs. If you're interested in contributing to the Rakudo\nRaku compiler, you may find the\nL<Z-Script helper tool|https://github.com/zoffixznet/z> useful.\n\nTo install the last official monthly release, check out the tag visible\nat L<https://raw.githubusercontent.com/rakudo/rakudo/master/VERSION> or\nset up L<a helper command|https://github.com/zoffixznet/r#table-of-contents>.\n\nSome users choose to use L<rakubrew|https://rakubrew.org/>, which allows\nquick installation of multiple versions of Rakudo in parallel.\n\nIn either case you will probably need to also install\nL«C<zef>|https://github.com/ugexe/zef» and\nL«C<rakudoc>|https://raku.land/zef:coke/rakudoc» from the\nL<ecosystem|https://raku.land/>.\n\n=head2 Where can I find good documentation on Raku?\n\nSee L<the official documentation website|/index>\n(especially its L<\"Introduction\" section|/introduction>).\n\nL<perl6book.com|https://perl6book.com/> contains a list of dead tree and\nelectronic books.\n\nBe mindful of publication dates when reading third-party articles.\nAnything published before December, 2015 likely describes a pre-release\nversion of Raku.\n\nYou can always\nL<get help from a live human in our help chat|https://web.libera.chat/?channel=#raku>\nor L<search the chat logs|https://irclogs.raku.org/>\nto find previous conversations and discussions.\n\nX<|Reference,Books>\n=head2 Can I get some books about Raku?\n\nHere are some available books, in alphabetical order:\n\n=item L<Learning to program with Raku: First Steps|https://www.amazon.com/gp/product/B07221XCVL>, by JJ Merelo\n\n=item L<Metagenomics|https://kyclark.gitbooks.io/metagenomics/content/>,\nby Ken Youens-Clark\n\n=item L<Parsing with Perl 6 Regexes and Grammars|https://smile.amazon.com/dp/1484232275/>, by Moritz Lenz\n\n=item L<Perl 6 at a Glance|https://deeptext.media/perl6-at-a-glance/>,\nby Andrew Shitov\n\n=item L<Raku Fundamentals|https://www.apress.com/gp/book/9781484261088>,\nby Moritz Lenz\n\n=item L<Perl 6 Deep Dive|https://www.packtpub.com/en-us/product/perl-6-deep-dive-9781787123458>, by Andrew Shitov\n\n=item L<Think Perl 6: How to Think Like a Computer Scientist|https://greenteapress.com/wp/think-perl-6/>, by Laurent Rosenfeld.\n\nA list of books published or in progress is maintained in\nL<C<raku.org>|https://raku.org>.\n\nX<|Reference,Specification (FAQ)>\n=head2 What is the Raku specification?\n\nThe specification refers to the official test suite for Raku. It's called\nL<C<roast>|https://github.com/Raku/roast> and is hosted on github. Any\ncompiler that passes the tests is deemed to implement that version of the\nRaku specification.\n\nRoast's C<master> branch corresponds to the latest development that isn't\nnecessarily part of any specification yet. Other branches\ncorrespond to specific versions; for example, \"6.c-errata\".\n\nSo C<6.c-errata> is a released language version we don't change other than to\nfix errors in tests (the \"errata\") whereas master is the unreleased\nwork-in-progress that may become the next language version. Its current state\nis not necessarily prescriptive of the next language version's behavior since\nnew additions will be reviewed for inclusion into the release.\n\n=head2 Is there a glossary of Raku related terms?\n\nYes, see L<glossary|/language/glossary>.\n\n=head2 I'm a Perl programmer. Where is a list of differences between Perl\nand Raku?\n\nThere are several I<Perl to Raku> guides in the\nL<Introduction section of the documentation|/introduction>, most notable of which\nis the L<Overview|/language/perl-nutshell>.\n\nX<|Reference,Ruby Quickstart (FAQ)>\n=head2 I'm a Ruby programmer looking for quickstart type docs?\n\nSee the L<rb-nutshell|/language/rb-nutshell> guide.\n\n=head1 Modules\n\nX<|Reference,CPAN (FAQ)>X<|Reference,ecosystem>\n=head2 Is there a repository of third party library modules for Raku?\n\nYes. As a user, the\nL«C<zef> module installer|https://github.com/ugexe/zef» will\nautomatically install the version of a module with the highest\nversion number.  If you want a specific version and/or a version\nfrom a specific author, you can also specify that with C<zef>.\n\nAs a new module author, you can use the\nL<C<fez> module uploader|https://raku.land/zef:tony-o/fez>\nto upload your module to the Raku ecosystem.  There are also a\nnumber of helper modules that help you set up a skeleton of a\ndistribution, such as L<C<App::Mi6>|https://raku.land/zef:skaji/App::Mi6>,\nwhich will also help you with uploading once your module is\nready for distribution.\n\nHistorically, you could also upload a Raku module to CPAN by using\nL<PAUSE|https://pause.perl.org/> to upload a module.  And before\nthat, there was a way of using Github/Gitlab to make your module\navailable for download.  These are now considered to not be the\nbest way for new module authors to start with.\n\nX<|Reference,rakudoc (FAQ)> X<|Other languages,perldoc (FAQ)>\n=head2 Is there a perldoc (command line documentation viewer) for Raku?\n\nYes, it's called L«C<rakudoc>|https://raku.land/zef:coke/rakudoc»\nand is present in the ecosystem under that name. It\ncomes bundled in with Rakudo Star but needs to be manually installed with C<zef>\nif you are using a Rakudo monthly release.\n\nX<|Reference,Perl modules (FAQ)>\n=head2 Can I use Perl modules from Raku?\n\nYes, with L<Inline::Perl5|https://github.com/niner/Inline-Perl5/>, which works\nwell with most Perl modules. It can even run Perl Catalyst and DBI.\n\nX<|Reference,C and C++ (FAQ)>\n=head2 Can I use C and C++ from Raku?\n\nL<Nativecall|/language/nativecall> makes this\nparticularly easy.\n\n=head2 Nativecall can't find C<libfoo.so> and I only have C<libfoo.so.1.2>!\n\nIn most Linux systems, shared libraries will be installed in such a way that,\n for a specific C<libfoo>, there will be a C<libfoo.so.x.y.z> real file, and\n then a set of symlinks C<libfoo.so> and C<libfoo.so.x>. for instance, C<ls\n /usr/local/lib/libxxhash.so*> returns:\n\n=for code :lang<text>\n/usr/local/lib/libxxhash.so -> libxxhash.so.0.6.5\n/usr/local/lib/libxxhash.so.0 -> libxxhash.so.0.6.5\n/usr/local/lib/libxxhash.so.0.6.5\n\nIn general, installing a C<libfoo-dev> or C<libfoo-devel> (depending on the\ndistro) in Linux will install the shared library I<and> set up those symlinks\n for you. But in some cases, you will only have, as in the question,\nC<libfoo.so.1.2>.\n\nIn that case, just use the version of C<is native> that explicitly sets the\n ABI/API version, as indicated in\nL<the manual|/language/nativecall#ABI/API_version>:\n\n=for code :skip-test<snippet>\nsub call-foo() is native('foo',v1.2);\n\n\n=head2 Where have all the traditional UNIX library functions gone?\n\nIt's fairly easy to use L<NativeCall|/language/nativecall> to access them.\n\nAn ecosystem module L<POSIX|https://github.com/cspencer/perl6-posix> is\nalso available.\n\nX<|Reference,Core standard library (FAQ)>\nX<|Reference,Rakudo Star distribution and compiler-only release (FAQ)>\n=head2 Does Rakudo have a core standard library?\n\nL<Rakudo Star distribution|https://rakudo.org/downloads/> does come\nwith L<many useful modules|https://github.com/rakudo/star/blob/master/etc/modules.txt>.\n\nRakudo compiler-only release includes\nL<only a couple of the most basic modules|/language/distributions/tools>.\n\nMany more modules can be found in the L<ecosystem|https://raku.land/>.\n\n=head2 Is there something like C<B::Deparse>/How can I get hold of the AST?\n\nUse C<--target=optimize> command line option to view the AST of your program,\ne.g., C<raku --target=optimize -e 'say \"hi\"'>\n\nThe target C<optimize> gives the AST after the static optimizer does its job,\nwhile target C<ast> gives the AST before that step. To get the full list of\navailable targets, run C<raku --stagestats -e \"\">\n\nX<|Reference,Precompile (FAQ)>\n=head2 What is precompilation?\n\nWhen you load a module for the first time, Rakudo compiles it into bytecode.\nThen, Rakudo both stores the compiled bytecode on disk and uses it, because\nthat tends to be significantly faster.\n\nX<|Reference,Circular dependencies (FAQ)>\n=head2 Can I have circular dependencies between modules?\n\nNo, you can't have circular dependencies, and you should\nget a C<Circular module loading detected> error if you have them between your\nmodules.\n\nVery likely you can accomplish what you are trying to do using\nL<roles|/language/objects#Roles>. Instead of C<A.rakumod> depending on\nC<B.rakumod> and C<B.rakumod> depending on C<A.rakumod>, you can have C<A-Role.rakumod>\nand C<B-Role.rakumod> and classes in C<A.rakumod> and C<B.rakumod> implementing these\nroles respectively. Then you can depend on C<A-Role.rakumod> and\nC<B-Role.rakumod> without the need for the circular dependency.\n\nOne of the reasons why circular dependencies do not work in Raku is\none pass parsing. We have to know what A means when we parse B, and we\nhave to know what B means when we parse A, which is clearly an\ninfinite loop.\n\nNote that Raku has no “1 file = 1 class” limitation, and circular\ndependencies within a single compilation unit (e.g., file) are possible\nthrough stubbing. Therefore another possible solution is to move\nclasses into the same compilation unit.\n\n\n=head1 Common operations\n\n=head2 String: How can I parse and get a L<number|/language/numerics> from a L<string|/type/Str>?\n\nUse the L<+ prefix|/language/operators#prefix_+>:\n\n=begin code :ok-test<dd>\nsay \"42.123456789123456789\";  # OUTPUT: «42.123456789123456789␤»\nsay +\"42.4e-2\";               # OUTPUT: «0.424␤»\n=end code\n\nThis example of L<contextualization|/language/contexts> can numify any string you could enter as a L<literal number|/language/syntax#Number_literals>.\nL<val|/routine/val> routine converts it to L<allomorph|/language/glossary#Allomorph>.\nL<unival|/routine/unival> routine converts one unicode codepoint.\n\n=head2 String: How can I check if a string contains a substring and if so, how can I get indices of matches?\n\nUse L<.contains|/type/Str#method_contains> or L<.indices|/type/Str#method_indices>:\n\n=begin code\n\"az and az and az again\".contains(\"az\"); # OUTPUT: «True␤»\n\"az and az and az again\".indices(\"az\");  # OUTPUT: «(0 7 14)␤»\n=end code\n\n=head2 String: How can I get the hexadecimal representation of a string?\n\nTo get a hexadecimal list of each byte of a string (i.e. hex encoder),\nfirst convert the string to a L<C<Blob>|/type/Blob> with L<.encode|/routine/encode>.\n\n=begin code\nsay \"I ❤ 🦋\".encode>>.base(16);  # OUTPUT: «(49 20 E2 9D A4 20 F0 9F A6 8B)␤»\n=end code\n\nNote that L<.gist|/routine/gist> or L<.raku|/routine/raku> methods can be useful for variable introspection:\n\n=begin code\nsay \"I ❤ 🦋\".encode.raku;  # OUTPUT: «utf8.new(73,32,226,157,164,32,240,159,166,139)␤»\nsay \"I ❤ 🦋\".encode.gist;  # OUTPUT: «utf8:0x<49 20 E2 9D A4 20 F0 9F A6 8B>␤»\n=end code\n\n=head2 String: How can I remove from a string some characters by index?\n\nUse L<.comb|/routine/comb> to transform it to a L<C<Seq>|/type/Seq>, then the L<(-) infix|/language/operators#infix_(-),_infix_%E2%88%96> to remove the unwanted indices:\n\n=begin code\nsay '0123456789'.comb[(^* (-) (1..3, 8).flat).keys.sort].join;  # OUTPUT: «045679␤»\n=end code\n\nIf the string is large, L<.comb|/routine/comb> can take time. In which case, L<.substr-rw|/routine/substr-rw> is faster:\n\n=begin code\nmulti postcircumfix:<[- ]> (Str:D $str is copy, +@indices) {\n    for @indices.reverse {\n        when Int   { $str.substr-rw($_,1) = '' }\n        when Range { $str.substr-rw($_  ) = '' }\n    }\n    return $str;\n}\n\nsay '0123456789'[- 1..3, 8 ];  # OUTPUT: «045679␤»\n=end code\n\n=head2 String: How can I split a string in equal parts?\n\nL<.comb|/routine/comb> is accepting an optional L<C<Int>|/type/Int>:\n\n=begin code\n.say for 'abcdefghijklmnopqrstuvwxyz'.comb: 8;  # OUTPUT: «abcdefgh␤ijklmnop␤qrstuvwx␤yz»\n=end code\n\n=head1 Language features\n\nX<|Reference,Data::Dumper (FAQ)>\n=head2 How can I dump Raku data structures\n(like Perl Data::Dumper and similar)?\n\nTypical options are to use the L<say|/routine/say> routine that uses\nthe L<gist|/routine/gist> method which gives the \"gist\" of the object being\ndumped. More detailed output can be obtained by calling the\nL<perl|/routine/perl> method (soon to be deprecated in favor of C<$obj.raku>,\navailable since the Rakudo 2019.11 release) that typically returns an object's\nrepresentation in L<EVAL|/routine/EVAL>-able code.\n\nIf you're using the L<rakudo|https://rakudo.org> implementation, you can use\nthe L«rakudo-specific C<dd> routine|/programs/01-debugging#Dumper_function_(dd)»\nfor dumping, whose output is similar to L<raku|/routine/raku>, but\nwith more information.\n\nExamples:\n\n=begin code :ok-test<dd>\nmy $foo = %( foo => 'bar' );\nsay $foo.raku;   # OUTPUT: «${:foo(\"bar\")}␤»\nsay $foo;        # OUTPUT: «{foo => bar}␤»\n\n# non-standard routine available in rakudo implementation:\ndd $foo;         # OUTPUT: «Hash $foo = ${:foo(\"bar\")}␤»\n=end code\n\nThere are also L<several ecosystem modules|https://raku.land/?q=dump>\nthat provide more control over how data structures are dumped, including\nsupport for colored output.\n\n=head2 Why is the Rakudo compiler so apologetic?\n\nIf SORRY! is present in the output, the error is a compile time error.\nOtherwise, it's a runtime error.\n\nExample:\n\n=begin code\nsub foo( Int $a, Int $b ) {...}\nfoo(1)     # ===SORRY!=== Error while compiling ...\n=end code\n\n=for code\nsay 1/0;   # Attempt to divide 1 by zero using div\n\n=head2 What is C<(Any)>?\n\nL«C<Any>|/type/Any» is a top level class most objects inherit from.\nThe L<C<Any>|/type/Any> type object is\nL<the default value|/type/Attribute#Trait_is_default> on variables and\nparameters without an explicit type constraint, which means you'll\nlikely see C<(Any)> printed when you output a L<gist|/routine/gist> of\na variable without any value by using, for instance, the\nL«C<say> routine|/routine/say»:\n\n=begin code\nmy $foo;\nsay $foo; # OUTPUT: «(Any)␤»\n\nmy Int $baz;\nsay $baz; # OUTPUT: «(Int)␤»\n\nmy $bar = 70;\nsay $bar; # OUTPUT: «70␤»\n=end code\n\nTo test whether a variable has any defined values, see\nL<DEFINITE|/language/classtut#index-entry-type_object-DEFINITE-A_word_on_types> and L<defined|/routine/defined>\nroutines. Several other constructs exist that test for definiteness, such as\nL«C<with>, C<orwith>, and C<without>|/syntax/with orwith without»\nstatements, L«C<//>|/routine/$SOLIDUS$SOLIDUS», L<andthen|/routine/andthen>,\nL<notandthen|/routine/notandthen>, and\nL<orelse|/routine/orelse> operators, as well as\nL<type constraint smileys|/language/signatures#Constraining_argument_definiteness>.\n\n=head2 What is C<so>?\n\nC<so> is a loose precedence operator that coerces to L<C<Bool>|/type/Bool>.\n\nIt has the same semantics as the C<?> prefix operator, just like\nC<and> is the low-precedence version of C<&&>.\n\nExample:\n\n=for code\nsay so 1|2 == 2;    # OUTPUT: «True␤»\n\nIn this example, the result of the comparison (which is a\nL<C<Junction>|/type/Junction>), is converted to Bool before being printed.\n\n=head2 What are those C<:D> and C<:U> things in signatures?\n\nIn Raku, classes and other types are objects and pass type checks\nof their own type.\n\nFor example, if you declare a variable\n\n=for code\nmy Int $x = 42;\n\nthen not only can you assign integers (that is, instances of class Int) to it,\nbut the L<C<Int>|/type/Int> type object itself:\n\n=begin code :preamble<my Int $x>\n$x = Int\n=end code\n\nIf you want to exclude type objects, you can append the C<:D> type smiley,\nwhich stands for \"definite\":\n\n=begin code\nmy Int:D $x = 42;\n$x = Int;\n\n# dies with:\n# Type check failed in assignment to $x;\n# expected Int:D but got Int\n=end code\n\nLikewise, C<:U> constrains to undefined values, that is, type objects.\n\nTo explicitly allow either type objects or instances, you can use C<:_>.\n\n=head2 What is the C«-->» thing in the signature?\n\nL«-->|/language/signatures#Constraining_return_types» is a return constraint, either\na type or a definite value.\n\nExample of a type constraint:\n\n=begin code\nsub divide-to-int( Int $a, Int $b --> Int ) {\n        return ($a / $b).narrow;\n}\n\ndivide-to-int(3, 2)\n# Type check failed for return value; expected Int but got Rat\n=end code\n\nExample of a definite return value:\n\n=begin code\nsub discard-random-number( --> 42 ) { rand }\nsay discard-random-number;\n# OUTPUT: «42␤»\n=end code\n\nIn this case, the final value is thrown away because the return value is\nalready specified in the signature.\n\nX<|Reference,Junction (FAQ)>\n=head2 How can I extract the values from a Junction?\n\nIf you want to extract the values from a\nL<C<Junction>|/type/Junction>, you are probably doing something wrong and\nshould be using a L<C<Set>|/type/Set> instead.\n\nJunctions are meant as matchers, not for doing algebra with them.\n\nIf you want to do it anyway, you can abuse autothreading for that:\n\n=begin code\nsub junction-values(Mu $j) {\n    my @values;\n    -> Any $s { @values.push: $s }.($j);\n    @values;\n}\n\nsay junction-values(1|2|3).join(', ');\n# prints 1, 2, 3 or a permutation thereof\n=end code\n\n=head2 If Str is immutable, how does C<s///> work? If Int is immutable,\nhow does C<$i++> work?\n\nIn Raku, values of many basic types are immutable, but the variables holding\nthem are not. The C<s///> operator works on a variable, into which it puts a\nnewly created string object. Likewise, C<$i++> works on the C<$i> variable, not\njust on the value in it.\n\nKnowing this, you would not try to change a literal string (e.g. like\nC<'hello' ~~ s/h/H/;>), but you might accidentally do something equivalent\nusing C<map> as follows.\n\n=begin code\nmy @foo = <hello world>.map: { s/h/H/ };\n\n# dies with\n# Cannot modify an immutable Str (hello)\n\nmy @bar = <hello world>».subst-mutate: 'h', 'H';\n\n# dies with\n# Cannot resolve caller subst-mutate(Str: Str, Str);\n# the following candidates match the type but require\n# mutable arguments: ...\n=end code\n\nInstead of modifying the original value in place, use a routine or operator\nthat returns a new value:\n\n=begin code\nmy @foo = <hello world>.map: { S/h/H/ };  # ['Hello','world']\nmy @bar = <hello world>».subst: 'h', 'H'; # ['Hello','world']\n=end code\n\nSee the documentation on L<containers|/language/containers> for more\ninformation.\n\n=head2 What's up with array references and automatic dereferencing?\nDo I need the C<@> sigil?\n\nIn Raku, nearly everything is a reference, so talking about taking\nreferences doesn't make much sense. Scalar variables can also contain\narrays directly:\n\n=begin code\nmy @a = 1, 2, 3;\nsay @a;                 # OUTPUT: «[1 2 3]␤»\nsay @a.^name;           # OUTPUT: «Array␤»\n\nmy $scalar = @a;\nsay $scalar;            # OUTPUT: «[1 2 3]␤»\nsay $scalar.^name;      # OUTPUT: «Array␤»\n=end code\n\nThe big difference is that arrays inside a scalar act as one value in list\ncontext, whereas arrays will be happily iterated over.\n\n=begin code\nmy @a = 1, 2, 3;\nmy $s = @a;\n\nfor @a { ... }          # loop body executed 3 times\nfor $s { ... }          # loop body executed only once\n\nmy @flat = flat @a, @a;\nsay @flat.elems;            # OUTPUT: «6␤»\n\nmy @nested = flat $s, $s;\nsay @nested.elems;          # OUTPUT: «2␤»\n=end code\n\nYou can force list context with C<@( ... )> or by calling the\nC<.list> method on an expression, and item context with\nC<$( ... )> or by calling the C<.item> method on an expression.\n\nSee the L«I<Perl 6: Sigils, Variables, and Containers>|https://perl6advent.wordpress.com/2017/12/02/» article to learn more.\n\nX<|Reference,Sigils (FAQ)>\n=head2 Why sigils? Couldn't you do without them?\n\nThere are several reasons:\n\n=item they make it easy to interpolate variables into strings\n\n=item they form micro-namespaces for different variables and twigils, thus\navoiding name clashes\n\n=item they allow easy single/plural distinction\n\n=item they work like natural languages that use mandatory noun markers, so\nour brains are built to handle it\n\n=item they aren't mandatory, since you can declare sigilless names\n(if you don't mind the ambiguity)\n\n=head2 \"Type Str does not support associative indexing.\"\n\nYou likely tried to mix string interpolation and key characters, like HTML tags:\n\n=begin code\nmy $foo = \"abc\";\nsay \"$foo<html-tag>\";\n=end code\n\nRaku thinks C<$foo> is a Hash and C«<html-tag>» is a string literal\nhash key. Use a closure to help it to understand you.\n\n=begin code\nmy $foo = \"abc\";\nsay \"{$foo}<html-tag>\";\n=end code\n\nX<|Reference,Coroutine (FAQ)>\n=head2 Does Raku have coroutines? What about C<yield>?\n\nRaku has no C<yield> statement like Python does, but it does offer similar\nfunctionality through lazy lists. There are two popular ways to write\nroutines that return lazy lists:\n\n=begin code :preamble<sub have_data {};sub some_data {};>\n# first method, gather/take\nmy @values = gather while have_data() {\n    # do some computations\n    take some_data();\n    # do more computations\n}\n\n# second method, use .map or similar method\n# on a lazy list\nmy @squares = (1..*).map(-> \\x { x² });\n=end code\n\n=head2 Why can't I initialize private attributes from the new method,\nand how can I fix this?\n\nThe C<say> statement in the following code sample\n\n=begin code\nclass A {\n    has $!x;\n    method show-x {\n        return $!x;\n    }\n}\nsay A.new(x => 5).show-x;\n=end code\n\ndoes not print 5. Private attributes are I<private>, which means invisible to\nthe outside world. If the default constructor could initialize them, they would\nleak into the public API. Thus, in this particular code sample the attribute\nC<$!x> isn't initialized during object construction by the default\nconstructor.\n\nIf you still want to initialize private attributes with the default constructor,\nyou can add a C<submethod BUILD> to achieve such task:\n\n=begin code\nclass B {\n    has $!x;\n    submethod BUILD(:$!x) { }\n    method show-x {\n        return $!x;\n    }\n}\nsay B.new(x => 5).show-x;\n=end code\n\nC<BUILD> is called by the default constructor (indirectly, see\nL<Object Construction|/language/objects#Object_construction>\nfor more details) with all the named arguments that the user passes to the\nconstructor. C<:$!x> is a named parameter with name C<x>, and when called\nwith a named argument of name C<x>, its value is bound to the attribute C<$!x>.\n\nHowever, you shouldn't do that. If the attribute is declared as private,\nthen it shouldn't be exposed to the environment outside the class (e.g.,\nduring object construction). On the other hand, if the attribute is public,\nthere is no downside to declaring it that way with C<$.x> since the external\nview is read-only by default, and you can still access it internally with C<$!x>.\n\n=head2 How and why do C<say>, C<put> and C<print> differ?\n\nThe most obvious difference is that C<say> and C<put> append\na newline at the end of the output, and C<print> does not.\n\nBut there's another difference: C<print> and C<put> convert their\narguments to a string by calling the L<C<Str>|/routine/Str> method on each item\npassed to them while C<say> uses the C<gist> method. The C<gist> method,\nwhich you can also create for your own classes, is intended to create a\nL<C<Str>|/type/Str> for human interpretation. So it is free to leave out information\nabout the object deemed unimportant to understanding the essence of the object.\n\nOr phrased differently, C<$obj.Str> gives a string representation,\nC<$obj.gist> provides a short summary of that object suitable for\nfast recognition by a human, and C<$obj.raku> gives a Raku-ish\nrepresentation from which the object could be re-created.\n\nFor example, when the L<C<Str>|/routine/Str> method is invoked on a type object, also known\nas an \"undefined value\", the type is stringified to an empty string\nand a C<warn>ing is thrown. On the other hand, the C<gist> method returns the\nname of the type between parentheses (to indicate there's nothing in that\nvalue except the type).\n\n=begin code\nmy Date $x;     # $x now contains the Date type object\nprint $x;       # empty string plus warning\nsay $x;         # OUTPUT: «(Date)␤»\n=end code\n\nIf you'd like to show a debugging version of an object, it is probably better\nto use the L«rakudo-specific C<dd> routine|/programs/01-debugging#Dumper_function_(dd)».\nIt essentially does C<$obj.raku> and shows that on STDERR rather than\nSTDOUT, so it won't interfere with any \"normal\" output of your program.\n\nIn short, C<say> is optimized for casual human interpretation, C<dd> is optimized\nfor casual debugging output and C<print> and C<put> are more generally suitable\nfor producing output.\n\nC<put> is thus a hybrid of C<print> and C<say>; like C<print>, it calls the\nL<C<Str>|/routine/Str> method on the object. And like C<say>, it adds a newline at the end\nof the output.\n\n=head2 What's the difference between C<token> and C<rule> ?\n\nC<regex>, C<token> and C<rule> introduce regexes, but with\nslightly different semantics.\n\nC<token> implies the C<:ratchet> or C<:r> modifier, which prevents the\nrule from backtracking.\n\nC<rule> implies both the C<:ratchet> and C<:sigspace> (short C<:s>)\nmodifier, which means a rule doesn't backtrace, and it treats\nwhitespace in the text of the regex as C«<.ws>» calls (i.e.,\nmatches whitespace, which is optional except between two word\ncharacters). Whitespace at the start of the regex and at the start\nof each branch of an alternation is ignored.\n\nC<regex> declares a plain regex without any implied modifiers.\n\n=head2 What's the difference between C<die> and C<fail>?\n\nC<die> throws an exception.\n\nC<fail> returns a L<C<Failure>|/type/Failure> object. (If the caller has declared C<use fatal;>\nin the calling lexical scope, C<fail> throws an exception instead of\nreturning it.)\n\nA L<C<Failure>|/type/Failure> is an \"unthrown\" or \"lazy\" exception. It's an object that contains\nthe exception, and throws the exception if you try to use the L<C<Failure>|/type/Failure>\nas an ordinary object or ignore it in sink context.\n\nA L<C<Failure>|/type/Failure> returns C<False> from a C<defined> check, and you can extract\nthe exception with the C<exception> method.\n\n=head2 You can have colonpairs in identifiers. What's the justification?\n\nL<Identifiers can include colon pairs, which become part of their name|/language/syntax#Identifiers>.\nAccording to\nL<Larry Wall's answer to the issue|https://github.com/Raku/doc/issues/1753#issuecomment-362875676>,\nI<We\nalready had the colon pair mechanism available, so it was a no-brainer to use\nthat to extend any name that needs to be able to quote uniquefying but\nnon-standard characters (or other information with a unique stringification to\nsuch characters)>.\n\n=head2 How do most people enter unicode characters?\n\nIt depends on the operating system, windowing environment and/or editors. L<This\npage on entering Unicode characters|/language/unicode_entry> specifies how it is\ndone in the most popular operating systems and editors.\n\nX<|Reference,Raku Implementation (FAQ)>\n=head1 Raku implementation\n\n=head2 What Raku implementations are available?\n\nL<Rakudo|https://rakudo.org> is the only compiler under active development.\n\nHistoric implementations include Niecza (.NET) and Pugs (Haskell).\n\n=head2 What language is Rakudo written in?\n\nA short answer is that Rakudo is written almost entirely in Raku. A more\ndetailed answer is that Rakudo is written in a mixture of Raku and NQP (\"Not\nQuite Perl\"). NQP is a lightweight Raku-like environment for virtual\nmachines; it's designed to be a high-level way to create compilers and\nlibraries for virtual machines (such as MoarVM and JVM) using Raku syntax.\n\nX<|Reference,NQP (FAQ)>\n=head2 What language is NQP written in?\n\nNQP is a mixture of (1) NQP code, (2) whatever language the underlying virtual\nmachine is using, (3) some third-party C and Java libraries, and (4) some\nbootstrapping files created by earlier runs of the build process.\n\n=head2 Is Raku Lisp?\n\n=for code\n(not (not Nil))\n\n=head2 Can I compile my script to a standalone executable?\n\nTools like\nL«C<App::InstallerMaker::WiX>|https://raku.land/zef:raku-community-modules/App::InstallerMaker::WiX»\nallow you to create an installer that will package the compiler and your script.\nHowever, the currently available compilers do not support creating a standalone\nexecutable yet.\n\nIf you wish to help out, the I<Rakudo> compiler on I<MoarVM> backend has\nL<https://github.com/MoarVM/MoarVM/issues/875> issue opened as a place to\ndiscuss this problem.\n\nX<|Reference,Raku Distribution (FAQ)>\n=head1 Raku distribution\n\nX<|Reference,Rakudo Star release cycle (FAQ)>\n=head2 When will the next version of Rakudo Star be released?\n\nA Rakudo Star release is typically produced quarterly, with release\nannouncements L<posted on rakudo.org|https://rakudo.org/news>.\n\n=head1 Metaquestions and advocacy\n\n=head2 Why was Raku originally called Perl 6?\n\n… As opposed to some other name that didn't imply all the things\nthat the higher number might indicate on other languages.\n\nThe short answer is that it was Larry's choice under\nL<Rule 1|https://perldoc.perl.org/5.12.4/perlhack.html#DESCRIPTION>.\n\nThe community considers Perl and Raku sister languages - they have\na lot in common, address many of the same problem spaces, but Raku is not\nintended to replace Perl. In fact, both languages interoperate with\neach other.\n\n=head2 When will Raku be ready? Is it ready now?\n\nReadiness of programming languages and their compilers is not a binary\ndecision. As the language and the implementations evolve, they\ngrow steadily more usable. Depending on your needs,\nRaku and its compilers may or may not be ready for you.\n\nThat said, version 6.c (Christmas 2015) is the first official release of Raku\nas a language, along with a validation suite and a compiler that passes it.\n\n=head2 Why should I learn Raku? What's so great about it?\n\nRaku unifies many great ideas that aren't usually found in other programming\nlanguages. While several other languages offer some of these features, none of\nthem offer all of them.\n\n=item Raku offers procedural, object-oriented AND functional programming\nmethodologies.\n\n=item Easy to use consistent syntax, using invariable sigils for data-structures.\n\n=item Full grapheme based Unicode support, including Annex #29.\n\n=item Clean, more readable regular expressions; taken to the next level of\nusability, with a lot more functionality. Named regular expressions improve\nease of use.\n\n=item Junctions allowing easy checking of multiple possibilities;\ne.g., C<$a == 1|3|42> (Is C<$a> equal to 1 or 3 or 42?).\n\n=item Dynamic variables provide a lexically scoped alternative to global\nvariables.\n\n=item Emphasis on composability and lexical scoping to prevent\n“action at a distance”; e.g., imports are always lexically scoped.\n\n=item Easy to understand consistent scoping rules and closures.\n\n=item Powerful object orientation, with classes and roles (everything can be\nseen as an object). Inheritance. Subtyping. Code-reuse.\n\n=item Introspection into objects and metaobjects (turtles all the way down).\n\n=item MetaObject Protocol allowing for metaprogramming without needing to\ngenerate or parse code.\n\n=item Subroutine and method signatures for easy unpacking of positional and\nnamed parameters.\n\n=item Multi-dispatch for identically named subroutines/methods with different\nsignatures, based on arity, types and optional additional code.\n\n=item Compile time error reporting on unknown subroutines or impossible dispatch.\n\n=item Optional gradual type-checking at no additional runtime cost. With\noptional type annotations.\n\n=item Advanced error reporting based on introspection of the compiler/runtime\nstate. This means more useful, more precise error messages.\n\n=item Phasers (like C<BEGIN> / C<END>) allow code to be executed at scope\nentry / exit, loop first / last / next and many more special contexts.\n\n=item High level concurrency model, both for implicit as well as explicit\nmulti-processing, which goes way beyond primitive threads and locks. Raku's\nconcurrency offers a rich set of (composable) tools.\n\n=item Multiple-core computers are getting used more and more, and with Raku\nthese can be used thanks to parallelism, both implicit (e.g., with the C«>>».\nmethod) and explicit ( C<start { code }> ). This is important, because Moore's\nLaw is ending.\n\n=item Structured language support is provided to enable programming for\nasynchronous execution of code.\n\n=item Supplies allow code to be executed when something happens (like a timer,\nor a signal, or a filesystem event).\n\n=item C<react> / C<whenever> / C<supply> keywords allows easy construction of\ninteractive, event driven applications.\n\n=item Lazy evaluation when possible, eager evaluation when wanted or necessary.\nThis means, for example, lazy lists, and even infinite lazy lists, like the\nFibonacci sequence, or all prime numbers.\n\n=item Native data types for faster, closer-to-the-metal, processing.\n\n=item Interfacing to external libraries in C and C++ is fairly easy with\nL<NativeCall|/language/nativecall>.\n\n=item Interfacing with Perl (CPAN) and Python modules is fairly easy with\nL<Inline::Perl5|https://raku.land/cpan:NINE/Inline::Perl5> and\nL<Inline::Python|https://raku.land/cpan:NINE/Inline::Python>\n\n=item Can have multiple versions of a module installed and loaded\nsimultaneously.\n\n=item System administration simplified due to simpler update and upgrade policies.\n\n=item Simple numeric computation without precision loss because of\nL<C<Rat>|/type/Rat>s (rational numbers).\n\n=item Extensible grammars for parsing data or code (which Raku uses to parse\nitself).\n\n=item Raku is a very mutable language (define your own functions, operators,\ntraits and data-types, which modify the parser for you).\n\n=item Large selection of data-types, plus the possibility to create your own\ntypes.\n\n=item Multi-dimensional shaped or native arrays with proper bounds checking.\n\n=item Execute code at any time during parsing of a grammar, or when a certain\nmatch occurred.\n\n=item Adding a custom operator or adding a trait is as simple as writing a\nsubroutine.\n\n=item Automatic generation of hyper-operators on any operator (system or custom\nadded).\n\n=item Runs on a variety of back-ends. Currently MoarVM and JVM, JavaScript in\ndevelopment, more may follow.\n\n=item Runtime optimization of hot code paths during execution (JIT).\n\n=item Runs on small (e.g., Raspberry Pi) and large multi-processor hardware.\n\n=item Garbage collection based: no timely destruction, so no reference-counting\nnecessary. Use phasers for timely actions.\n\n=item Methods can be mixed into any instantiated object at runtime; e.g., to\nallow adding out-of-band data.\n\n=item Easy command-line interface accessible by C<MAIN> subroutine with multiple\ndispatch and automated usage message generation.\n\n=item Fewer lines of code allow for more compact program creation.\nHuffman-coding of names allows for better readability.\n\n=item Lazy lists defined with a simple iterator interface, which any class can\nsupply by minimally supplying a single method.\n\n=item Ability to use hyphens and other non-alphanumeric ASCII\ncharacters as well as certain Unicode characters in identifiers. (Using\nhyphens instead of underscores in test is commonly called \"kebab case\"\namong its users. See also \"camel case\" and \"snake case\":\nL<https://en.wikipedia.org/wiki/Letter_case#Special_case_styles>.)\n\n=item Raku's mottos remain the same as they have been for Perl all along:\n“Perl is different. In a nutshell, Perl is designed to make the easy jobs easy,\nwithout making the hard jobs impossible.” and “There Is More Than One Way To Do\nIt”. Now with even more -Ofun added.\n\n=head2 Is Raku fast enough for me?\n\nThat depends on what you are doing. Rakudo has been developed with the\nphilosophy of \"make it work right then make it work fast.\" It's fast for some\nthings already but needs work for others. Since Raku provides lots of clues\nto the JIT that other dynamic languages don't, we think we'll have a lot of\nheadroom for performance improvements.\n\nThe following crude benchmarks, with all the usual caveats about such things,\nshow that Raku can be faster than Perl for similar tasks if the big weaponry\nis included, that is, if Raku features are used to its full extent; at the\nsame time, Perl can be faster if only the bare bones are included. Similar\nsituations can be observed when comparing Raku to other languages.\n\nTry it on your system. You may be pleasantly surprised!\n\nExamples:\n\n=begin code\n# Raku version\nclass Foo { has $.i is rw };\n\nfor 1..1_000_000 -> $i {\n    my $obj = Foo.new;\n    $obj.i = $i;\n}\n=end code\n\n=begin code :lang<perl>\n# Perl version\npackage Foo;\nuse Moose;\n\nhas i => (is => 'rw');\n\n__PACKAGE__->meta->make_immutable;\n\nfor my $i (1..1_000_000) {\n    my $obj = Foo->new;\n    $obj->i($i);\n}\n\n1;\n\n# Another Perl version that offers bare-bones set of features\n# compared to Moose/Raku's version but those are not needed in this\n# specific, simple program anyway.\npackage Foo;\nuse Mojo::Base -base;\n\nhas 'i';\n\nfor my $i (1..1_000_000) {\n    my $obj = Foo->new;\n    $obj->i($i);\n}\n\n1;\n=end code\n\nYou might want to use this program for comparing performance, too. It works\nunder both languages, as long as C<perl -Mbigint> is used for invocation for\nPerl.\n\n=begin code\nmy ($prev, $current) = (1, 0);\n\nfor (0..100_000) {\n    ($prev, $current) = ($current, $prev + $current);\n}\nprint $current;\n=end code\n\n=end pod\n"
  },
  {
    "path": "doc/Language/filename-extensions.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"beginning\")\n\n=TITLE Filename extensions\n\n=SUBTITLE The extensions recommended for files with Raku content.\n\n=begin table\nFile contents          | Extension | Historic extensions\n========================================================\nRaku script            | .raku     | .pl, .p6\nRaku module            | .rakumod  | .pm, .pm6\nRaku documentation     | .rakudoc  | .pm, pm6, pod, pod6\nTest files in raku     | .rakutest | .t\nNot Quite Perl (NQP)   | .nqp      |\n=end table\n\nNote that in most cases, the historic extensions will still work.\n\n=head1 Introduction\n\nAn extension is the part of the filename after the final '.'; if no '.'\nis present, there is no extension.\n\nFilename extensions can be used to associate behavior with the file content, such as opening\na specialized reader or editor, running a program with the file content as input, etc.\nEven when it is not required by the operating system, filename extensions can provide a useful\nreminder about the contents of the file.\n\n=head1 History\n\nThe Raku language was originally known as Perl 6, and this is reflected in the historic column\nabove. Please use the current extensions whenever possible when generating new code.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/functions.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Functions\n\n=SUBTITLE Functions and functional programming in Raku\n\nRoutines are one of the means Raku has to reuse code. They come in\nseveral forms, most notably L<C<Method>|/type/Method>s, which belong in\nclasses and roles and are associated with an object; and functions (also\ncalled I<subroutines> or L<C<Sub>|/type/Sub>s, for short), which can be\ncalled independently of objects.\n\nSubroutines default to lexical (C<my>) scoping, and calls to them are\ngenerally resolved at compile time.\n\nSubroutines can have a L<C<Signature>|/type/Signature>, also called\nI<parameter list>, which specifies which, if any, arguments the\nsignature expects. It can specify (or leave open) both the number and\ntypes of arguments, and the return value.\n\nIntrospection on subroutines is provided via L<C<Routine>|/type/Routine>.\n\n=head1 Defining/Creating/Using functions\n\n=head2 X<Subroutines|Syntax,sub>\n\nThe basic way to create a subroutine is to use the C<sub> declarator followed by\nan optional L<identifier|/language/syntax#Identifiers>:\n\n    sub my-func { say \"Look ma, no args!\" }\n    my-func;\n\nThe sub declarator returns a value of type L<C<Sub>|/type/Sub> that can be stored\nin any container:\n\n    my &c = sub { say \"Look ma, no name!\" }\n    c;     # OUTPUT: «Look ma, no name!␤»\n\n    my Any:D $f = sub { say 'Still nameless...' }\n    $f();  # OUTPUT: «Still nameless...␤»\n\n    my Code \\a = sub { say ‚raw containers don't implement postcircumfix:<( )>‘ };\n    a.();  # OUTPUT: «raw containers don't implement postcircumfix:<( )>␤»\n\nThe declarator C<sub> will declare a new name in the current scope at compile\ntime. As such, any indirection has to be resolved at compile time:\n\n    constant aname = 'foo';\n    sub ::(aname) { say 'oi‽' };\n    foo;\n\nThis will become more useful once macros are added to Raku.\n\nTo have the subroutine take arguments, a L<C<Signature>|/type/Signature> goes\nbetween the subroutine's name and its body, in parentheses:\n\n=for code\nsub exclaim ($phrase) {\n    say $phrase ~ \"!!!!\"\n}\nexclaim \"Howdy, World\";\n\nBy default, subroutines are L<lexically scoped|/syntax/my>. That is,\nC<sub foo {...}> is the same as C<my sub foo {...}> and is only\ndefined within the current scope.\n\n=begin code\nsub escape($str) {\n    # Puts a slash before non-alphanumeric characters\n    S:g[<-alpha -digit>] = \"\\\\$/\" given $str\n}\n\nsay escape 'foo#bar?'; # OUTPUT: «foo\\#bar\\?␤»\n\n{\n    sub escape($str) {\n        # Writes each non-alphanumeric character in its hexadecimal escape\n        S:g[<-alpha -digit>] = \"\\\\x[{ $/.ord.base(16) }]\" given $str\n    }\n\n    say escape 'foo#bar?' # OUTPUT: «foo\\x[23]bar\\x[3F]␤»\n}\n\n# Back to original escape function\nsay escape 'foo#bar?'; # OUTPUT: «foo\\#bar\\?␤»\n=end code\n\nSubroutines don't have to be named. If unnamed, they're called I<anonymous>\nsubroutines.\n\n    say sub ($a, $b) { $a ** 2 + $b ** 2 }(3, 4) # OUTPUT: «25␤»\n\nBut in this case, it's often desirable to use the more succinct L<C<Block>|/type/Block>\nsyntax. Subroutines and blocks can be called in place, as in the example above.\n\n    say -> $a, $b { $a ** 2 + $b ** 2 }(3, 4)    # OUTPUT: «25␤»\n\nOr even\n\n    say { $^a ** 2 + $^b ** 2 }(3, 4)            # OUTPUT: «25␤»\n\nX<|Language,pointy blocks>\n=head2 X«Blocks and lambdas|Syntax,->»\n\nWhenever you see something like C«{ $_ + 42 }», C«-> $a, $b { $a ** $b }», or\nC«{ $^text.indent($:spaces) }», that's L<C<Block>|/type/Block> syntax; the C«->» is\nconsidered also part of the block. Statements such as C<if>, C<for>, C<while>\nare followed by these kind of blocks.\n\n    for 1, 2, 3, 4 -> $a, $b {\n        say $a ~ $b;\n    }\n    # OUTPUT: «12␤34␤»\n\nThey can also be used on their own as anonymous blocks of code.\n\n    say { $^a ** 2 + $^b ** 2}(3, 4) # OUTPUT: «25␤»\n\nPlease note that this implies that, despite the fact that statements such as\nC<if> do not define a topic variable, they actually can:\n\n=for code\nmy $foo = 33;\nif $foo ** 33 -> $a {\n    say \"$a is not null\"; #\n} # OUTPUT: «129110040087761027839616029934664535539337183380513 is not null␤»\n\nFor block syntax details, see the documentation for the L<C<Block>|/type/Block>\ntype.\n\n=head2 Signatures\n\nThe parameters that a function accepts are described in its I<signature>.\n\n=for code\nsub format(Str $s) { ... }\n-> $a, $b { ... }\n\nDetails about the syntax and use of signatures can be found in the\ndocumentation on the L<C<Signature>|/type/Signature> class.\n\n=head3 X<Automatic signatures|Variables,@_>\n\nX<|Variables,%_>\nIf no signature is provided but either of the two automatic variables C<@_> or\nC<%_> are used in the function body, a signature with C<*@_> or C<*%_> will be\ngenerated. Both automatic variables can be used at the same time.\n\n    sub s { say @_, %_ };\n    say &s.signature # OUTPUT: «(*@_, *%_)␤»\n\n=head2 X<Arguments|Language,Argument>\n\nArguments are supplied as a comma separated list. To disambiguate nested calls,\nuse parentheses:\n\n    sub f(&c){ c() * 2 }; # call the function reference c with empty parameter list\n    sub g($p){ $p - 2 };\n    say(g(42), 45);       # pass only 42 to g()\n\nWhen calling a function, positional arguments should be supplied\nin the same order as the function's signature. Named arguments\nmay be supplied in any order, but it's considered good form to\nplace named arguments after positional arguments. Inside the\nargument list of a function call, some special syntax is supported:\n\n    sub f(|c){};\n    f :named(35);     # A named argument (in \"adverb\" form)\n    f named => 35;    # Also a named argument\n    f :35named;       # A named argument using abbreviated adverb form\n    f 'named' => 35;  # Not a named argument, a Pair in a positional argument\n    f 'hi', :1x, :2y; # Positional and named arguments\n    my \\c = <a b c>.Capture;\n    f |c;             # Merge the contents of Capture $c as if they were supplied\n\nArguments passed to a function are conceptually first collected in a\nL<C<Capture>|/type/Capture> container. Details about the syntax and use of these containers\ncan be found in L<C<Capture>|/type/Capture>'s documentation.\n\nWhen using named arguments, note that normal list \"pair-chaining\" allows\none to skip commas between named arguments.\n\n    sub f(|c){};\n    f :dest</tmp/foo> :src</tmp/bar> :lines(512);\n    f :32x :50y :110z;   # This flavor of \"adverb\" works, too\n    f :a:b:c;            # The spaces are also optional.\n\nIf positional arguments are also passed, then either they must be passed\nwithin parentheses placed I<immediately> after the function's name or the comma\nafter the last positional argument must be kept when chaining named arguments in\nabbreviated adverb form. The spaces between chained named arguments and\nthe list of positional arguments is optional.\n\n    sub p($x, $y, :$translate, :$rotate) {};\n    p(1, 1, :translate, :rotate); # normal way\n    p 1, 1, :translate, :rotate;  # also normal way\n\n    p(1, 1) :translate  :rotate;  # parentheses + chained named arguments\n    p(1, 1) :translate:rotate;\n    p(1, 1):translate:rotate;\n\n    p 1, 1, :translate  :rotate;  # dangling comma + chained named arguments\n    p 1, 1, :translate:rotate;\n    p 1, 1,:translate:rotate;\n\n=head2 Return values\n\nAny L<C<Block>|/type/Block> or L<C<Routine>|/type/Routine> will provide the value of its last expression as\na return value to the caller. If either L<return|/language/control#return> or\nL<return-rw|/language/control#return-rw> is called, then its parameter, if any,\nwill become the return value. The default return value is L<C<Nil>|/type/Nil>.\n\n    sub a { 42 };\n    sub b { say a };\n    sub c { };\n    b;     # OUTPUT: «42␤»\n    say c; # OUTPUT: «Nil␤»\n\nMultiple return values are returned as a list or by creating a\nL<C<Capture>|/type/Capture>. Destructuring can be used to untangle multiple return\nvalues.\n\n    sub a { 42, 'answer' };\n    put a.raku;\n    # OUTPUT: «(42, \"answer\")␤»\n\n    my ($n, $s) = a;\n    put [$s, $n];\n    # OUTPUT: «answer 42␤»\n\n    sub b { <a b c>.Capture };\n    put b.raku;\n    # OUTPUT: «\\(\"a\", \"b\", \"c\")␤»\n\n=head2 Return type constraints\n\nRaku has many ways to specify a function's return type:\n\n=for code\nsub foo(--> Int)      {}; say &foo.returns; # OUTPUT: «(Int)␤»\n=for code\nsub foo() returns Int {}; say &foo.returns; # OUTPUT: «(Int)␤»\n=for code\nsub foo() of Int      {}; say &foo.returns; # OUTPUT: «(Int)␤»\n=for code\nmy Int sub foo()      {}; say &foo.returns; # OUTPUT: «(Int)␤»\n\nAttempting to return values of another type will cause a compilation error.\n\n=for code\nsub foo() returns Int { \"a\"; }; foo; # Type check fails\n\nC<returns> and C<of> are equivalent, and both take only a Type since they are\ndeclaring a trait of the L<C<Callable>|/type/Callable>. The last declaration is, in\nfact, a type declaration, which obviously can take only a type. In the other hand,\nC«-->» can take either undefined or definite values.\n\nNote that L<C<Nil>|/type/Nil> and L<C<Failure>|/type/Failure> are exempt from return type constraints and\ncan be returned from any routine, regardless of its constraint:\n\n=for code\nsub foo() returns Int { fail   }; foo; # Failure returned\nsub bar() returns Int { return }; bar; # Nil returned\n\n=head2 X<Multi-dispatch|Syntax,multi>\n\nRaku allows for writing several routines with the same name but different\nsignatures. When the routine is called by name, the runtime environment\ndetermines the proper I<candidate> and invokes it.\n\nEach candidate is declared with the C<multi> keyword. Dispatch happens\ndepending on the parameter L<arity|/type/Code#method_arity> (number), type and\nname; and under some circumstances the order of the multi\ndeclarations. Consider the following example:\n\n=begin code\n# version 1\nmulti happy-birthday( $name ) {\n    say \"Happy Birthday $name !\";\n}\n\n# version 2\nmulti happy-birthday( $name, $age ) {\n    say \"Happy {$age}th Birthday $name !\";\n}\n\n# version 3\nmulti happy-birthday( :$name, :$age, :$title  = 'Mr' ) {\n    say \"Happy {$age}th Birthday $title $name !\";\n}\n\n\n# calls version 1 (arity)\nhappy-birthday 'Larry';                        # OUTPUT: «Happy Birthday Larry !␤»\n# calls version 2 (arity)\nhappy-birthday 'Luca', 40;                     # OUTPUT: «Happy 40th Birthday Luca !␤»\n# calls version 3\n# (named arguments win against arity)\nhappy-birthday( age => '50', name => 'John' ); # OUTPUT: «Happy 50th Birthday Mr John !␤»\n# calls version 2 (arity)\nhappy-birthday( 'Jack', 25 );                  # OUTPUT: «Happy 25th Birthday Jack !␤»\n=end code\n\nThe first two versions of the C<happy-birthday> sub differs only in the arity\n(number of arguments), while the third version uses named arguments and is\nchosen only when named arguments are used, even if the arity is the same of\nanother C<multi> candidate.\n\nWhen two sub have the same arity, the type of the arguments drive the dispatch;\nwhen there are named arguments they drive the dispatch even when their type is\nthe same as another candidate:\n\n=begin code\nmulti happy-birthday( Str $name, Int $age ) {\n    say \"Happy {$age}th Birthday $name !\";\n}\n\nmulti happy-birthday( Str $name, Str $title ) {\n    say \"Happy Birthday $title $name !\";\n}\n\nmulti happy-birthday( Str :$name, Int :$age ) {\n    say \"Happy Birthday $name, you turned $age !\";\n}\n\nhappy-birthday 'Luca', 40;                 # OUTPUT: «Happy 40th Birthday Luca !␤»\nhappy-birthday 'Luca', 'Mr';               # OUTPUT: «Happy Birthday Mr Luca !␤»\nhappy-birthday age => 40, name => 'Luca';  # OUTPUT: «Happy Birthday Luca, you turned 40 !␤»\n=end code\n\nNamed parameters participate in the dispatch even if they are not provided in\nthe call. Therefore a multi candidate with named parameters will be given\nprecedence.\n\nI<More information about L<type constraints|/language/signatures#Type_constraints>\nis available.>\n\n    multi as-json(Bool $d) { $d ?? 'true' !! 'false'; }\n    multi as-json(Real $d) { ~$d }\n    multi as-json(@d)      { sprintf '[%s]', @d.map(&as-json).join(', ') }\n\n    say as-json( True );                        # OUTPUT: «true␤»\n    say as-json( 10.3 );                        # OUTPUT: «10.3␤»\n    say as-json( [ True, 10.3, False, 24 ] );   # OUTPUT: «[true, 10.3, false, 24]␤»\n\nFor some signature differences (notably when using a where clause or a subset)\nthe order of definition of the multi methods or subs is used, evaluating\neach possibility in turn.  See\nL<multi resolution by order of definition|/language/functions#multi_resolution_by_order_of_definition>\nbelow for examples.\n\nC<multi> without any specific routine type always defaults to a C<sub>, but you\ncan use it on methods as well. The candidates are all the multi methods of the\nobject:\n\n    class Congrats {\n        multi method congratulate($reason, $name) {\n            say \"Hooray for your $reason, $name\";\n        }\n    }\n\n    role BirthdayCongrats {\n        multi method congratulate('birthday', $name) {\n            say \"Happy birthday, $name\";\n        }\n        multi method congratulate('birthday', $name, $age) {\n            say \"Happy {$age}th birthday, $name\";\n        }\n    }\n\n    my $congrats = Congrats.new does BirthdayCongrats;\n\n    $congrats.congratulate('promotion','Cindy'); # OUTPUT: «Hooray for your promotion, Cindy␤»\n    $congrats.congratulate('birthday','Bob');    # OUTPUT: «Happy birthday, Bob␤»\n\nUnlike C<sub>, if you use named parameters with multi methods, the parameters\nmust be required parameters to behave as expected.\n\nPlease note that a non-multi sub or operator will hide multi candidates of the\nsame name in any parent scope or child scope. The same is true for imported\nnon-multi candidates.\n\nMulti-dispatch can also work on parameter traits, with routines with C<is rw>\n parameters having a higher priority than those that do not:\n\n=for code\nproto þoo (|) {*}\nmulti þoo( $ðar is rw ) { $ðar = 42 }\nmulti þoo( $ðar ) { $ðar + 42 }\nmy $bar = 7;\nsay þoo($bar); # OUTPUT: «42␤»\n\n=head3 X<proto|Syntax,proto>\n\nC<proto> is a way to formally declare commonalities between C<multi>\ncandidates. It acts as a wrapper that can validate but not modify\narguments. Consider this basic example:\n\n    proto congratulate(Str $reason, Str $name, |) {*}\n    multi congratulate($reason, $name) {\n       say \"Hooray for your $reason, $name\";\n    }\n    multi congratulate($reason, $name, Int $rank) {\n       say \"Hooray for your $reason, $name -- got rank $rank!\";\n    }\n\n    congratulate('being a cool number', 'Fred');     # OK\n    congratulate('being a cool number', 'Fred', 42); # OK\n\n=for code :skip-test<illustrates error>\ncongratulate('being a cool number', 42);         # Proto match error\n\nThe proto insists that all C<multi congratulate> subs conform to the basic\nsignature of two strings, optionally followed by further parameters. The C<|> is\nan un-named L<C<Capture>|/type/Capture> parameter, and allows a C<multi> to take additional\narguments. The first two calls succeed, but the third fails (at compile time)\nbecause C<42> doesn't match L<C<Str>|/type/Str>.\n\n=for code :preamble<sub congratulate {}>\nsay &congratulate.signature # OUTPUT: «(Str $reason, Str $name, | is raw)␤»\n\nYou can give the C<proto> a function body, and place the C<{*}> (note there is no\nwhitespace inside the curly braces) where\nyou want the dispatch to be done. This can be useful when you have a\n\"hole\" in your routine that gives it different behavior depending on the\narguments given:\n\n    # attempts to notify someone -- False if unsuccessful\n    proto notify(Str $user, Str $msg) {\n       my \\hour = DateTime.now.hour;\n       if 8 < hour < 22 {\n          return {*};\n       } else {\n          # we can't notify someone when they might be sleeping\n          return False;\n       }\n    }\n\nSince C<proto> is a wrapper for C<multi> candidates, the signatures of\nthe routine's C<multi> candidates do not necessarily have to match that\nof the C<proto>; arguments of C<multi> candidates may have subtypes of\nthose of the C<proto>, and the return types of the C<multi> candidates\nmay be entirely different from that of the C<proto>. Using differing\ntypes like this is especially useful when giving C<proto> a function\nbody:\n\n=begin code\nenum DebugType <LOG WARNING ERROR>;\n\n#|[ Prints a message to stderr with a color-coded key. ]\nproto debug(DebugType:D $type, Str:D $message --> Bool:_) {\n    note sprintf qb/\\e[1;%dm[%s]\\e[0m %s/, {*}, $type.key, $message\n}\nmulti debug(LOG;; Str:D --> 32)     { }\nmulti debug(WARNING;; Str:D --> 33) { }\nmulti debug(ERROR;; Str:D --> 31)   { }\n=end code\n\nC<{*}> always dispatches to candidates with the parameters it's called\nwith. Parameter defaults and type coercions will work but are not passed on.\n\n=for code\nproto mistake-proto(Str() $str, Int $number = 42) {*}\nmulti mistake-proto($str, $number) { say $str.^name }\nmistake-proto(7, 42);  # OUTPUT: «Int␤» -- not passed on\n=for code :skip-test<illustrates error>\nmistake-proto('test'); # fails -- not passed on\n\nA longer example using C<proto> for methods shows how to extract common functionality into\na proto method.\n\n=for code\nclass NewClass {\n    has $.debug is rw = False;\n    has $.value is rw = 'Initial value';\n    proto method handle( | ) {\n        note \"before value is ｢$.value｣\" if $.debug;\n        {*}\n        note \"after value is ｢$.value｣\" if $.debug;\n    }\n    multi method handle(Str $s) {\n        $.value = $s;\n        say 'in string'\n    }\n    multi method handle(Positional $s) {\n        $.value = $s[0];\n        say 'in positional'\n    }\n    multi method handle( $a, $b ) {\n        $.value = \"$a is looking askance at $b\";\n        say 'with more than one value'\n    }\n}\nmy NewClass $x .= new;\n$x.handle('hello world');\n$x.handle(<hello world>);\n$x.debug = True;\n$x.handle('hello world');\n$x.handle(<hello world>);\n$x.handle('Claire', 'John');\n# OUTPUT:\n# in string\n# in positional\n# before value is ｢hello｣\n# in string\n# after value is ｢hello world｣\n# before value is ｢hello world｣\n# in positional\n# after value is ｢hello｣\n# before value is ｢hello｣\n# with more than one value\n# after value is ｢Claire is looking askance at John｣\n\n=head3 X<only|Syntax,only>\n\nThe C<only> keyword preceding C<sub> or C<method> indicates that it will be the\nonly function with that name that inhabits a given namespace.\n\n    only sub you () {\"Can make all the world seem right\"};\n\nThis will make other declarations in the same namespace, such as\n\n    sub you ( $can ) { \"Make the darkness bright\" }\n\nfail with an exception of type L<C<X::Redeclaration>|/type/X::Redeclaration>. C<only> is the default value\nfor all subs; in the case above, not declaring the first subroutine as C<only>\nwill yield exactly the same error; however, nothing prevents future developers\nfrom declaring a proto and preceding the names with C<multi>. Using C<only>\nbefore a routine is a\nL<defensive programming|https://en.wikipedia.org/wiki/Defensive_programming>\nfeature that declares the intention of not having routines with the same name\ndeclared in the same namespace in the future.\n\n=begin code :lang<text>\n(exit code 1)\n===SORRY!=== Error while compiling /tmp/only-redeclaration.raku\nRedeclaration of routine 'you' (did you mean to declare a multi-sub?)\nat /tmp/only-redeclaration.raku:3\n------> <BOL>⏏<EOL>\n=end code\n\nAnonymous subs cannot be declared C<only>. C<only sub {}> will throw an error of\ntype, surprisingly, L<C<X::Anon::Multi>|/type/X::Anon::Multi>.\n\n\n=head3 multi resolution by order of definition\n\nWhen the breakdown by parameter type is not enough to find an unambiguous\nmatch, there are some different tiebreakers that may be evaluated in order\nof declaration of the methods or subs: these include where clauses and\nsubsets, named parameters, and signature unpacks.\n\nIn this code example, two multi subs are distinguished only by where clauses\nwhere there's one ambiguous case that might pass either of them, the value 4.\nIn this case, which ever multi sub is defined first wins:\n\n=begin code\n{\n  multi check_range ( Int $n where {$_ > 3} ) {\n      return \"over 3\";\n  };\n  multi check_range ( Int $n where {$_ < 5} ) {\n      return \"under 5\";\n  };\n  say check_range(4);  # OUTPUT: over 3\n}\n{\n  multi check_range ( Int $n where {$_ < 5} ) {\n      return \"under 5\";\n  };\n  multi check_range ( Int $n where {$_ > 3} ) {\n      return \"over 3\";\n  };\n  say check_range(4);  # OUTPUT: under 5\n}\n=end code\n\nIn the following example, three subsets are used to restrict strings to\ncertain allowed values, where there are overlaps between all three:\n\n=begin code\nsubset Monster  of Str where { $_ eq any( <godzilla gammera ghidora> ) };\nsubset Hero     of Str where { $_ eq any( <godzilla ultraman inframan> ) };\nsubset Knockoff of Str where { $_ eq any( <gammera inframan thorndike> ) };\n\n{\n    multi speak (Monster $name) {\n        say \"The monster, $name roars!\";\n    }\n    multi speak (Hero $name) {\n        say \"The hero, $name shouts!\";\n    }\n    multi speak (Knockoff $name) {\n        say \"The knockoff, $name, slinks away...\";\n    }\n    speak('godzilla');     # OUTPUT: The monster, godzilla roars!\n    speak('gammera');      # OUTPUT: The monster, gammera roars!\n    speak('inframan');     # OUTPUT: The hero, inframan shouts!\n}\n=end code\n\nNote that here 'godzilla' is treated as Monster, not as Hero, because the\nMonster multi comes first; and neither 'gammera' or 'inframan' are treated\nas Knockoff, because that multi comes last.\n\nIt should be noted that the order of definition is the order in which Raku\nsees them, which might not be easy to discern if, for example, the multi\nsubs were imported from different modules.  As the organization of a code\nbase becomes more complex, object classes may scale better than using\nsubsets as types, as in this example.\n\n\n=head1 Conventions and idioms\n\nWhile the dispatch system described above provides a lot of flexibility,\nthere are some conventions that most internal functions, and those in\nmany modules, will follow.\n\n=head2 Slurpy conventions\n\nPerhaps the most important one of these conventions is the way slurpy list\narguments are handled. Most of the time, functions will not automatically\nflatten slurpy lists. The rare exceptions are those functions that don't have a\nreasonable behavior on lists of lists (e.g., L<chrs|/routine/chrs>) or where\nthere is a conflict with an established idiom (e.g., L<pop|/routine/pop> being\nthe inverse of L<push|/routine/push>).\n\nIf you wish to match this look and feel, any L<C<Iterable>|/type/Iterable>\nargument must be broken out element-by-element using a C<**@> slurpy, with\ntwo nuances:\n\n=item An L<C<Iterable>|/type/Iterable> inside a L<Scalar container|/language/containers#Scalar_containers> doesn't count.\n\n=item L<C<List>|/type/List>s created with a L<C<,>|/routine/,> at the top level only count as one L<C<Iterable>|/type/Iterable>.\n\nThis can be achieved by using a slurpy with a\nL<C<+>|/language/signatures#Parameter_traits_and_modifiers> or C<+@> instead of C<**@>:\n\n    sub grab(+@a) { \"grab $_\".say for @a }\n\nwhich is shorthand for something very close to:\n\n    multi grab(**@a) { \"grab $_\".say for @a }\n    multi grab(\\a) {\n        a ~~ Iterable and a.VAR !~~ Scalar ?? nextwith(|a) !! nextwith(a,)\n    }\n\nThis results in the following behavior, which is known as the\nI<\"single argument rule\"> and is important to understand when invoking\nslurpy functions:\n\n=for code :preamble<sub grab(+@a) {};>\ngrab(1, 2);      # OUTPUT: «grab 1␤grab 2␤»\ngrab((1, 2));    # OUTPUT: «grab 1␤grab 2␤»\ngrab($(1, 2));   # OUTPUT: «grab 1 2␤»\ngrab((1, 2), 3); # OUTPUT: «grab 1 2␤grab 3␤»\n\nThis also makes user-requested flattening feel consistent whether there is\none sublist, or many:\n\n=for code :preamble<sub grab(+@a) {};>\ngrab(flat (1, 2), (3, 4));   # OUTPUT: «grab 1␤grab 2␤grab 3␤grab 4␤»\ngrab(flat $(1, 2), $(3, 4)); # OUTPUT: «grab 1 2␤grab 3 4␤»\ngrab(flat (1, 2));           # OUTPUT: «grab 1␤grab 2␤»\ngrab(flat $(1, 2));          # OUTPUT: «grab 1␤grab 2␤»\n\nIt's worth noting that mixing binding and sigilless variables\nin these cases requires a bit of finesse, because there is no\nL<C<Scalar>|/type/Scalar> intermediary used during binding.\n\n=for code :preamble<sub grab(+@a) {};>\nmy $a = (1, 2);  # Normal assignment, equivalent to $(1, 2)\ngrab($a);        # OUTPUT: «grab 1 2␤»\nmy $b := (1, 2); # Binding, $b links directly to a bare (1, 2)\ngrab($b);        # OUTPUT: «grab 1␤grab 2␤»\nmy \\c = (1, 2);  # Sigilless variables always bind, even with '='\ngrab(c);         # OUTPUT: «grab 1␤grab 2␤»\n\nSee the L«documentation of the C<list> subroutine|/type/List#routine_list» for\nmore examples of how to use a routine that adheres to the single argument rule.\n\n=head1 Functions are first-class objects\n\nFunctions and other code objects can be passed around as values, just like any\nother object.\n\nThere are several ways to get hold of a code object. You can assign it to a\nvariable at the point of declaration:\n\n    my $square = sub (Numeric $x) { $x * $x }\n    # and then use it:\n    say $square(6);    # OUTPUT: «36␤»\n\nX<|Syntax,prefix &>\nOr you can reference an existing named function by using the C<&>-sigil in\nfront of it.\n\n    sub square($x) { $x * $x };\n\n    # get hold of a reference to the function:\n    my $func = &square\n\nThis is very useful for I<higher order functions>, that is, functions that\ntake other functions as input. A simple one is L<map|/type/List#routine_map>,\nwhich applies a function to each input element:\n\n    sub square($x) { $x * $x };\n    my @squared = map &square,  1..5;\n    say join ', ', @squared;        # OUTPUT: «1, 4, 9, 16, 25␤»\n\nYou can use the same for operators, except that in that case the name with\nwhich they have been declared, using C<infix:>, must be used:\n\n     my $exp := &infix:<**>; say $exp(7,3); # OUTPUT: «343␤»\n\nThis can be done even in cases where operators have been I<auto-generated>,\nfor instance in this case where C<XX> is the metaoperator C<X> applied to the\nC<X> operator.\n\n    my $XX := &infix:<XX>; say $XX( [1,(2,3)] , [(4,5),6]  );\n    # OUTPUT: «(((1 (4 5))) ((1 6)) (((2 3) (4 5))) (((2 3) 6)))␤»\n\nBaseline is that, in case of operators, you don't really need to worry about\nthe actual way they were defined, just use the C«&infix< >» to grab a pointer\nto them.\n\n\n\n=head2 Z<>Infix form\n\nTo call a subroutine with 2 arguments like an infix operator, use a subroutine\nreference surrounded by C<[> and C<]>.\n\n    sub plus { $^a + $^b };\n    say 21 [&plus] 21;\n    # OUTPUT: «42␤»\n\n=head2 X<Closures|Language,closures>\n\nAll code objects in Raku are I<closures>, which means they can reference\nlexical variables from an outer scope.\n\n    sub generate-sub($x) {\n        my $y = 2 * $x;\n        return sub { say $y };\n        #      ^^^^^^^^^^^^^^  inner sub, uses $y\n    }\n    my $generated = generate-sub(21);\n    $generated(); # OUTPUT: «42␤»\n\nHere, C<$y> is a lexical variable inside C<generate-sub>, and the inner\nsubroutine that is returned uses it. By the time that inner sub is called,\nC<generate-sub> has already exited. Yet the inner sub can still use C<$y>,\nbecause it I<closed> over the variable.\n\nAnother closure example is the use of L<map|/type/List#routine_map> to multiply\na list of numbers:\n\n    my $multiply-by = 5;\n    say join ', ', map { $_ * $multiply-by }, 1..5;     # OUTPUT: «5, 10, 15, 20, 25␤»\n\nHere, the block passed to C<map> references the variable C<$multiply-by> from\nthe outer scope, making the block a closure.\n\nLanguages without closures cannot easily provide higher-order functions that\nare as easy to use and powerful as C<map>.\n\n=head2 Routines\n\nRoutines are code objects that conform to the type L<C<Routine>|/type/Routine>, most\nnotably L<C<Sub>|/type/Sub>, L<C<Method>|/type/Method>, L<C<Regex>|/type/Regex>\nand L<C<Submethod>|/type/Submethod>.\n\nThey carry extra functionality in addition to what a L<C<Block>|/type/Block>\nsupplies: they can come as L<multis|#Multi-dispatch>, you can\nL<wrap|/type/Routine#method_wrap> them, and exit early with C<return>:\n\n    my $keywords = set <if for unless while>;\n\n    sub has-keyword(*@words) {\n        for @words -> $word {\n            return True if $word (elem) $keywords;\n        }\n        False;\n    }\n\n    say has-keyword 'not', 'one', 'here';       # OUTPUT: «False␤»\n    say has-keyword 'but', 'here', 'for';       # OUTPUT: «True␤»\n\nHere, C<return> doesn't just leave the block inside which it was called, but\nthe whole routine. In general, blocks are transparent to C<return>, they\nattach to the outermost routine.\n\nX<|Language,use soft (pragma)>\nRoutines can be inlined and as such provide an obstacle for wrapping. Use the\npragma C<use soft;> to prevent inlining to allow wrapping at runtime.\n\n    sub testee(Int $i, Str $s){\n        rand.Rat * $i ~ $s;\n    }\n\n    sub wrap-to-debug(&c){\n        say \"wrapping {&c.name} with arguments {&c.signature.raku}\";\n        &c.wrap: sub (|args){\n            note \"calling {&c.name} with {args.gist}\";\n            my \\ret-val := callwith(|args);\n            note \"returned from {&c.name} with return value {ret-val.raku}\";\n            ret-val\n        }\n    }\n\n    my $testee-handler = wrap-to-debug(&testee);\n    # OUTPUT: «wrapping testee with arguments :(Int $i, Str $s)␤»\n\n    say testee(10, \"ten\");\n    # OUTPUT: «calling testee with \\(10, \"ten\")␤returned from testee with return value \"6.151190ten\"␤6.151190ten␤»\n    &testee.unwrap($testee-handler);\n    say testee(10, \"ten\");\n    # OUTPUT: «6.151190ten␤»\n\n\n=comment Important ones: candidates, wrap, unwrap, assuming, arity, count\n\n=head1 Defining operators\n\nOperators are just subroutines with funny names. The funny names are composed\nof the category name (C<infix>, C<prefix>, C<postfix>, C<circumfix>,\nC<postcircumfix>), followed by a colon, and a list of the operator name or\nnames (two components in the case of circumfix and postcircumfix). An expanded\nexplanation of all these operators and what they mean is included\nL<in this table|/language/operators#Operator_classification>.\n\nThis works both for adding multi candidates to existing operators and for\ndefining new ones. In the latter case, the definition of the new subroutine\nautomatically installs the new operator into the grammar, but only in the\ncurrent lexical scope. Importing an operator via C<use> or C<import> also\nmakes it available.\n\n=begin code\n# adding a multi candidate to an existing operator:\nmulti infix:<+>(Int $x, \"same\") { 2 * $x };\nsay 21 + \"same\";            # OUTPUT: «42␤»\n\n# defining a new operator\nsub postfix:<!>(Int $x where { $x >= 0 }) { [*] 1..$x };\nsay 6!;                     # OUTPUT: «720␤»\n=end code\n\nThe operator declaration becomes available as soon as possible, so you can\nrecurse into a just-defined operator:\n\n=begin code\nsub postfix:<!>(Int $x where { $x >= 0 }) {\n    $x == 0 ?? 1 !! $x * ($x - 1)!\n}\nsay 6!;                     # OUTPUT: «720␤»\n=end code\n\nCircumfix and postcircumfix operators are made of two delimiters, one opening\nand one closing.\n\n=begin code\nsub circumfix:<START END>(*@elems) {\n    \"start\", @elems, \"end\"\n}\n\nsay START 'a', 'b', 'c' END;        # OUTPUT: «(start [a b c] end)␤»\n=end code\n\nPostcircumfixes also receive the term after which they are parsed as\nan argument:\n\n=begin code\nsub postcircumfix:<!! !!>($left, $inside) {\n    \"$left -> ( $inside )\"\n}\nsay 42!! 1 !!;      # OUTPUT: «42 -> ( 1 )␤»\n=end code\n\nBlocks can be assigned directly to operator names. Use a variable declarator and\nprefix the operator name with an C<&>-sigil.\n\n    my &infix:<ieq> = -> |l { [eq] l>>.fc };\n    say \"abc\" ieq \"Abc\";\n    # OUTPUT: «True␤»\n\n=head2 X<Precedence|Traits,is tighter>\n\nX<|Traits,is equiv>\nX<|Traits,is looser>\n\nOperator precedence in Raku is specified relative to existing operators. The\ntraits C<is tighter>, C<is equiv> and C<is looser> can be provided with an\noperator to indicate how the precedence of the new operator is related to\nother, existing ones. More than one trait can be applied.\n\nFor example, C«infix:<*>» has a tighter precedence than C«infix:<+>»,\nand squeezing one in between works like this:\n\n=begin code\nsub infix:<!!>($a, $b) is tighter(&infix:<+>) {\n    2 * ($a + $b)\n}\n\nsay 1 + 2 * 3 !! 4;     # OUTPUT: «21␤»\n=end code\n\nHere, the C<1 + 2 * 3 !! 4> is parsed as C<1 + ((2 * 3) !! 4)>, because the\nprecedence of the new C<!!> operator is between that of C<+> and C<*>.\n\nThe same effect could have been achieved with:\n\n    sub infix:<!!>($a, $b) is looser(&infix:<*>) { ... }\n\nTo put a new operator on the same precedence level as an existing operator,\nuse C<is equiv(&other-operator)> instead.\n\n\n=head2 Associativity\n\nWhen the same operator appears several times in a row, there are multiple\npossible interpretations. For example:\n\n    1 + 2 + 3\n\ncould be parsed as\n\n    (1 + 2) + 3         # left associative\n\nor as\n\n    1 + (2 + 3)         # right associative\n\nFor addition of real numbers, the distinction is somewhat moot, because C<+> is\nL<mathematically associative|https://en.wikipedia.org/wiki/Associative_property>.\n\nBut for other operators it matters a great deal. For example, for the\nexponentiation/power operator, C«infix:<**>»:\n\n    say 2 ** (2 ** 3);      # OUTPUT: «256␤»\n    say (2 ** 2) ** 3;      # OUTPUT: «64␤»\n\nRaku has the following possible associativity configurations:\n\n=begin table\n\n    Associativity | Meaning of $a ! $b ! $c\n    ==============+========================\n    left          | ($a ! $b) ! $c\n    right         | $a ! ($b ! $c)\n    non           | ILLEGAL\n    chain         | ($a ! $b) and ($b ! $c)\n    list          | infix:<!>($a; $b; $c)\n\n=end table\n\nThe L<Operator docs|/language/operators#Operator_associativity> contain\nadditional details about operator associativity.\n\nX<|Traits,is assoc>\nYou can specify the associativity of an infix operator with the C<is assoc> trait,\nwhere C<left> is the default associativity. Specifying the associativity of\nnon-infix operators is planed but not yet implemented.\n\n=begin code\nsub infix:<§>(*@a) is assoc<list> {\n    '(' ~ @a.join('|') ~ ')';\n}\n\nsay 1 § 2 § 3;      # OUTPUT: «(1|2|3)␤»\n=end code\n\n=head1 Traits\n\nI<Traits> are subroutines that run at compile time and modify the behavior of a\ntype, variable, routine, attribute, or other language object.\n\nExamples of traits are:\n\n=for code :skip-test<incomplete code>\nclass ChildClass is ParentClass { ... }\n#                ^^ trait, with argument ParentClass\nhas $.attrib is rw;\n#            ^^^^^  trait with name 'rw'\nclass SomeClass does AnotherRole { ... }\n#               ^^^^ trait\nhas $!another-attribute handles <close>;\n#                       ^^^^^^^ trait\n\n... and also C<is tighter>, C<is looser>, C<is equiv> and C<is assoc> from the\nprevious section.\n\nTraits are subs declared in the form C«trait_mod<VERB>», where C<VERB>\nstands for the name like C<is>, C<does> or C<handles>. It receives the modified\nthing as argument, and the name as a named argument. See L<C<Sub>|/type/Sub#Traits>\nfor details.\n\n=begin code\nmulti trait_mod:<is>(Routine $r, :$doubles!) {\n    $r.wrap({\n        2 * callsame;\n    });\n}\n\nsub square($x) is doubles {\n    $x * $x;\n}\n\nsay square 3;       # OUTPUT: «18␤»\n=end code\n\nSee L<type Routine|/type/Routine> for the documentation of built-in routine\ntraits.\n\n=head1 Re-dispatching\n\nThere are cases in which a routine might want to call the next method\nfrom a chain. This chain could be a list of parent classes in a class\nhierarchy, or it could be less specific multi candidates from a multi\ndispatch, or it could be the inner routine from a C<wrap>.\n\nFortunately, we have a series of re-dispatching tools that help us to make\nit easy.\n\n=head2 The Next Tools\n\nThe table below represents the next tools in relation to three attributes:\n\n=item1 B<Returns:> \"Yes\" means that it returns, and the code will continue from\nthat point.  \"No\" means that it never returns to this function -- it's as\nthough the call has a built-in \"return\".\n\n=item1 B<Arguments:> Specifically, whether the arguments from the current\nfunction are reused in the call, or whether you need to specify some\narguments.  In the case of C<nextcallee>, there are no arguments needed,\nbecause they're instead passed to the return value when it's called.\n\n=item1 B<Referee:> This is the method that will be called by the tool (the\nreciprocal of \"referrer\").  It can be one of:\n\n=item2 B<next:> The next item in the chain\n\n=item2 B<self:> It will call itself again, as in recursion\n\n=item2 B<preset:> It will call the item that was saved by C<nextcallee>\n\n=begin table\n\n                     | Returns | Arguments | Referee*\n    =================+=========+===========+========\n    nextsame         | No      | Reuse     | next\n    nextwith         | No      | Specify   | next\n    callsame         | Yes     | Reuse     | next\n    callwith         | Yes     | Specify   | next\n    nextcallee       | Yes     | None      | next\n    samewith         | Yes     | Specify   | self\n    nextcallee's rv* | Yes     | Specify   | preset\n\n=end table\n* C<nextcallee>'s rv is the tool returned from calling C<nextcallee>, which\nitself can be called.\n\nFrom the above we learn:\n\n=item C<with> always means that the arguments need to be specified -- this\none is consistent.\n\n=item C<same> at word end means the arguments of the currently running\nfunction will automatically be reused when calling the referee.  Note that\nC<samewith>, despite containing \"same\", doesn't mean that the arguments will\nbe reused.  That's because the \"same\" here refers to the Referee -- the\nfunction is calling the same method as itself, not the next in the call stack.\n\n=item C<next> means that it won't return, except for C<nextcallee>, which does\nreturn\n\n=head2 X<sub callsame|Subroutines,callsame>\n\nC<callsame> calls the next matching candidate with the same arguments that were\nused for the current candidate and returns that candidate's return value.\n\n=begin code\nproto a(|) {*}\n\nmulti a(Any $x) {\n    say \"Any $x\";\n    return 5;\n}\n\nmulti a(Int $x) {\n    say \"Int $x\";\n    my $res = callsame;\n    say \"Back in Int with $res\";\n}\n\na 1;        # OUTPUT: «Int 1␤Any 1␤Back in Int with 5␤»\n=end code\n\n=head2 X<sub callwith|Subroutines,callwith>\n\nC<callwith> calls the next candidate matching the original signature, that is,\nthe next function that could possibly be used with the arguments provided by\nusers and returns that candidate's return value.\n\n=begin code\nproto a(|) {*}\n\nmulti a(Any $x) {\n    say \"Any $x\";\n    return 5;\n}\nmulti a(Int $x) {\n    say \"Int $x\";\n    my $res = callwith($x + 1);\n    say \"Back in Int with $res\";\n}\n\na 1;        # OUTPUT: «Int 1␤Any 2␤Back in Int with 5␤»\n=end code\n\nHere, C<a 1> calls the most specific L<C<Int>|/type/Int> candidate first, and C<callwith>\nre-dispatches to the less specific L<C<Any>|/type/Any> candidate. Note that although our\nparameter C<$x + 1> is an L<C<Int>|/type/Int>, still we call the next candidate in the chain.\n\nIn this case, for example:\n\n=begin code\nproto how-many(|) {*}\n\nmulti how-many( Associative $a ) {\n    say \"Associative $a \";\n    my $calling = callwith( 1 => $a );\n    return $calling;\n}\n\nmulti how-many( Pair $a ) {\n    say \"Pair $a \";\n    return \"There is $a \"\n\n}\n\nmulti how-many( Hash $a ) {\n    say \"Hash $a\";\n    return \"Hashing $a\";\n}\n\nmy $little-piggy = little => 'piggy';\nsay $little-piggy.^name;        # OUTPUT: «Pair␤»\nsay &how-many.cando( \\( $little-piggy ));\n# OUTPUT: «(sub how-many (Pair $a) { #`(Sub|68970512) ... } sub how-many (Associative $a) { #`(Sub|68970664) ... })␤»\nsay how-many( $little-piggy  ); # OUTPUT: «Pair little     piggy␤There is little piggy␤»\n=end code\n\nthe only candidates that take the L<C<Pair>|/type/Pair> argument supplied by the user are the\ntwo functions defined first. Although a L<C<Pair>|/type/Pair> can be easily coerced to a\nL<C<Hash>|/type/Hash>, here is how signatures match:\n\n=for code\nsay :( Pair ) ~~ :( Associative ); # OUTPUT: «True␤»\nsay :( Pair ) ~~ :( Hash );        # OUTPUT: «False␤»\n\nThe arguments provided by us are a L<C<Pair>|/type/Pair>. It does not match a L<C<Hash>|/type/Hash>, so the\ncorresponding function is thus not included in the list of candidates, as can be\nseen by the output of C<&how-many.cando( \\( $little-piggy ));>.\n\n=head2 X<sub nextsame|Subroutines,nextsame>\n\nC<nextsame> calls the next matching candidate with the same arguments that were\nused for the current candidate and B<never> returns.\n\n=begin code\nproto a(|) {*}\n\nmulti a(Any $x) {\n    say \"Any $x\";\n    return 5;\n}\nmulti a(Int $x) {\n    say \"Int $x\";\n    nextsame;\n    say \"never executed because nextsame doesn't return\";\n}\n\na 1;        # OUTPUT: «Int 1␤Any 1␤»\n=end code\n\n=head2 X<sub nextwith|Subroutines,nextwith>\n\nC<nextwith> calls the next matching candidate with arguments provided by users\nand B<never> returns.\n\n=begin code\nproto a(|) {*}\n\nmulti a(Any $x) {\n    say \"Any $x\";\n    return 5;\n}\nmulti a(Int $x) {\n    say \"Int $x\";\n    nextwith($x + 1);\n    say \"never executed because nextwith doesn't return\";\n}\n\na 1;        # OUTPUT: «Int 1␤Any 2␤»\n=end code\n\n=head2 X<sub samewith|Subroutines,samewith>\n\nC<samewith> calls the multi again with arguments provided at the call site\nand returns the value provided by the call.  This can be used for self-recursion.\n\n=begin code\nproto factorial(|) {*}\n\nmulti factorial(Int $x where * ≤ 1) { 1 }\nmulti factorial(Int $x) {\n    $x * samewith($x-1);\n}\n\nsay (factorial 10); # OUTPUT: «36288000␤»\n=end code\n\n=head2 X<sub nextcallee|Subroutines,nextcallee>\n\nRedispatch may be required to call a block that is not the current scope what\nprovides C<nextwith> and friends with the problem to referring to the wrong\nscope. Use C<nextcallee> to capture the right candidate and call it at the\ndesired time.\n\n=begin code\nproto pick-winner(|) {*}\n\nmulti pick-winner (Int \\s) {\n    my &nextone = nextcallee;\n    Promise.in(π²).then: { nextone s }\n}\nmulti pick-winner { say \"Woot! $^w won\" }\n\nwith pick-winner ^5 .pick -> \\result {\n    say \"And the winner is...\";\n    await result;\n}\n\n# OUTPUT:\n# And the winner is...\n# Woot! 3 won\n=end code\n\nThe L<C<Int>|/type/Int> candidate takes the C<nextcallee> and then fires up a L<C<Promise>|/type/Promise>\nto be executed in parallel, after some timeout, and then returns. We can't use\nC<nextsame> here, because it'd be trying to C<nextsame> the Promise's block\ninstead of our original routine.\n\nNote that, despite its name, the C<nextcallee> function is like:\n\n=item C<callwith>/C<nextwith>, in that it takes parameters\n\n=item C<callwith>/C<callsame>, in that it returns; the call to C<nextcallee> returns\na reference, and the call to the reference also returns (unlike\nC<nextwith>/C<nextsame>, which don't return)\n\n=head2 X<Wrapped routines|Language,wrapped routines>\n\nBesides those already mentioned above, re-dispatch is helpful in many more\nsituations. For instance, for dispatching to wrapped routines:\n\n=begin code\n# enable wrapping:\nuse soft;\n\n# function to be wrapped:\nsub square-root($x) { $x.sqrt }\n\n&square-root.wrap(sub ($num) {\n   nextsame if $num >= 0;\n   1i * callwith(abs($num));\n});\n\nsay square-root(4);     # OUTPUT: «2␤»\nsay square-root(-4);    # OUTPUT: «0+2i␤»\n=end code\n\n=head2 Routines of parent class\n\nAnother use case is to re-dispatch to methods from parent classes.\n\n=for code\nsay Version.new('1.0.2') # OUTPUT: v1.0.2\n\n=begin code\nclass LoggedVersion is Version {\n    method new(|c) {\n        note \"New version object created with arguments \" ~ c.raku;\n        nextsame;\n    }\n}\n\nsay LoggedVersion.new('1.0.2');\n\n# OUTPUT:\n# New version object created with arguments \\(\"1.0.2\")\n# v1.0.2\n=end code\n\n=head1 Coercion types\n\nCoercion types force a specific type for routine arguments while allowing\nthe routine itself to accept a wider input. When invoked, the arguments are\nnarrowed automatically to the stricter type, and therefore within the routine\nthe arguments have always the desired type.\n\nIn the case the arguments cannot be converted to the stricter type, a I<Type\nCheck> error is thrown.\n\n=begin code\nsub double(Int(Cool) $x) {\n    2 * $x\n}\n\nsay double '21';# OUTPUT: «42␤»\nsay double  21; # OUTPUT: «42␤»\nsay double Any; # Type check failed in binding $x; expected 'Cool' but got 'Any'\n=end code\n\nIn the above example, the L<C<Int>|/type/Int> is the target type to which the\nargument C<$x> will be coerced, and L<C<Cool>|/type/Cool> is the type that the\nroutine accepts as wider input.\n\nIf the accepted wider input type is L<C<Any>|/type/Any>, it is possible to\nabbreviate the coercion C<Int(Any)> by omitting the L<C<Any>|/type/Any> type, thus\nresulting in C<Int()>.\n\nThe coercion works by looking for a method with the same name as the target\ntype: if such method is found on the argument, it is invoked to convert the\nlatter to the expected narrow type. From the above, it is clear that it is\npossible to provide coercion among user types just providing the required\nmethods:\n\n=begin code\nclass Bar {\n   has $.msg;\n}\n\nclass Foo {\n   has $.msg = \"I'm a foo!\";\n\n   # allows coercion from Foo to Bar\n   method Bar {\n       Bar.new(:msg($.msg ~ ' But I am now Bar.'));\n   }\n}\n\n# wants a Bar, but accepts Any\nsub print-bar(Bar() $bar) {\n   say $bar.^name; # OUTPUT: «Bar␤»\n   say $bar.msg;   # OUTPUT: «I'm a foo! But I am now Bar.␤»\n}\n\nprint-bar Foo.new;\n=end code\n\nIn the above code, once a C<Foo> instance is passed as argument to C<print-bar>,\nthe C<Foo.Bar> method is called and the result is placed into C<$bar>.\n\nCoercion types are supposed to work wherever types work, but Rakudo currently\n(2018.05) only implements them in signatures, for both parameters and return\ntypes.\n\n=comment Non-parameter coercion types will theoretically be working in 6.2. Updated the reference above to latest version.\n\nCoercion also works with return types:\n\n=begin code\nsub are-equal (Int $x, Int $y --> Bool(Int) ) { $x - $y };\n\nfor (2,4) X (1,2) -> ($a,$b) {\n    say \"Are $a and $b equal? \", are-equal($a, $b);\n} #  OUTPUT: «Are 2 and 1 equal? True␤Are 2 and 2 equal? False␤Are 4 and 1 equal? True␤Are 4 and 2 equal? True␤»\n=end code\n\nIn this case, we are coercing an L<C<Int>|/type/Int> to a L<C<Bool>|/type/Bool>, which is then printed (put\ninto a string context) in the C<for> loop that calls the function.\n\n=head1 sub MAIN\n\nDeclaring a C<sub MAIN> is not compulsory in Raku scripts, but you can\nprovide one to create a\nL<command line interface|/language/create-cli>\nfor your script.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/glossary.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"reference\")\n\n=TITLE Glossary\n\n=SUBTITLE Glossary of Raku terminology\n\n=head1 X<6model|Reference,6model>\n\nC<6model> is used in the L<MoarVM|/language/glossary#MoarVM>, and provides\nprimitives used to create an object system. It is described in\nL<this presentation by Jonathan Worthington|https://jnthn.net/papers/2013-yapceu-moarvm.pdf> and implemented\nL<here in MoarVM|https://github.com/MoarVM/MoarVM/tree/master/src/6model>.\n\n=head1 X<Abstract class|Reference,Abstract Class>\n\nThe generic Computer Science term \"abstract class\" defines the\nL<interface|#Interface> or L<API|#API> of a class. In Raku, this is\nimplemented using L<roles|#Roles> with L<stubbed|#Stub> methods.\n\n    role Canine {\n        method bark { ... }          # the ... indicates a stub\n    }\n\n    class Dog does Canine {\n        method bark { say \"woof\" }   # *MUST* be implemented by class\n    }\n\n\n=head1 X<Advent calendar|Reference,Advent Calendar>\n\nIn the context of Raku, a yearly set of blog posts for each day from\nthe 1st until the 25th of December, to be found at\nL<https://raku-advent.blog>.\n\n=head1 X<Adverb|Language,Adverb>\n\nGenerically, an adverb is a named argument to a function. There are\nalso some specific syntax forms that allow adverbs to be tucked into\nsome convenient places:\n\n=for code :preamble<my @h>\nq:w\"foo bar\";   # \":w\" is a Quotelike form modifier adverb\nm:g/a|b|c/;     # \":g\" is too\n@h{3}:exists;   # \":exists\" is too, but is known as a subscript adverb\n\nAdverbs are usually expressed with colon pair notation, and for this\nreason colon pair notation is also known as the adverbial pair form:\n\n    :a(4)          # Same as \"a\" => 4\n\nSome other forms that use a colon in ways that have adverb-like\nsemantics are called adverbial forms. One special form starts with an\ninteger value, followed by a name (for the key):\n\n    :20seconds     # same as seconds => 20\n\nAlso see L<Colon pair and colon list|#Colon pair and colon list>.\n\n=head1 X<Adverbial pair|Language,Adverbial Pair>\n\nA generalized form of C<pair notation>. They all start with the colon,\nas shown in the following examples:\n\n=begin table\n  adverbial pair            | pair notation\n  ==========================|==========================\n    :foo<hi hello>          | foo => <hi hello>\n    :foo('bar')             | foo => 'bar'\n    :foo(42)                | foo => 42\n    :42foo                  | foo => 42\n    :foo                    | foo => True\n    :!foo                   | foo => False\n    :$foo                   | foo => $foo\n=end table\n\nSimilarly to the angle brackets L«C«<…>»|/language/quoting#Word_quoting:_<_>» in the first line,\nother circumfix operators with their usual semantics can be used for stating the value,\ne.g. C<:foo[…]> for an array and C<:foo{…}> for a hash or even a L<C<Block>|/type/Block>.\nWith parentheses like in the second and third line, nearly all constructs can be used inside,\nnotably L<quoting constructs|/language/quoting> and L<regexes|/language/regexes>.\n\nAlso see the sections L<Adverb|#Adverb> and L<Colon pair and colon list|#Colon pair and colon list>.\n\n=head1 X<Anonymous|Reference,Anonymous>\n\nA subroutine, method or submethod is called I<anonymous> if it can't be\ncalled by name.\n\n    # named subroutine\n    sub double($x) { 2 * $x };\n\n    # anonymous subroutine, stored in a named scalar\n    my $double = sub ($x) { 2 * $x };\n\nNote that it is still allowed to have a name, but you cannot call it by\nthat name:\n\n=for code\n# anonymous, but knows its own name\nmy $s = anon sub triple($x) { 3 * $x }\nsay $s.name;        # OUTPUT: «triple␤»\n=for code :skip-test<illustrates error>\nsay triple(42);     # OUTPUT: «Undeclared routine: triple␤»\n\n\n=head1 X<API|Reference,API>\n\nApplication Programming Interface. Ideally, someone using your system or\nlibrary should be able to do so with knowledge only of the API, but not\nnecessarily knowing anything about the internals or the implementation details.\n\nSee also L<abstract class|#Abstract class>.\n\n=head1 X<Apocalypse|Reference,Apocalypse>\n\nA document originally written by L<TimToady|#TimToady>, in which he processed the\ninitial barrage of RFCs that came out of the Perl community. Now only kept\nas a historical document for reference. See also L<Exegesis|#Exegesis> and\nL<Synopsis|#Synopsis>.\n\n=head1 X<Arity|Reference,Arity>\n\nThe number of L<C<Positional>|/type/Positional> operands expected by an\nL<operator|#Operator>, subroutine, method or callable block.\n\n=begin code :preamble<class Foo {}>\nsub infix:<+>(Foo $a, Foo $b) { $a.Int + $b.Int }  # arity of \"+\" is 2\nsub frobnicate($x) { ... }                         # arity of 1\nsub the-answer() { 42 }                            # arity of 0\n-> $key, $value { ... }                            # arity of 2\n=end code\n\nThe arity of a L<C<Callable>|/type/Callable> is one of the main selectors in\nL<multi-dispatch|#Multi-dispatch>. Note that required named arguments, e.g. C<(:$foo!)>,\ncount as arity.\n\n=head1 X<ASCII operator|Language,ASCII operator>\n\nThe ASCII variant of a non-ASCII Unicode L<operator|#Operator> or\nL<symbol|#Symbol>.\nFor instance, C<(elem)> corresponds to the C<∈> (\"Is this an element of\nthat set?\") operator that comes from set theory. ASCII operators are a\nworkaround to the problem that people don't know how to type Unicode yet.\nCulturally, while we encourage people to use the Unicode symbols in a\nvague sort of way, we do not disparage the use of the\nL<ASCII variants|/language/unicode_ascii>.\nWell, maybe just a little...\n\n=head1 X<Autothreading|Language,Autothreading>\n\nAutothreading is what happens if you pass a L<C<Junction>|/type/Junction> to\na subroutine that expects a parameter of type L<C<Any>|/type/Any> or a subtype\nthereof (such as anything L<C<Cool>|/type/Cool>). The call is then executed for\neach value of the junction. The result of these calls is assembled in a new\njunction of the same type as the original junction.\n\n    sub f($x) { 2 * $x };\n    say f(1|2|3) == 4;    # OUTPUT: «any(False, True, False)␤»\n\nHere C<f()> is a sub with one parameter, and since it has no explicit type,\nit is implicitly typed as L<C<Any>|/type/Any>. The L<C<Junction>|/type/Junction> argument causes the\nC<f(1|2|3)> call to be internally executed as C<f(1)|f(2)|f(3)>, and the\nresulting junction is C<2|4|6>. These are then all compared to C<4>,\nresulting in a junction C<False|True|False>. This process of separating\njunction arguments into multiple calls to a function is called\nI<autothreading>.\n\nIf you use the resulting junction in a Boolean context, such as with an\nC<if>, it collapses into a single Boolean which is C<True> if any of the\nvalues in the junction are True.\n\n=for code :preamble<sub f {};>\nif f(1|2|3) == 4 {    # fires because f(2) == 4 is true\n    say 'success';\n}\n\n=head1 X<Backtracking|Reference,Backtracking>\n\nBacktracking is the default way a regexp is matched. The engine\nis allowed to explore several ways moving backward in the string\ncharacters in order to allow every piece of a regexp\nto match something.\nFor more information, see\nL<Regexp Backtracking section|/language/regexes#Backtracking>.\n\n=head1 X<binder|Reference,binder>\n\nWhen you pass an argument list to a function (or any other callable,\nlike a method or a block), the argument list gets bound to the\nparameters in the signature. The code that does this is called the\nI<binder>.\n\n=head1 X<block|Reference,block>\n\nL<Blocks|/type/Block> are code object with its own lexical scope, which\nallows them to define variables without interfering with other in the\ncontaining block.\n\n=head1 X<bytecode|Reference,bytecode>\n\nAlthough Raku looks like an interpreted language, since it uses the\nC<#!> form to run its scripts (and they are called I<scripts>), it is\nactually\nL<compiled to run in a virtual machine|https://www.reddit.com/r/perl6/comments/42dkme/perl6_not_being_an_interpreted_language/>\nso the compiler (currently Rakudo) generates\nL<bytecode|https://en.wikipedia.org/wiki/Bytecode> that runs either in\nMoarVM or the Java Virtual Machine, the two VMs currently supported.\n\n=head1 X<Camelia|Reference,Camelia>\n\nA butterfly image intended primarily to represent Raku, The Language.\n\n=head1 X<Colon pair and colon list|Reference,Colon Pair>\n\nX<|Reference,Colon List>\nA colon pair is a shorthand syntax used to create or visually present\na L<C<Pair>|/type/Pair> object. The two most common forms are:\n\n    :a(4)          # Same as \"a\" => 4,   same as Pair.new(\"a\", 4)\n    :a<4>          # Same as \"a\" => \"4\", same as Pair.new(\"a\", val(\"4\"))\n\nThis is also known as the adverbial pair form.\n\nB<Note>: when the part after the colon and before the balanced delimiters is\nnot a legal identifier, other semantics apply, not all of which produce\nL<C<Pair>|/type/Pair> objects.\n\nTwo other common forms are:\n\n    :a             # Same as :a(True)\n    :!a            # Same as :a(False)\n\nA colon list just means that a list that contains only colon pairs,\ndoes not need commas, or even spaces:\n\n    :a(4):c:!d:c   # Same as a => 4, c => True, d => False, c => True\n\nFinally, if there is a variable with the same name as an intended adverbial\npair, you don't have to specify the name twice, but just specify the adverb\nwith the appropriate sigil:\n\n=begin table\n    variable only | same as\n  ================|==============\n    :$foo         | foo => $foo\n    :@bar         | bar => @bar\n    :%mapper      | mapper => %mapper\n    :&test        | test => &test\n=end table\n\nSee also L<Adverb|#Adverb>.\n\n\n=head1 X<Community|Reference,Community>\n\nSee L<https://raku.org/community/> for information about how to participate\nin the friendly Raku community.\n\n=head1 X<Compilation unit or I<compunit>|Reference,compunit (glossary)>\n\nX<|Reference,compilation unit>\nA L<compunit|https://github.com/rakudo/rakudo/blob/master/docs/module_management.md>\nis a piece of Raku code that is analyzed and compiled as a single unit.\nTypically, this piece of code will be contained in a single file, but code\ninside an L<EVAL|/routine/EVAL> is also considered a compunit.\n\n=head1 X<Damian Conway|Reference,Damian Conway>\n\nOriginal author of the L<Exegesis|#Exegesis> (among many other things).\nSee also L<https://en.wikipedia.org/wiki/Damian_Conway>.\n\n=head1 X<decont|Reference,decont>\n\nShort for \"decontainerize\", meaning to remove an item\nL<from its C«Scalar» container|/language/containers>, often to obtain\nL<a different behavior|https://perl6advent.wordpress.com/2017/12/02/#theoneandonly>\nfor items that have it.\n\n=head1 X<diffy|Reference,diffy>\n\nSee L<operator|#Operator>. It means the type of the operator result is\nsufficiently different from its arguments that op= makes little sense.\n\n=head1 X<ecosystem|Reference,ecosystem>\n\nThe module ecosystem consists of all the published modules available for Raku, which\ncan be searched at L<Raku Land|https://raku.land/>. Note that different ecosystems\nbased on different technologies exist, but this typically refers to the C<fez>\necosystem.\n\n=head1 X<Exegesis|Reference,Exegesis>\n\nA document originally written by L<TheDamian|#TheDamian>, in which he tried to explain\nthe L<Apocalypses|#Apocalypse> to the common (wo)man. Now only kept as a\nhistorical document for reference. See also L<Synopsis|#Synopsis>.\n\n=head1 X<fiddly|Reference,fiddly>\n\nToo complicated to apply a metaop to. See L<operator|#Operator>.\n\n=head1 X<Forward declarations|Reference,forward declaration>\n\nDeclare the scope and/or type of a functional entity (class or routine)\nwithout actually declaring its code by using\nthe L<\"stub\" operator|/language/operators#listop_...>; code\nwill be declared later on in the same file.\n\n=for code\ngrammar Quux {\n    my regex future {...};\n    say \"foobarbaz\" ~~ /<future>/;\n    regex future { f \\w** 2 b \\w ** 2 }\n}\n\nIn this case, the regex acts as a method; please note that the scope is only\ndeclared once.\n\n=head1 X<gradual typing|Reference,gradual typing>\n\nYou don't have to specify types of variables and parameters, but if you do,\nit helps in early determination of impossible dispatches and better\noptimization. See also L<https://en.wikipedia.org/wiki/Gradual_typing>.\n\n=head1 X<Handle|Reference,Handle>\n\nA handle is a data structure used to store information about some\ninput/output operation such as file or socket reading or writing. Raku\nuses L<C<IO::Handle>|/type/IO::Handle> as a base class for filehandles,\nand L<C<IO::Socket>|/type/IO::Socket> for sockets.\n\n=head1 X<Huffmanize|Reference,Huffmanize>\n\nWith reference to L<Huffman coding|https://en.wikipedia.org/wiki/Huffman_coding>,\n\"huffmanizing\" is making things that are commonly used easier, and often shorter,\nto type. With things that are used less frequently it's both less of a bother\nto type longer pieces of code and often longer, more descriptive naming\nis necessary to easily be reminded of what the rarely-used feature does.\n\nFor example, printing output is a common task, while performing\nthread-safe atomic addition on native atomicity-safe integers is much less so.\nThere's a need to \"huffmanize\" the task printing and that's why you can do it\nby just typing three letters L<put|/routine/put>. But there's no need to\n\"huffmanize\" the rarely-needed atomic operators, which is why you type the\nlengthier names, such as L<atomic-inc-fetch|/routine/atomic-inc-fetch>. The\nname L<put|/routine/put> is a bit vague, but because\nit's commonly used, it's easy to learn what it does. On the other hand,\nthe name L<atomic-inc-fetch|/routine/atomic-inc-fetch> is rarer,\nand the more descriptive name helps recall its purpose better.\n\n=head1 X<iffy|Reference,iffy>\n\nOften used as a Boolean value. See L<operator|#Operator>. Made via\nthe L<C<use> keyword|/language/using-modules/code#use>.\n\n=head1 X<import|Reference,import>\n\nInclude functions from a module in the current namespace.\n\n=head1 X<infix stopper|Reference,infix>\n\nAn I<infix stopper> is something that tells us the grammar not try to parse\nan infix at that point. Consider say C<\"abc42def\" ~~ m|\\d+|>. Ordinarily,\na C<|> in a regex is treated as an alternation, but since the infix stopper\nmatches the current regex terminator, we don't continue and try to parse an\ninfix at that point. The C<|> is thus treated as the end of the regex.\n\n=head1 X<Instance|Reference,instance>\n\nAn I<instance> of a class is also called an I<object> in some other\nprogramming languages. It has storage for attributes and is often the return\nvalue of a call to a method called C<new>, or a literal.\n\nInstances of most types are defined to be C<True> e.g.,\nC<defined($instance)> is C<True>.\n\n    my Str $str = \"hello\";  ## this is with built-in types, e.g. Str\n    if defined($str) {\n        say \"Oh, yeah. I'm defined.\";\n    }\n    else {\n        say \"No. Something off? \";\n    }\n\n    ## if you wanted objects...\n    class A {\n        # nothing here for now.\n    }\n\n    my $an_instance = A.new;\n    say $an_instance.defined.raku;# defined($an_instance) works too.\n\nTo put things another way, a class contains the blueprints of methods\nand attributes, and an instance carries it into the real world.\n\n=head1 X<Interface|Reference,Interface>\n\nAn interface is an L<abstract class|#Abstract class>.\n\n=head1 X<Invocant|Reference,Invocant>\n\nCaller, I<the one who calls or invokes>. The invocant of a method would\nbe the object on which that method is being called, or, in some cases,\nthe class itself. I<Invocant> is used instead of caller because the\nlatter refers to the I<scope>.\n\n=head1 X<IRC|Reference,IRC>\n\nInternet Relay Chat. Raku developers and users usually hang out on\nthe C<#raku> channel of C<irc.libera.chat>. This channel is also\npopulated by a host of friendly bots that allow you to interact with\nRaku and its codebase, as well as send delayed messages and other\ngoodies. Check the full list in\nL<the community page of raku.org|https://raku.org/community>.\n\n=head1 X<IRC lingo|Reference,IRC lingo>\n\nThe following terms are often used on the Raku related L<IRC|#IRC>\nchannels:\n\n=head2 X<ALAP|Reference,ALAP>\n\nAs Late As Possible\n\n=head2 X<backlog|Reference,backlog>\n\nThat part of a discussion on an L<IRC|#IRC> channel that you've missed. If it is\nno longer available in your IRC client, you can check L<the logs|https://irclogs.raku.org>.\n\n=head2 X<Bot|Reference,Bot>\n\nA program that does automatic tasks on one or more L<IRC|#IRC> channels by\nacting like a regular user (as far as the IRC server is concerned) and\nperforming some tasks that may involve answering to users requests.\nExamples can be found L<on the IRC page of raku.org|https://raku.org/community/irc>.\n\n=head2 X<DWIM|Reference,DWIM>\n\nI<Do What I Mean>. A programming language designer motto.\nThe opposite of a DWIM is a L<WAT|#WAT>.\n\n=head2 X<flap|Reference,flap>\n\nSometimes a test will fail under some conditions, but not others; when this\ntest passes in some test runs and fails in others, it's called flapping.\n\n=head2 X<fossil|Reference,fossil>\n\nSomething in a generally current document that is no longer true but which\nhas not yet been fixed by correcting or removing it.\n\n=head2 X<FSVO|Reference,FSVO>\n\nFor Some Value Of...\n\n=head2 X<FTFY|Reference,FTFY>\n\nFixed That For You\n\n=head2 X<IIRC|Reference,IIRC>\n\nIf I Read (or Remember) Correctly.\n\n=head2 X<IMHO|Reference,IMHO>\n\nIn My Humble Opinion.\n\n=head2 X<IWBN|Reference,IWBN>\n\nIt Would Be Nice\n\n=head2 X<LHF|Reference,LHF>\n\nLow Hanging Fruit. Usually used in the context of a (relatively) simple\ntask to be performed by a (relative) newbie.\n\n=head2 X<LGTM|Reference,LGTM>\n\nLooks Good To Me\n\n=head2 X<LTA|Reference,LTA>\n\nLess Than Awesome. Usually used in the context of an error message that\nis rather non-descriptive or unrelated to the actual error.\n\n=head2 X<Opt|Reference,Opt>\n\nShort for \"optimization\", usually in either the context of\nL<spesh|#Spesh> or JIT.\n\n=head2 X<PR|Reference,PR>\n\nSee L<Pull request|#Pull request>.\n\n=head2 X<P5|Reference,P5>\n\nPerl 5\n\n=head2 X<RSN|Reference,RSN>\n\nReal Soon Now.\n\n=head2 X<TIMTOWTDI|Reference,TIMTOWTDI>\n\nAn alternative form of L<TIMTOWTDI|#TMTOWTDI>, explicitly including the \"is\" from\nthe contraction \"There's\".\n\n=head2 X<TMI|Reference,TMI>\n\nToo Much Information.\n\n=head2 X<TMTOWTDI|Reference,TMTOWTDI>\n\n\"There's More Than One Way To Do It\", the Perl motto.\n\n=head2 X<UGT|Reference,UGT>\n\n\"Universal Greeting Time\" - i.e., it's always \"morning\".\n\n=head2 X<WFM|Reference,WFM>\n\nWorks For Me\n\n=head2 X<WIP|Reference,WIP>\n\nWork In Progress\n\n=head2 X<WW|Reference,WW>\n\nShort for C<wrong window>. When on L<IRC|#IRC>, someone types something in\na channel that was intended for another channel, or for a private\nmessage.\n\n=head1 X<Larry Wall|Reference,Larry Wall>\n\nL<Perl's|#Perl> benevolent dictator for life, among many other things.\nSee also L<https://en.wikipedia.org/wiki/Larry_Wall>.\n\n=head1 X<Lexing|Reference,Lexing>\n\nPerforming L<lexical analysis|https://en.wikipedia.org/wiki/Lexical_analysis>,\na step which usually precedes parsing.\n\n=head1 X<LHS|Reference,LHS>\n\nX<|Reference,Left-hand side>\nAs an acronym left-hand side, it usually refers to the left-hand side of\nan expression, and more specifically to the left-hand side of\nexpressions such as C<$lhs = \"this would be the right-hand side\">. Since\nthe left-hand side of these expressions modify their value, when\nsomething behaves as a LHS it means that it can be read and written to.\nSee also L<Sides of an equation|https://en.wikipedia.org/wiki/Sides_of_an_equation>.\n\n=head1 X<Literal|Reference,Literal>\n\nA I<literal> is a piece of code that directly stands for an (often built-in)\nobject and also refers to the object itself.\n\n    my $x = 2;      # the 2 is a literal\n    say $x;         # $x is not a literal, but a variable\n    my $s = \"Foo\";  # the \"Foo\" is a literal, the $s is a variable\n\nDifferent types of literals are described in\nL<the syntax document|/language/syntax#Literals>.\n\n=head1 X<lvalue|Reference,lvalue>\n\nAn I<lvalue>, or a I<left value>, is anything that can appear on the\nleft-hand side of the assignment operator C<=>. It is anything you\ncan assign to.\n\nTypical lvalues are variables, private and C<is rw> attributes, lists of\nvariables and lvalue subroutines.\n\nExamples of lvalues:\n\n=begin table\n    Declaration             lvalue          Comments\n\n    my $x;                  $x\n    my ($a, $b);            ($a, $b)\n    has $!attribute;        $!attribute     Only inside classes\n    has $.attrib is rw;     $.attrib\n    sub a is rw { $x };     a()\n=end table\n\nExamples of things that are not lvalues:\n\n=begin table\n    3                        literals\n    constant x = 3;          constants\n    has $.attrib;            attributes; you can only assign to $!attrib\n    sub f { }; f();          \"normal\" subs are not writable\n    sub f($x) { $x = 3 };    error - parameters are read-only by default\n=end table\n\nThese are typically called L<rvalues|#rvalue>.\n\n=head1 X<Mainline|Reference,Mainline>\n\nThe C<mainline> is the program text that is not part of any kind of block.\n\n=for code :solo\nuse v6.c;     # mainline\nsub f {\n              # not in mainline, in sub f\n}\nf();          # in mainline again\n\nYou can also have the mainline of any package-like declarator, such as\nclass, L<module|/language/using-modules/introduction>, L<grammar|/language/grammars>, etc.\nThese are typically run just after the class/module/grammar have been compiled\n(or when loaded from a precompiled file).\n\n=head1 X<Mayspec|Reference,Mayspec>\n\nStands for \"Maybe Specification\". Usually refers to existing tests in the\nL<language specification|https://github.com/Raku/roast/>. The speaker\nis indicating they did not check whether the test is a spectest or a propspec\ntest; i.e., whether the test is included in a released language specification\nor is a new test, proposed for the next version of the spec.\n\n=head1 X<MoarVM|Reference,MoarVM>\n\nMoarVM is short for Metamodel On A Runtime Virtual Machine.\nIt's a virtual machine designed specifically for L<NQP|#NQP> and\nits L<MOP|/language/mop>: L<6model|#6model>. A document about\nL<the purpose of MoarVM|https://github.com/MoarVM/MoarVM/blob/master/docs/reveal.md>.\nMoarVM has some similarities with the Hotspot VM so you may peruse its\nL<glossary|http://openjdk.java.net/groups/hotspot/docs/HotSpotGlossary.html>\nfor entries missing from the present one.\n\n=head1 X<Multi-dispatch|Reference,Multi-Dispatch>\n\nX<|Reference,MMD>\nThe mechanism used to invoke different routines (L<C<Method>|/type/Method>s or\nL<C<Sub>|/type/Sub>s) of the same name, selecting the correct one based on the\nL<C<Parameter>|/type/Parameter> prototype and the arguments it was called with.\n\nThe selection process is primarily based on types and number of arguments\n(L<arity|#Arity>), where the narrowest, most specific candidate wins,\ntypically without regard to the order of declaration. Note that required named\narguments, e.g. C<(:$foo!)>, count as arity. The C<is default> trait may be used as a\ntiebreaker in this first phase.  There is also a secondary phase where some\ndifferent tiebreakers may be evaluated in order of declaration of the\nmethods or subs.\n\n=head1 X<multi-method|Reference,multi-method>\n\nA L<method|/type/Method> that has multiple candidates going by the same name\nand are subject to L<Multi-Dispatch|#Multi-dispatch>.\n\n=head1 X<NFG|Reference,NFG>\n\nNormal Form Grapheme is the way Raku implements graphemes, using a normal form\nin which strings with the same graphemes can be easily compared in constant\ntime. More on that on L<these articles|https://raku.github.io/CCR/Remaster/Jonathan%20Worthington/This-week-Unicode-normalization-many-RTs.html> L<by Jonathan Worthington|https://raku.github.io/CCR/Remaster/Jonathan%20Worthington/This-week-digging-into-NFG-fixing-use-fatal-and-more.html>\nand a fun explanation of how NFG works in L<this IRC log|https://irclogs.raku.org/perl6/2018-04-29.html#16:57-0002>.\n\n=head1 X<Niecza|Reference,Niecza>\n\nAn implementation of Raku targeting the .NET platform. No longer actively\nmaintained.\n\n=head1 X<Not Quite Perl|Reference,NQP>\n\nSee L<NQP|#NQP>.\n\n=head1 X<NQP|Reference,Not Quite Perl>\n\nNQP is a primitive language for writing subroutines and methods using a\nsubset of the Raku syntax. It's not intended to be a full-fledged\nprogramming language, nor does it provide a runtime environment beyond\nthe basic VM primitives. Compilers (such as L<Rakudo|#Rakudo>) typically use\nNQP to compile action methods that convert a parse tree\ninto its equivalent abstract syntax tree representation.\n\n=head1 X<NYI|Reference,NYI>\n\nNot Yet Implemented\n\n=head1 X<opcode|Reference,opcode>\n\nAn opcode, or operation code, is a bytecode operation, that is, a command of\nthe language actually used on the virtual machine. They are not usually\nintended for human consumption, but they are usually specified somewhere,\nlike L<this document for MoarVM|https://github.com/MoarVM/MoarVM/blob/master/docs/bytecode.md>.\n\n=head1 X<Operator|Reference,Operator>\n\nAn expression is made of operators and operands. More precisely it is made\nof an operator and operands that can be subexpressions or L<value|#value>s.\nOperators are an alternative syntax for a L<multi-method|#multi-method>. With that\nsyntax, what would be the arguments of the function are named\noperands instead. Operators are classified into\nL<categories|https://github.com/Raku/old-design-docs/blob/master/S02-bits.pod#Grammatical_Categories> of\ncategories. A category has a precedence, an arity, and can be L<fiddly|#fiddly>,\nL<iffy|#iffy>, L<diffy|#diffy>. Raku is very creative as to what is an operator, so\nthere are many categories. Operators are made of many tokens, possibly with\na subexpression. For example, C<@a[0]> belongs to the postcircumfix\ncategory, is broken into the operand C<@a> and the postcircumfix operator\nC<[0]> where C<0> is the postcircumfixed subexpression.\n\nThe C«<O(I<...>)>» construction gives information about an operator\nthat completes the information provided by its category. Below\nC<%conditional> is the category, C«:reducecheck<ternary>», which\nspecifies calling C<.ternary> to post-process the L<parse subtree|#Parse_tree>\nand C«:pasttype<if>» specifies the NQP L<opcode|#opcode> generated in the\nAST from the parse subtree.\n\n        <O('%conditional, :reducecheck<ternary>, :pasttype<if>')>\n\n=head1 X<Parameter|Reference,Parameter>\n\nL<C<Parameter>|/type/Parameter> is a class to define parameters to\nL<C<Sub>|/type/Sub>routines, L<C<Method>|/type/Method>s and L<C<Callable>|/type/Callable> blocks.\nAs opposed to the arguments you specify when calling a\nsubroutine/method/callable block.\n\n    sub foo($bar) { say $bar }     # $bar is a parameter\n    foo(42);                       # 42 is an argument\n\n=head1 X<Parrot|Reference,Parrot>\n\nA L<virtual machine|#Virtual_machine> designed to run Raku and other\ndynamic languages. No longer maintained.\n\n=head1 X<Parse tree|Reference,Parse Tree>\n\nA L<parse tree|https://en.wikipedia.org/wiki/Parse_tree> represents the\nstructure of a string or sentence according to a grammar.\nL<C<Grammar>|/type/Grammar>s in Raku output parse trees when they successfully\nmatch a string.\n\n=head1 X<PAST|Reference,PAST>\n\nL<Parrot|#Parrot> AST.\n\n=head1 X<Perl|Reference,Perl>\n\nThe Perl programming language.\n\n=head1 X<Perl 6|Reference,Perl 6>\n\nThe name used for Raku before October 2019.\n\n=head1 X<POD|Reference,POD>\n\nB<P>lain B<O>l' B<D>ocumentation, a documentation format understood by\nRaku. See L<here|/language/pod> for further information.\n\n=head1 X<POV|Reference,POV>\n\nStands for \"Proof Of Viability\". To be included in the language specification,\na \"proof of viability\" implementation of the feature must exist in at least one\nmostly-compliant Raku compiler.\n\n=head1 X<priming|Reference,priming>\n\nPriming (sometimes called L<partial function\napplication|https://en.wikipedia.org/wiki/Partial_application> in other\nprogramming languages) is the act of creating a new function by providing some\nbut not all of the arguments to an existing function.  For example, to create a\nfunction that takes one argument and adds 42 to it, you could prime the addition\noperator with C<42> as a single argument: C<* + 42>.  See\nL<Whatever-priming|/type/Whatever> and L<assuming|/type/Code#method_assuming>.\n\n=head1 X<property|Reference,property>\n\nIn this context, it either refers to an\nL<object property|/language/objects#index-entry-Property-property>,\nwhich is the value of an instance variable, or a\nL<Unicode property|/language/regexes#Unicode_properties>\nwhich are codepoint features that\nallow programs to identify what kind of entity they represent, that is, if they\nare a letter, or a number, or something completely different like a control\ncharacter.\n\n=head1 X<Propspec|Reference,Propspec>\n\nStands for \"Proposed Specification\". Usually refers to existing tests in the\nL<language specification|https://github.com/Raku/roast/> that are proposed\nfor inclusion in the next release.\n\n=head1 X<pugs|Reference,pugs>\n\nL<pugs|https://en.wikipedia.org/wiki/Pugs> was one of the first\ninterpreters/compilers written for Raku. It was written in Haskell\nby Audrey Tang.\n\n=head1 X<Pull request|Reference,Pull request>\n\nA feature of L<GitHub|https://github.com> and other git hosts like\nL<GitLab|https://gitlab.com> that allows you to make patches to be\neasily applied using the GitHub web user interface. It means you request\nsomeone to do a git pull from your L<repository|#Repository> to hers. PR\nis its usual acronym.\n\n=head1 X<QAST|Reference,QAST>\n\nSuccessor to L<PAST|#PAST> ('Q' being the next letter after 'P').\n\n=head1 X<Rakudo|Reference,Rakudo>\n\nRakudo is the name of a Raku implementation that runs on L<MoarVM|#MoarVM> and\nthe JVM. It is an abbreviation of C<Rakuda-do>, which, when translated\nfrom Japanese, means \"The Way of the Camel\". Also, in Japanese, \"Rakudo\"\nmeans \"Paradise.\"\n\n=head1 X<Reify|Reference,Reify>\n\nIn the English language, L<reify means|https://www.dictionary.com/browse/reify>\n\"to convert into or regard as a concrete thing.\" Its meaning in Raku is very\nsimilar, in that conceptual things, like \"elements of an infinite list\", get\nI<reified> when you try to operate on some of them. In general, reification\nmeans turning a potential element (be it an element in a lazy list that has not\nbeen computed yet or an element in a container that has not been extracted) into\nits actual value.\n\n=head1 X<Repository|Reference,Repository>\n\nA filesystem under control of a source control management application,\nusually git, that holds the sources for a project, library or\napplication. This file, for instance, is in\nL<a GitHub repository|https://github.com/Raku/doc>. Repositories store not only\nfiles, but also history of changes and can be used by the developing or\nwriting team for interaction through issues or comments to code.\n\nIn Raku context, however, a repository is also a short name for\nI<compilation unit repository> and constitutes a system that locates and\nloads modules, managing their installation and precompilation. They are\nstructured as linked lists, including chain of repositories ending in\nthe default C<Compunit::Repository::Installation>.\n\n=head1 X<RHS|Reference,RHS>\n\nX<|Reference,Right-hand side>\nAcronym for right-hand side, usually refers to the right-hand side of\nassignment operators and expressions such as C<my $bound := $rhs> or\nC<my $a = 5; $a //= $rhs>. See\nalso L<Sides of an equation|https://en.wikipedia.org/wiki/Sides_of_an_equation>.\n\n=head1 X<roast|Reference,roast>\n\nThe Raku L<specification tests|#Test suite>, which live here:\nL<https://github.com/Raku/roast/>. Originally developed for L<pugs|#pugs>,\nit now serves all Raku implementations. Why roast? It's the\nB<r>epository B<o>f B<a>ll B<s>pec B<t>ests.\n\n=head1 X<Roles|Reference,role>\n\nRoles, mix-ins or traits define interfaces and/or implementation of\nthose interfaces as well as instance variables using them, and are\nmixed-in when declaring classes that follow that interface. L<Abstract\nclasses|#Abstract_class> are particular examples of Roles where the\nactual implementation is deferred to the class that uses that Role.\n\nRoles are part of Raku's L<object system|/language/objects>, and are\ndeclared using the\nL<role|/language/objects#index-entry-role_declaration-role> keyword and\nused in class declaration via L<does|/routine/does>.\n\n=head1 X<rvalue|Reference,rvalue>\n\nA value that can be used on the right-hand side of an assignment. See also\nL<lvalue|#lvalue>.\n\n=head1 X<SAP|Reference,SAP>\n\nStands for \"Specification APpendices\". The\nL<SAP|https://github.com/Raku/roast/tree/master/APPENDICES> includes\noptional tests that implementations may choose to follow, but don't\nnecessarily have to.\n\nCan be used as a verb. To I<SAP> something is to place it into Specification\nAppendices.\n\n=head1 X<Semilist|Reference,Semilist>\n\nA semilist is a I<semicolon-separated> list like this one: C<1;3;5>, and\nis actually a list of lists, with each component of the semilist being a\nslice of a particular dimension. C<@array[1;3;5]> would be equivalent to\nC<@array[1][3][5]>.\n\n=head1 X<Sigil|Reference,Sigil>\n\nThe sigil is the first character of a variable name. It must\nbe either $, @, %, or & respectively for a L<C<Scalar>|/type/Scalar>,\nL<C<Array>|/type/Array>, L<C<Hash>|/type/Hash>, or L<C<Code>|/type/Code>\nvariable. See also Twigil and role. Also sigiled variables allow short\nconventions for L<variable interpolation|#Variable_interpolation> in a\ndouble quoted string, or even postcircumfix expressions starting with\nsuch a variable.\n\n=head1 X<Sigilless variable|Reference,Sigilless Variable>\n\nL<Sigilless variables|/language/variables#index-entry-\\_(sigilless_variables)>\nare actually aliases to the value it is assigned to them, since they are not\ncontainers. Once you assign a sigilless variable (using the escape\nC<\\>), its value cannot be changed.\n\n=head1 X<Spesh|Reference,Spesh>\n\nA functionality of the L<MoarVM|#MoarVM> platform that uses runtime gathered\ndata to improve commonly used pieces of L<bytecode|#bytecode>. It is much like a\nJIT compiler, except that those usually output machine code rather than\nbytecode.\n\n=head1 X<STD|Reference,STD>\n\nC<STD.pm> is the \"standard\" Raku grammar definition (see\nL<https://github.com/perl6/std/>) that was used to implement Raku.\nSTD.pm is no longer really a \"specification\" in a proscriptive sense:\nit's more of a guideline or model for Raku implementations to follow.\n\n=head1 X<Stub|Reference,Stub>\n\nStubs define name and signature of methods whose implementation is\ndeferred to other classes.\n\n    role Canine {\n        method bark { ... }          # the ... indicates a stub\n    }\n\nClasses with stubs are L<Abstract classes|#Abstract class>.\n\n=head1 X<Symbol|Reference,Symbol>\n\nFancy alternative way to denote a name. Generally used in the context of\nL<module|/language/using-modules/introduction>s linking, be it in the OS level, or at the\nRaku L<virtual machine|#Virtual_machine> level for modules generated from languages\ntargeting these VMs. The set of imported or exported symbols is called\nthe symbol table.\n\n=head1 X<Synopsis|Reference,Synopsis>\n\nThe current human-readable description of the Raku language. Still in\ndevelopment. Much more a community effort than the\nL<Apocalypses|#Apocalypse> and L<Exegeses|#Exegesis> were. The current\nstate of the language is reflected by L<roast|#roast>, its L<test suite|#Test suite>, not\nthe synopses where speculative material is not always so flagged or more\nrecent additions have not been documented. This is even more true of\nmaterial that has not been yet implemented.\n\n=head1 X<Syntax analysis|Reference,Syntax Analysis>\n\nA syntax or syntactic analysis is equivalent to\nL<parsing|https://en.wikipedia.org/wiki/Parsing> a string to generate its\nL<parse tree|#Parse_tree>.\n\n=head1 X<Test suite|Reference,test suite>\n\nThe Raku test suite is L<roast|#roast>.\n\n=head1 X<TheDamian|Reference,TheDamian>\n\nL<IRC|#IRC> screen name for L<Damian Conway|#Damian Conway>, writer of the original\nL<Exegeses|#Exegesis>.\n\n=head1 X<Thunk|Reference,Thunk>\n\nA piece of code that isn't immediately executed, but doesn't have an independent\nscope.\n\n=head1 X<Tight and loose precedence|Reference,Tight>\n\nX<|Reference,Loose>\nIn this context, tight or tighter refers to\nL<precedence rules|/language/functions#Precedence>\nand is the opposite of C<looser>. Precedence rules for new terms are\nalways expressed in relationship with other terms, so C<is tighter>\nimplies that operands with that operator will be grouped before operands\nwith the looser operator. Operators with\nL<tight precedence|/language/operators#Tight_AND_precedence>\nare grouped with priority to others and are generally tighter than most\nothers; loose\nL<exactly the opposite|/language/traps#Loose_Boolean_operators>,\nso it is always convenient to be aware of the exact precedence of all\noperators used in an expression.\n\n=head1 X<TimToady|Reference,TimToady>\n\nL<IRC|#IRC> screen name for L<Larry Wall|#Larry Wall>, creator of Perl. The name comes from\nthe pronunciation of L<TIMTOWTDI|#TIMTOWTDI> as a word.\n\n\n=head1 X<token|Reference,Token>\n\nIn this context, a L<C<token>|/syntax/token> is a regex that does not backtrack.\nIn general, L<tokens|https://en.wikipedia.org/wiki/Lexical_analysis> are\nextracted from the source program while L<lexing|#Lexing>.\n\n=head1 X<Truthy and Falsy|Reference,Truthy>\n\nX<|Reference,Falsy>\nA value is \"truthy\" if it evaluates to C<True> in Boolean context and \"falsy\"\nif it evaluates to C<False>.\n\nFor example, a non-empty string is considered C<True> and an empty string\nC<False>:\n\n=begin code\nsay so \"\";                    # OUTPUT: «False␤»\nsay so \"non-empty\";           # OUTPUT: «True␤»\n\nsay \"truthy\" if \"non-empty\";  # OUTPUT: «truthy␤»\n=end code\n\nwhile L«C<Numeric>|/type/Numeric»s are considered C<True> when non-zero:\n\n=begin code\nsay so  0;                    # OUTPUT: «False␤»\nsay so  1;                    # OUTPUT: «True␤»\nsay so -1;                    # OUTPUT: «True␤»\n\nsay \"truthy\" if -1;           # OUTPUT: «truthy␤»\nsay 0 || \"falsy\";             # OUTPUT: «falsy␤»\n=end code\n\n=head1 X<twine|Reference,twine>\n\nA data structure used to hold a POD string with embedded formatting\ncodes. For example:\n\n=begin code\n=begin pod\nC<foo>\n=end pod\nsay $=pod[0].contents[0].contents.raku;\n=end code\n\nThe output will be:\n\n=begin code\n[\"\", Pod::FormattingCode.new(type => \"C\", meta => [], config => {}, contents => [\"foo\"]),\"\"]\n=end code\n\nThe C<twine> is an array with an odd number of elements beginning\nwith a simple string, alternating with formatting code objects and\nsimple strings, and ending with a simple string; the formatting code\nobjects are interC<twine>d with the strings. The strings may be empty\n(as shown in the example). A twine with no formatting code will contain\none simple string.\n\n=head1 X<Type objects|Reference,Type Objects>\n\nA\nL<type object|/language/classtut#A_word_on_types>\nis an object that is used to represent a type or a class. Since in\nobject oriented programming everything is an object, classes are\nobjects too, and they inherit from L<C<Mu>|/type/Mu>.\n\n=head1 X<Type smiley|Reference,Type Smiley>\n\nA\nL<type smiley|/language/signatures#Constraining_argument_definiteness>\nis a suffix a type may have that indicates the definiteness of values\nthat can typecheck against it. This may be C<:D> to indicate that only\ndefined values can typecheck (i.e. instances), C<:U> to indicate that only\nundefined values can typecheck (i.e. type objects), or C<:_> to indicate\nthat both defined and undefined values can typecheck. These resemble\nemoticons, thus the name.\n\n=head1 X<UB|Reference,UB>\n\nStands for \"Undefined Behavior\". In other words, it is something that\nis not explicitly specified by the language specification.\n\n=head1 X<value|Reference,value>\n\nA value is what is actually contained in a container such as a variable.\nUsed in expressions such as L<lvalue|/language/glossary#lvalue>, to\nindicate that that particular container can be assigned to.\n\n=head1 X<Value type|Reference,Value type>\n\nA type is known as a B<value type> if it is immutable and any instance\nof that type is interchangeable with any other instance \"of the same\nvalue\"—that is, any instance constructed in the same way. An instance of\na value type is often I<called> a B<value> (but should not be confused\nwith L<lvalue|#lvalue>s or L<rvalue|#rvalue>s).\n\nFor example, numbers are value types, so a number constructed one place\nin your program with, for instance, the literal C<3> can't be changed in\nany way—it simply I<is> 3—and any later use of the literal C<3> can\nsafely be pointed at the same place in memory as the first with no ill\nconsequences.\n\nClasses doing the roles L<C<Numeric>|/type/Numeric> and\nL<C<Stringy>|/type/Stringy> are among a few examples of built-in value\ntypes.\n\nA value type is created by ensuring that an instance of the value type\nis immutable (i.e., its attributes cannot be modified after\nconstruction) and that its L«C<WHICH>|/routine/WHICH» method returns the\nsame thing every time an instance with the same value is constructed\n(and conversely returns a different thing every time an instance with a\ndifferent value is constructed).\n\nThe language is free to optimize based on the assumption that equivalent\ninstances of value types are interchangeable, but you should not depend\non any such optimization. For instance, if you want\nL«C<clone>|/routine/clone» to return an instance of C<self>, or you want\ninstance construction to be\nL<memoized|https://en.wikipedia.org/wiki/Memoization> so that\nre-construction of a previously-constructed value always returns the\nsame instance, you currently must override this behavior yourself.\n\n(The same would hold true of object finalization, but if your instances\nneed special destruction behavior, you almost certainly do not actually\nhave a value type. Values should be thought of as \"timeless\" and\nexisting in some ideal form outside of your program's memory, like\nnatural values are.)\n\n=head1 X<Variable|Reference,Variable>\n\nA variable is a name for a L<container|/language/containers>.\n\n=head1 X<Variable interpolation|Reference,Variable Interpolation>\n\nThe value of variables is interpolated into strings by simply inserting\nthat variable into the string:\n\n    my $polation=\"polation\";\n    say \"inter$polation\";     # OUTPUT: «interpolation␤»\n\nThis might need curly braces in case it precedes some alphanumeric\ncharacters\n\n    my $inter=\"inter\";\n    say \"{$inter}polation\"; # OUTPUT: «interpolation␤»\n\nInterpolation occurs in L<string context|/language/contexts#String>, so\na valid stringification method must exist for the class. More general\ninterpolation can be achieved using the\nL<double q|/language/quoting#Interpolation:_qq> quoting constructs.\n\n=head1 X<Virtual machine|Reference,Virtual Machine>\n\nA virtual machine is the Raku compiler entity that executes the\nL<bytecode|#bytecode>. It can optimize the bytecode or generate machine code\nJust in Time. Examples are L<MoarVM|#MoarVM>, L<Parrot|#Parrot> (who are intended to run\nRaku) and more generic virtual machines such as JVM and Javascript.\n\n=head1 X<WAT|Reference,WAT>\n\nThe opposite of a L<DWIM|#DWIM>; counter-intuitive behavior. It is said\nthat to every DWIM there is a corresponding WAT.\nSee also L<https://www.destroyallsoftware.com/talks/wat>.\n\n=head1 X<whitespace|Reference,whitespace>\n\nA character or group of blank characters, used to separate words. An\nexample is the space character « ».\n\n=head1 X<zef|Reference,zef>\n\nL<zef|https://github.com/ugexe/zef> is a tool to manage Raku module installation.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/grammar_tutorial.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"tutorial\")\n\n=TITLE Grammar tutorial\n\n=SUBTITLE An introduction to grammars\n\n=head1 Before we start\n\n=head2 Why grammars?\n\nGrammars parse strings and return data structures from those strings.\nGrammars can be used to prepare a program for execution, to determine\nif a program can run at all (if it's a valid program), to break down\na web page into constituent parts, or to identify the different parts\nof a sentence, among other things.\n\n=head2 When would I use grammars?\n\nIf you have strings to tame or interpret, grammars provide the tools\nto do the job.\n\nThe string could be a file that you're looking to break into sections;\nperhaps a protocol, like SMTP, where you need to specify which \"commands\"\ncome after what user-supplied data; maybe you're designing your own\ndomain specific language. Grammars can help.\n\n=head2 The broad concept of grammars\n\nRegular expressions (L<Regexes|/language/regexes>) work well for finding\npatterns in strings. However, for some tasks, like finding multiple patterns\nat once, or combining patterns, or testing for patterns that may surround\nstrings regular expressions, alone, are not enough.\n\nWhen working with HTML, you could define a grammar to recognize HTML tags, both\nthe opening and closing elements, and the text in between. You could then\norganize these elements into data structures, such as arrays or hashes.\n\n=head1 Getting more technical\n\n=head2 The conceptual overview\n\nGrammars are a special kind of class. You declare and define a grammar exactly\nas you would any other class, except that you use the I<grammar> keyword instead\nof I<class>.\n\n=begin code :skip-test<incomplete code>\ngrammar G { ... }\n=end code\n\nAs such classes, grammars are made up of methods that define a regex, a token,\nor a rule. These are all varieties of different types of match methods. Once you\nhave a grammar defined, you call it and pass in a string for parsing.\n\n=begin code :preamble<grammar G{};my $string;>\nmy $matchObject = G.parse($string);\n=end code\n\nNow, you may be wondering, if I have all these regexes defined that just return\ntheir results, how does that help with parsing strings that may be ahead\nor backwards in another string, or things that need to be combined from many of\nthose regexes... And that's where grammar actions come in.\n\nFor every \"method\" you match in your grammar, you get an action you can use\nto act on that match. You also get an overarching action that you can use to\ntie together all your matches and to build a data structure. This overarching\nmethod is called C<TOP> by default.\n\n=head2 The technical overview\n\nAs already mentioned, grammars are declared using the I<grammar> keyword and its\n\"methods\" are declared with I<regex>, or I<token>, or I<rule>.\n\n=item Regex methods are slow but thorough, they will look back in the string\nand really try.\n\n=item Token methods are faster than regex methods and ignore\nwhitespace. Token methods don't backtrack; they give up after the first\npossible match.\n\n=item Rule methods are the same as token methods except whitespace\nis not ignored.\n\nWhen a method (regex, token or rule) matches in the grammar, the string matched\nis put into a L<match object|/type/Match> and keyed with the same name as the\nmethod.\n\n    =begin code\n    grammar G {\n        token TOP { <thingy> .* }\n        token thingy { 'clever_text_keyword' }\n    }\n    =end code\n\nIf you were to use C<my $match = G.parse($string)> and your\nstring started with 'clever_text_keyword', you would get a match\nobject back that contained 'clever_text_keyword' keyed by\nthe name of C«<thingy>» in your match object. For instance:\n\n=begin code\ngrammar G {\n    token TOP { <thingy> .* }\n    token thingy { 'Þor' }\n}\n\nmy $match = G.parse(\"Þor is mighty\");\nsay $match.raku;     # OUTPUT: «Match.new(made => Any, pos => 13, orig => \"Þor is mighty\",...»\nsay $/.raku;         # OUTPUT: «Match.new(made => Any, pos => 13, orig => \"Þor is mighty\",...»\nsay $/<thingy>.raku;\n# OUTPUT: «Match.new(made => Any, pos => 3, orig => \"Þor is mighty\", hash => Map.new(()), list => (), from => 0)␤»\n=end code\n\nThe two first output lines show that C<$match> contains a L<C<Match>|/type/Match> object with\nthe results of the parsing; but those results are also assigned to the L<match variable C<$/>|/syntax/$$SOLIDUS>.\nEither match object can be keyed, as\nindicated above, by C<thingy> to return the match for that particular C<token>.\n\nThe C<TOP> method (whether regex, token, or rule) is the overarching pattern\nthat must match everything (by default). If the parsed string doesn't\nmatch the TOP regex, your returned match object will be empty (L<C<Nil>|/type/Nil>).\n\nAs you can see above, in C<TOP>, the C«<thingy>» token is mentioned. The\nC«<thingy>» is defined on the next line. That means that\nC<'clever_text_keyword'> B<must> be the first thing in the string, or\nthe grammar parse will fail and we'll get an empty match. This is great for\nrecognizing a malformed string that should be discarded.\n\n=head1 Learning by example - a REST contrivance\n\nLet's suppose we'd like to parse a URI into the component parts that make up a\nRESTful request. We want the URIs to work like this:\n\n=item The first part of the URI will be the \"subject\", like a part, or a\nproduct, or a person.\n\n=item The second part of the URI will be the \"command\", the standard CRUD\nfunctions (create, retrieve, update, or delete).\n\n=item The third part of the URI will be arbitrary data, perhaps the specific ID\nwe'll be working with or a long list of data separated by \"/\"'s.\n\n=item When we get a URI, we'll want 1-3 above to be placed into a data\nstructure that we can easily work with (and later enhance).\n\nSo, if we have \"/product/update/7/notify\", we would want\nour grammar to give us a match object that has a C<subject> of\n\"product\", a C<command> of \"update\", and C<data> of \"7/notify\".\n\nWe'll start by defining a grammar class and some match methods for the\nsubject, command, and data. We'll use the token declarator since we don't care\nabout whitespace.\n\n    =begin code\n    grammar REST {\n        token subject { \\w+ }\n        token command { \\w+ }\n        token data    { .* }\n    }\n    =end code\n\nSo far, this REST grammar says we want a subject that will be just I<word>\ncharacters, a command that will be just I<word> characters, and data that will\nbe everything else left in the string.\n\nNext, we'll want to arrange these matching tokens within the larger context of\nthe URI. That's what the TOP method allows us to do. We'll add the TOP method\nand place the names of our tokens within it, together with the rest of the\npatterns that makes up the overall pattern. Note how we're building a larger\nregex from our named regexes.\n\n    =begin code\n    grammar REST {\n        token TOP     { '/' <subject> '/' <command> '/' <data> }\n        token subject { \\w+ }\n        token command { \\w+ }\n        token data    { .* }\n    }\n    =end code\n\nWith this code, we can already get the three parts of our RESTful request:\n\n    =begin code :preamble<grammar REST {};>\n    my $match = REST.parse('/product/update/7/notify');\n    say $match;\n\n    # OUTPUT: «｢/product/update/7/notify｣␤\n    #          subject => ｢product｣\n    #          command => ｢update｣\n    #          data => ｢7/notify｣»\n    =end code\n\nThe data can be accessed directly by using C«$match<subject>» or\nC«$match<command>» or C«$match<data>» to return the values parsed.\nThey each contain match objects that you can work further with,\nsuch as coercing into a string ( C«$match<command>.Str» ).\n\n=head2 Adding some flexibility\n\nSo far, the grammar will handle retrieves, deletes and updates. However,\na I<create> command doesn't have the third part (the I<data> portion). This\nmeans the grammar will fail to match if we try to parse a create URI. To avoid\nthis, we need to make that last I<data> position match optional, along with the\n'/' preceding it. This is accomplished by adding a question mark to the grouped\n'/' and I<data> components of the TOP token, to indicate their optional nature,\njust like a normal regex.\n\nSo, now we have:\n\n    =begin code\n    grammar REST {\n        token TOP     { '/' <subject> '/' <command> [ '/' <data> ]? }\n        token subject { \\w+ }\n        token command { \\w+ }\n        token data    { .* }\n    }\n\n    my $m = REST.parse('/product/create');\n    say $m<subject>, $m<command>;\n\n    # OUTPUT: «｢product｣｢create｣␤»\n    =end code\n\nNext, assume that the URIs will be entered manually by a user and that the user\nmight accidentally put spaces between the '/'s. If we wanted to accommodate for\nthis, we could replace the '/'s in TOP with a token that allowed for spaces.\n\n    =begin code\n    grammar REST {\n        token TOP     { <slash><subject><slash><command>[<slash><data>]? }\n        token subject { \\w+ }\n        token command { \\w+ }\n        token data    { .* }\n\n        token slash   { \\s* '/' \\s* }\n    }\n\n    my $m = REST.parse('/ product / update /7 /notify');\n    say $m;\n\n    # OUTPUT: «｢/ product / update /7 /notify｣␤\n    #          slash => ｢/ ｣\n    #          subject => ｢product｣\n    #          slash => ｢ / ｣\n    #          command => ｢update｣\n    #          slash => ｢ /｣\n    #          data => ｢7 /notify｣»\n    =end code\n\nWe're getting some extra junk in the match object now, with those slashes.\nThere are techniques to clean that up that we'll get to later.\n=head2 Inheriting from a grammar\n\nSince grammars are classes, they behave, OOP-wise, in the same way as any other class; specifically, they can inherit from base classes that include some tokens or rules, this way:\n\n=begin code\ngrammar Letters {\n    token letters { \\w+ }\n}\n\ngrammar Quote-Quotes {\n    token quote { \"\\\"\" | \"`\" | \"'\" }\n}\n\ngrammar Quote-Other {\n    token quote { \"|\" | \"/\" | \"¡\" }\n}\n\ngrammar Quoted-Quotes is Letters is Quote-Quotes {\n    token TOP { ^  <quoted> $}\n    token quoted { <quote>? <letters> <quote>?  }\n}\n\ngrammar Quoted-Other is Letters is Quote-Other {\n    token TOP { ^  <quoted> $}\n    token quoted { <quote>? <letters> <quote>?  }\n}\n\nmy $quoted = q{\"enhanced\"};\nmy $parsed = Quoted-Quotes.parse($quoted);\nsay $parsed;\n# OUTPUT:\n#｢\"enhanced\"｣\n# quote => ｢\"｣\n# letters => ｢enhanced｣\n#quote => ｢\"｣\n\n$quoted = \"|barred|\";\n$parsed = Quoted-Other.parse($quoted);\nsay $parsed;\n# OUTPUT:\n#|barred|｣\n#quote => ｢|｣\n#letters => ｢barred｣\n#quote => ｢|｣\n=end code\n\nThis example uses multiple inheritance to compose two different grammars by varying the rules that correspond to C<quotes>. In this case, besides, we are rather using composition than inheritance, so we could use Roles instead of inheritance.\n\n=begin code\nrole Letters {\n    token letters { \\w+ }\n}\n\nrole Quote-Quotes {\n    token quote { \"\\\"\" | \"`\" | \"'\" }\n}\n\nrole Quote-Other {\n    token quote { \"|\" | \"/\" | \"¡\" }\n}\n\ngrammar Quoted-Quotes does Letters does Quote-Quotes {\n    token TOP { ^  <quoted> $}\n    token quoted { <quote>? <letters> <quote>?  }\n}\n\ngrammar Quoted-Other does Letters does Quote-Other {\n    token TOP { ^  <quoted> $}\n    token quoted { <quote>? <letters> <quote>?  }\n\n}\n=end code\n\nWill output exactly the same as the code above.  Symptomatic of the difference\nbetween Classes and Roles, a conflict like defining C<token quote> twice\nusing Role composition will result in an error:\n\n=begin code :skip-test<compile-time error>\ngrammar Quoted-Quotes does Letters does Quote-Quotes does Quote-Other { ... }\n# OUTPUT: ... Error while compiling ... Method 'quote' must be resolved ...\n=end code\n\n=head2 Adding some constraints\n\nWe want our RESTful grammar to allow for CRUD operations only. Anything else we\nwant to fail to parse. That means our \"command\" above should have one of four\nvalues: create, retrieve, update or delete.\n\nThere are several ways to accomplish this. For example, you could change the\ncommand method:\n\n    =begin code :solo\n    token command { \\w+ }\n\n    # …becomes…\n\n    token command { 'create'|'retrieve'|'update'|'delete' }\n    =end code\n\nFor a URI to parse successfully, the second part of the string\nbetween '/'s must be one of those CRUD values, otherwise the parsing fails.\nExactly what we want.\n\nThere's another technique that provides greater flexibility and improved\nreadability when options grow large: I<proto-regexes>.\n\nTo utilize these proto-regexes (multimethods, in fact) to limit ourselves to\nthe valid CRUD options, we'll replace C<token command> with the following:\n\n    =begin code\n    proto token command {*}\n    token command:sym<create>   { <sym> }\n    token command:sym<retrieve> { <sym> }\n    token command:sym<update>   { <sym> }\n    token command:sym<delete>   { <sym> }\n    =end code\n\nThe C<sym> keyword is used to create the various proto-regex options.\nEach option is named (e.g., C«sym<update>»), and for that option's use,\na special C«<sym>» token is auto-generated with the same name.\n\nThe C«<sym>» token, as well as other user-defined tokens, may be used in the\nproto-regex option block to define the specific I<match condition>.\nRegex tokens are compiled forms and, once defined, cannot subsequently be\nmodified by adverb actions (e.g., C<:i>). Therefore, as it's auto-generated,\nthe special C«<sym>» token is useful only where an exact match of the option\nname is required.\n\nIf, for one of the proto-regex options, a match condition occurs, then\nthe whole proto's search terminates. The matching data, in the form of a match\nobject, is assigned to the parent proto token. If the special C«<sym>» token\nwas employed and formed all or part of the actual match, then it's preserved as\na sub-level in the match object, otherwise it's absent.\n\nUsing proto-regex like this gives us a lot of flexibility. For example,\ninstead of returning C«<sym>», which in this case is the entire string that was\nmatched, we could instead enter our own string, or do other funny stuff. We\ncould do the same with the C<token subject> method and limit it also to only\nparsing correctly on valid subjects (like 'part' or 'people', etc.).\n\n=head2 Putting our RESTful grammar together\n\nThis is what we have for processing our RESTful URIs, so far:\n\n    =begin code\n    grammar REST\n    {\n        token TOP { <slash><subject><slash><command>[<slash><data>]? }\n\n        proto token command {*}\n        token command:sym<create>   { <sym> }\n        token command:sym<retrieve> { <sym> }\n        token command:sym<update>   { <sym> }\n        token command:sym<delete>   { <sym> }\n\n        token subject { \\w+ }\n        token data    { .* }\n        token slash   { \\s* '/' \\s* }\n    }\n    =end code\n\nLet's look at various URIs and see how they work with our grammar.\n\n    =begin code :preamble<grammar REST{};>\n    my @uris = ['/product/update/7/notify',\n                '/product/create',\n                '/item/delete/4'];\n\n    for @uris -> $uri {\n        my $m = REST.parse($uri);\n        say \"Sub: $m<subject> Cmd: $m<command> Dat: $m<data>\";\n    }\n\n    # OUTPUT: «Sub: product Cmd: update Dat: 7/notify␤\n    #          Sub: product Cmd: create Dat: ␤\n    #          Sub: item Cmd: delete Dat: 4␤»\n    =end code\n\nNote that since C«<data>» matches nothing on the second string, C«$m<data>»\nwill be L<C<Nil>|/type/Nil>, then using it in string context in the C<say> function warns.\n\nWith just this part of a grammar, we're getting almost everything we're\nlooking for. The URIs get parsed and we get a data structure with the data.\n\nThe I<data> token returns the entire end of the URI as one string. The 4 is\nfine. However from the '7/notify', we only want the 7. To get just the 7,\nwe'll use another feature of grammar classes: I<actions>.\n\n=head1 Grammar actions\n\nGrammar actions are used within grammar classes to do things with matches.\nActions are defined in their own classes, distinct from grammar classes.\n\nYou can think of grammar actions as a kind of plug-in expansion module for\ngrammars. A lot of the time you'll be happy using grammars all by their own.\nBut when you need to further process some of those strings, you can plug in the\nActions expansion module.\n\nTo work with actions, you use a named parameter called C<actions> which\nshould contain an instance of your actions class. With the code above, if our\nactions class called REST-actions, we would parse the URI string like this:\n\n    =begin code :skip-test<illustrates pattern>\n    my $matchObject = REST.parse($uri, actions => REST-actions.new);\n\n    #   …or if you prefer…\n\n    my $matchObject = REST.parse($uri, :actions(REST-actions.new));\n    =end code\n\nIf you I<name your action methods with the same name as your grammar methods>\n(tokens, regexes, rules), then when your grammar methods match, your action\nmethod with the same name will get called automatically. The method will also\nbe passed the corresponding match object (represented by the C<$/> variable).\n\nLet's turn to an example.\n\n=head2 Grammars by example with actions\n\nHere we are back to our grammar.\n\n    =begin code\n    grammar REST\n    {\n        token TOP { <slash><subject><slash><command>[<slash><data>]? }\n\n        proto token command {*}\n        token command:sym<create>   { <sym> }\n        token command:sym<retrieve> { <sym> }\n        token command:sym<update>   { <sym> }\n        token command:sym<delete>   { <sym> }\n\n        token subject { \\w+ }\n        token data    { .* }\n        token slash   { \\s* '/' \\s* }\n    }\n    =end code\n\nRecall that we want to further process the data token \"7/notify\", to get the 7.\nTo do this, we'll create an action class that has a method with the same name\nas the named token. In this case, our token is named C<data> so our method\nis also named C<data>.\n\n    =begin code\n    class REST-actions\n    {\n        method data($/) { $/.split('/') }\n    }\n    =end code\n\nNow when we pass the URI string through the grammar, the I<data token match>\nwill be passed to the I<REST-actions' data method>. The action method will\nsplit the string by the '/' character and the first element of the returned\nlist will be the ID number (7 in the case of \"7/notify\").\n\nBut not really; there's a little more.\n\n=head2 Keeping grammars with actions tidy with C<make> and C<made>\n\nIf the grammar calls the action above on data, the data method will be called,\nbut nothing will show up in the big C<TOP> grammar match result returned to our\nprogram. In order to make the action results show up, we need to call L<make|/routine/make>\non that result. The result can be many things, including strings, array or\nhash structures.\n\nYou can imagine that the C<make> places the result in a special contained area\nfor a grammar. Everything that we C<make> can be accessed later by L<made|/routine/made>.\n\nSo instead of the REST-actions class above, we should write:\n\n    =begin code\n    class REST-actions\n    {\n        method data($/) { make $/.split('/') }\n    }\n    =end code\n\nWhen we add C<make> to the match split (which returns a list), the action will\nreturn a data structure to the grammar that will be stored separately from\nthe C<data> token of the original grammar. This way, we can work with both\nif we need to.\n\nIf we want to access just the ID of 7 from that long URI, we access the first\nelement of the list returned from the C<data> action that we C<made>:\n\n    =begin code :skip-test<continued example>\n    my $uri = '/product/update/7/notify';\n\n    my $match = REST.parse($uri, actions => REST-actions.new);\n\n    say $match<data>.made[0];  # OUTPUT: «7␤»\n    say $match<command>.Str;   # OUTPUT: «update␤»\n    =end code\n\nHere we call C<made> on data, because we want the result of the action that\nwe C<made> (with C<make>) to get the split array. That's lovely! But, wouldn't\nit be lovelier if we could C<make> a friendlier data structure that contained\nall of the stuff we want, rather than having to coerce types and remember\narrays?\n\nJust like Grammar's C<TOP>, which matches the entire string, actions\nhave a TOP method as well. We can C<make> all of the individual match\ncomponents, like C<data> or C<subject> or C<command>, and then we can\nplace them in a data structure that we will C<make> in TOP. When we return\nthe final match object, we can then access this data structure.\n\nTo do this, we add the method C<TOP> to the action class and C<make>\nwhatever data structure we like from the component pieces.\n\nSo, our action class becomes:\n\n    =begin code\n    class REST-actions\n    {\n        method TOP ($/) {\n            make { subject => $<subject>.Str,\n                   command => $<command>.Str,\n                   data    => $<data>.made }\n        }\n\n        method data($/) { make $/.split('/') }\n    }\n    =end code\n\nHere in the C<TOP> method, the C<subject> remains the same as the subject we\nmatched in the grammar. Also, C<command> returns the valid C«<sym>» that was\nmatched (create, update, retrieve, or delete). We coerce each into C<.Str>, as\nwell, since we don't need the full match object.\n\nWe want to make sure to use the C<made> method on the C«$<data>» object,\nsince we want to access the split one that we C<made> with C<make> in our\naction, rather than the proper C«$<data>» object.\n\nAfter we C<make> something in the C<TOP> method of a grammar action, we can then\naccess all the custom values by calling the C<made> method on the grammar\nresult object. The code now becomes\n\n    =begin code :skip-test<continued example>\n    my $uri = '/product/update/7/notify';\n\n    my $match = REST.parse($uri, actions => REST-actions.new);\n\n    my $rest = $match.made;\n    say $rest<data>[0];   # OUTPUT: «7␤»\n    say $rest<command>;   # OUTPUT: «update␤»\n    say $rest<subject>;   # OUTPUT: «product␤»\n    =end code\n\nIf the complete return match object is not needed, you could return only the made\ndata from your action's C<TOP>.\n\n    =begin code :skip-test<continued example>\n    my $uri = '/product/update/7/notify';\n\n    my $rest = REST.parse($uri, actions => REST-actions.new).made;\n\n    say $rest<data>[0];   # OUTPUT: «7␤»\n    say $rest<command>;   # OUTPUT: «update␤»\n    say $rest<subject>;   # OUTPUT: «product␤»\n    =end code\n\nOh, did we forget to get rid of that ugly array element number? Hmm. Let's make\nsomething new in the grammar's custom return in C<TOP>... how about we call it\nC<subject-id> and have it set to element 0 of C«<data>».\n\n    =begin code\n    class REST-actions\n    {\n        method TOP ($/) {\n            make { subject    => $<subject>.Str,\n                   command    => $<command>.Str,\n                   data       => $<data>.made,\n                   subject-id => $<data>.made[0] }\n        }\n\n        method data($/) { make $/.split('/') }\n    }\n    =end code\n\nNow we can do this instead:\n\n    =begin code :skip-test<continued example>\n    my $uri = '/product/update/7/notify';\n\n    my $rest = REST.parse($uri, actions => REST-actions.new).made;\n\n    say $rest<command>;    # OUTPUT: «update␤»\n    say $rest<subject>;    # OUTPUT: «product␤»\n    say $rest<subject-id>; # OUTPUT: «7␤»\n    =end code\n\nHere's the final code:\n\n    =begin code\n    grammar REST\n    {\n        token TOP { <slash><subject><slash><command>[<slash><data>]? }\n\n        proto token command {*}\n        token command:sym<create>   { <sym> }\n        token command:sym<retrieve> { <sym> }\n        token command:sym<update>   { <sym> }\n        token command:sym<delete>   { <sym> }\n\n        token subject { \\w+ }\n        token data    { .* }\n        token slash   { \\s* '/' \\s* }\n    }\n\n\n    class REST-actions\n    {\n        method TOP ($/) {\n            make { subject    => $<subject>.Str,\n                   command    => $<command>.Str,\n                   data       => $<data>.made,\n                   subject-id => $<data>.made[0] }\n        }\n\n        method data($/) { make $/.split('/') }\n    }\n    =end code\n\n=head2 Add actions directly\n\nAbove we see how to associate grammars with action objects and perform\nactions on the match object. However, when we want to deal with the match\nobject, that isn't the only way. See the example below:\n\n    =begin code\n    grammar G {\n      rule TOP { <function-define> }\n      rule function-define {\n        'sub' <identifier>\n        {\n          say \"func \" ~ $<identifier>.made;\n          make $<identifier>.made;\n        }\n        '(' <parameter> ')' '{' '}'\n        { say \"end \" ~ $/.made; }\n      }\n      token identifier { \\w+ { make ~$/; } }\n      token parameter { \\w+ { say \"param \" ~ $/; } }\n    }\n\n    G.parse('sub f ( a ) { }');\n    # OUTPUT: «func f␤param a␤end f␤»\n    =end code\n\nThis example is a reduced portion of a parser. Let's focus more on the feature\nit shows.\n\nFirst, we can add actions inside the grammar itself, and such actions are\nperformed once the control flow of the regex arrives at them. Note that action\nobject's method will always be performed after the whole regex item matched.\nSecond, it shows what C<make> really does, which is no more than a sugar of\nC<$/.made = ...>. And this trick introduces a way to pass messages from within\na regex item.\n\nHopefully this has helped introduce you to the grammars in Raku and shown you\nhow grammars and grammar action classes work together. For more information,\ncheck out the more advanced L<Raku Grammar Guide|/language/grammars>.\n\nFor more grammar debugging, see\nL<Grammar::Debugger|https://github.com/jnthn/grammar-debugger>. This provides\nbreakpoints and color-coded MATCH and FAIL output for each of your grammar\ntokens.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/grammars.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Grammars\n\n=SUBTITLE Parsing and interpreting text\n\nGrammar is a powerful tool used to destructure text and often to return\ndata structures that have been created by interpreting that text.\n\nFor example, Raku is parsed and executed using a Raku-style grammar.\n\nAn example that's more practical to the common Raku user is the\nL<JSON::Tiny module|https://github.com/moritz/json>, which can deserialize\nany valid JSON file; however, the deserializing code is written in less than\n100 lines of simple, extensible code.\n\nIf you didn't like grammar in school, don't let that scare you off grammars.\nGrammars allow you to group regexes, just as classes allow you to group\nmethods of regular code.\n\n=head1 X<Named Regexes|Syntax,token>\n\nThe main ingredient of grammars is named L<regexes|/language/regexes>.\nWhile the syntax of L<Raku Regexes|/language/regexes> is outside the scope\nof this document, I<named> regexes have a special syntax, similar to\nsubroutine definitions: N<In fact, named regexes can even take extra\narguments, using the same syntax as subroutine parameter lists>\n\n=begin code\nmy regex number { \\d+ [ \\. \\d+ ]? }\n=end code\n\nIn this case, we have to specify that the regex is lexically scoped using\nthe C<my> keyword, because named regexes are normally used within grammars.\n\nBeing named gives us the advantage of being able to easily reuse the regex\nelsewhere:\n\n=begin code :preamble<my regex number{...};>\nsay so \"32.51\" ~~ &number;                         # OUTPUT: «True␤»\nsay so \"15 + 4.5\" ~~ /<number>\\s* '+' \\s*<number>/ # OUTPUT: «True␤»\n=end code\n\nB<C<regex>> isn't the only declarator for named regexes. In fact, it's the\nleast common. Most of the time, the B<C<token>> or B<C<rule>> declarators\nare used. These are both I<ratcheting>, which means that the match engine\nwon't back up and try again if it fails to match something. This will\nusually do what you want, but isn't appropriate for all cases:\n\n    =begin code\n    my regex works-but-slow { .+ q }\n    my token fails-but-fast { .+ q }\n    my $s = 'Tokens won\\'t backtrack, which makes them fail quicker!';\n    say so $s ~~ &works-but-slow; # OUTPUT: «True␤»\n    say so $s ~~ &fails-but-fast; # OUTPUT: «False␤»\n                                  # the entire string is taken by the .+\n    =end code\n\nNote that non-backtracking works on terms, that is, as the example below, if\nyou have matched something, then you will never backtrack. But when you fail to\nmatch, if there is another candidate introduced by C<|> or C<||>, you will\nretry to match again.\n\n    =begin code\n    my token tok-a { .* d  };\n    my token tok-b { .* d | bd };\n    say so \"bd\" ~~ &tok-a;        # OUTPUT: «False␤»\n    say so \"bd\" ~~ &tok-b;        # OUTPUT: «True␤»\n    =end code\n\n=head2 X<Rules|Syntax,rule>\n\nThe only difference between the C<token> and C<rule> declarators is that the\nC<rule> declarator causes L<C<:sigspace>|/language/regexes#Sigspace> to go\ninto effect for the Regex:\n\n    =begin code\n    my token token-match { 'once' 'upon' 'a' 'time' }\n    my rule  rule-match  { 'once' 'upon' 'a' 'time' }\n    say so 'onceuponatime'    ~~ &token-match; # OUTPUT: «True␤»\n    say so 'once upon a time' ~~ &token-match; # OUTPUT: «False␤»\n    say so 'onceuponatime'    ~~ &rule-match;  # OUTPUT: «False␤»\n    say so 'once upon a time' ~~ &rule-match;  # OUTPUT: «True␤»\n    =end code\n\n=head1 X<Creating grammars|Language,Creating grammars>\n\nL<C<Grammar>|/type/Grammar> is the superclass that classes automatically get when\nthey are declared with the C<grammar> keyword instead of C<class>. Grammars\nshould only be used to parse text; if you wish to extract complex data, you can\nadd actions within the grammar or use an L<action\nobject|/language/grammars#Action_objects> in conjunction with the grammar.\n\n=head2 X«Proto regexes|Syntax,:sym<>»\n\nX«|Language,proto regex»\nX«|Syntax,grammar»\nL<C<Grammar>|/type/Grammar>s are composed of rules, tokens and regexes; these are\nactually methods, since grammars are classes.\n\nN<They are actually a special kind of class, but for the rest of the section,\nthey behave in the same way as a I<normal> class would>\n\nThese methods can share a name and\nfunctionality in common, and thus can use L<proto|/syntax/proto>.\n\nFor instance, if you have a lot of alternations, it may become difficult to\nproduce readable code or subclass your grammar. In the C<Calculations> class below,\nthe ternary in C<method TOP> is less than ideal and it becomes even worse the\nmore operations we add:\n\n    grammar Calculator {\n        token TOP { [ <add> | <sub> ] }\n        rule  add { <num> '+' <num> }\n        rule  sub { <num> '-' <num> }\n        token num { \\d+ }\n    }\n\n    class Calculations {\n        method TOP ($/) { make $<add> ?? $<add>.made !! $<sub>.made; }\n        method add ($/) { make [+] $<num>; }\n        method sub ($/) { make [-] $<num>; }\n    }\n\n    say Calculator.parse('2 + 3', actions => Calculations).made;\n\n    # OUTPUT: «5␤»\n\nTo make things better, we can use proto regexes that look like C«:sym<...>»\nadverbs on tokens:\n\n    grammar Calculator {\n        token TOP { <calc-op> }\n\n        proto rule calc-op          {*}\n              rule calc-op:sym<add> { <num> '+' <num> }\n              rule calc-op:sym<sub> { <num> '-' <num> }\n\n        token num { \\d+ }\n    }\n\n    class Calculations {\n        method TOP              ($/) { make $<calc-op>.made; }\n        method calc-op:sym<add> ($/) { make [+] $<num>; }\n        method calc-op:sym<sub> ($/) { make [-] $<num>; }\n    }\n\n    say Calculator.parse('2 + 3', actions => Calculations).made;\n\n    # OUTPUT: «5␤»\n\nIn this grammar the alternation has now been replaced with C«<calc-op>»,\nwhich is essentially the name of a group of values we'll create. We do so by\ndefining a rule prototype with C<proto rule calc-op>. Each of our previous\nalternations have been replaced by a new C<rule calc-op> definition and the\nname of the alternation is attached with C«:sym<>» adverb.\n\nIn the class that declares actions, we now got rid of the ternary operator and\nsimply take the C<.made> value from the C«$<calc-op>» match object. And the\nactions for individual alternations now follow the same naming pattern as in the\ngrammar: C«method calc-op:sym<add>» and C«method calc-op:sym<sub>».\n\nThe real beauty of this method can be seen when you subclass the grammar\nand action classes. Let's say we want to add a multiplication feature to the\ncalculator:\n\n    =begin code :preamble<grammar Calculator {}; class Calculations {}>\n    grammar BetterCalculator is Calculator {\n        rule calc-op:sym<mult> { <num> '*' <num> }\n    }\n\n    class BetterCalculations is Calculations {\n        method calc-op:sym<mult> ($/) { make [*] $<num> }\n    }\n\n    say BetterCalculator.parse('2 * 3', actions => BetterCalculations).made;\n\n    # OUTPUT: «6␤»\n    =end code\n\nAll we had to add are an additional rule and action to the C<calc-op> group and\nthe thing works—all thanks to proto regexes.\n\n=head2 Special tokens\n\n=head3 X«C<TOP>|Regexes,TOP»\n\n    grammar Foo {\n        token TOP { \\d+ }\n    }\n\nThe C<TOP> token is the default first token attempted to match\nwhen parsing with a grammar. Note that if you're parsing with the\nL<C<.parse>|/type/Grammar#method_parse> method, C<token TOP> is automatically\nanchored to the start and end of the string. If you don't want to parse the\nwhole string, look up L<C<.subparse>|/type/Grammar#method_subparse>.\n\nUsing C<rule TOP> or C<regex TOP> is also acceptable.\n\nA different token can be chosen to be matched first using the C<:rule> named\nargument to C<.parse>, C<.subparse>, or C<.parsefile>. These are all L<C<Grammar>|/type/Grammar>\nmethods.\n\n=head3 X«C<ws>|Regexes,ws»\n\nThe default C<ws> matches zero or more whitespace characters, as long as that\npoint is not within a word (in code form, that's C«token ws { <!ww> \\s* }»):\n\n    # First <.ws> matches word boundary at the start of the line\n    # and second <.ws> matches the whitespace between 'b' and 'c'\n    say 'ab   c' ~~ /<.ws> ab <.ws> c /; # OUTPUT: «｢ab   c｣␤»\n\n    # Failed match: there is neither any whitespace nor a word\n    # boundary between 'a' and 'b'\n    say 'ab' ~~ /. <.ws> b/;             # OUTPUT: «Nil␤»\n\n    # Successful match: there is a word boundary between ')' and 'b'\n    say ')b' ~~ /. <.ws> b/;             # OUTPUT: «｢)b｣␤»\n\nPlease bear in mind that we're preceding C<ws> with a dot to avoid capturing,\nwhich we are not interested in. Since in general whitespace is a separator, this\nis how it's mostly found.\n\nWhen C<rule> is used instead of C<token>, C<:sigspace> is enabled by default and\nany whitespace after terms and closing parenthesis/brackets are turned into a\nnon-capturing call to C<ws>, written as C«<.ws>» where C<.> means non-capturing.\nThat is to say:\n\n    rule entry { <key> '=' <value> }\n\nIs the same as:\n\n    token entry { <key> <.ws> '=' <.ws> <value> <.ws> }\n\nYou can also redefine the default C<ws> token:\n\n    grammar Foo {\n        rule TOP { \\d \\d }\n    }.parse: \"4   \\n\\n 5\"; # Succeeds\n\n    grammar Bar {\n        rule TOP { \\d \\d }\n        token ws { \\h*   }\n    }.parse: \"4   \\n\\n 5\"; # Fails\n\nAnd even capture it, but you need to use it explicitly. Notice that in the\nnext example we use C<token> instead of C<rule>, as the latter would cause\nwhitespace to be consumed by the implicit non-capturing C<.ws>.\n\n=for code\ngrammar Foo { token TOP {\\d <ws> \\d} };\nmy $parsed = Foo.parse: \"3 3\";\nsay $parsed<ws>; # OUTPUT: «｢ ｣␤»\n\n=head3 X«C<sym>|Regexes,<sym>»\n\nThe C«<sym>» token can be used inside proto regexes to match the string value of\nthe C<:sym> adverb for that particular regex:\n\n    grammar Foo {\n        token TOP { <letter>+ }\n        proto token letter {*}\n              token letter:sym<R> { <sym> }\n              token letter:sym<a> { <sym> }\n              token letter:sym<k> { <sym> }\n              token letter:sym<u> { <sym> }\n              token letter:sym<*> {   .   }\n    }.parse(\"I ♥ Raku\", actions => class {\n        method TOP($/) { make $<letter>.grep(*.<sym>).join }\n    }).made.say; # OUTPUT: «Raku␤»\n\nThis comes in handy when you're already differentiating the proto regexes with\nthe strings you're going to match, as using C«<sym>» token prevents repetition\nof those strings.\n\n=head3 X«\"Always succeed\" assertion|Regexes,<?>»\n\nThe C«<?>» is the I<always succeed> assertion. When used as a grammar\ntoken, it can be used to trigger an Action class method. In the following\ngrammar we look for Arabic digits and define a C<succ> token with the always\nsucceed assertion.\n\nIn the action class, we use calls to the C<succ> method to do set up (in this\ncase, we prepare a new element in C<@!numbers>). In the C<digit> method,\nwe use the Arabic digit as an index into a list of Devanagari digits and add\nit to the last element of C<@!numbers>. Thanks to C<succ>, the last element\nwill always be the number for the currently parsed C<digit> digits.\n\n    grammar Digifier {\n        rule TOP {\n            [ <.succ> <digit>+ ]+\n        }\n        token succ   { <?> }\n        token digit { <[0..9]> }\n    }\n\n    class Devanagari {\n        has @!numbers;\n        method digit ($/) { @!numbers.tail ~= <०  १  २  ३  ४  ५  ६  ७  ८  ९>[$/] }\n        method succ  ($)  { @!numbers.push: ''     }\n        method TOP   ($/) { make @!numbers[^(*-1)] }\n    }\n\n    say Digifier.parse('255 435 777', actions => Devanagari.new).made;\n    # OUTPUT: «(२५५ ४३५ ७७७)␤»\n\n=head2 Methods in grammars\n\nIt's fine to use methods instead of rules or tokens in a grammar, as long\nas they return a L<C<Match>|/type/Match>:\n\n    grammar DigitMatcher {\n        method TOP (:$full-unicode) {\n            $full-unicode ?? self.num-full !! self.num-basic;\n        }\n        token num-full  { \\d+ }\n        token num-basic { <[0..9]>+ }\n    }\n\nThe grammar above will attempt different matches depending on the argument\nprovided to the subparse methods:\n\n    =begin code :preamble<grammar DigitMatcher{};>\n    say +DigitMatcher.subparse: '12७१७९०९', args => \\(:full-unicode);\n    # OUTPUT: «12717909␤»\n\n    say +DigitMatcher.subparse: '12७१७९०९', args => \\(:!full-unicode);\n    # OUTPUT: «12␤»\n    =end code\n\n=head2 Dynamic variables in grammars\n\nVariables can be defined in tokens by prefixing the lines of code defining them\nwith C<:>. Arbitrary code can be embedded anywhere in a token by surrounding it\nwith curly braces. This is useful for keeping state between tokens, which can be\nused to alter how the grammar will parse text. Using dynamic variables\n(variables with C<$*>, C<@*>, C<&*>, C<%*> twigils) in tokens cascades down\nthrough I<all> tokens defined thereafter within the one where it's defined,\navoiding having to pass them from token to token as arguments.\n\nOne use for dynamic variables is guards for matches. This example uses guards to\nexplain which regex classes parse whitespace literally:\n\n    grammar GrammarAdvice {\n        rule TOP {\n            :my Int $*USE-WS;\n            \"use\" <type> \"for\" <significance> \"whitespace by default\"\n        }\n        token type {\n            | \"rules\"   { $*USE-WS = 1 }\n            | \"tokens\"  { $*USE-WS = 0 }\n            | \"regexes\" { $*USE-WS = 0 }\n        }\n        token significance {\n            | <?{ $*USE-WS == 1 }> \"significant\"\n            | <?{ $*USE-WS == 0 }> \"insignificant\"\n        }\n    }\n\nHere, text such as \"use rules for significant whitespace by default\" will only\nmatch if the state assigned by whether rules, tokens, or regexes are mentioned\nmatches with the correct guard:\n\n=begin code :preamble<grammar GrammarAdvice{};>\nsay GrammarAdvice.subparse(\"use rules for significant whitespace by default\");\n# OUTPUT: «use rules for significant whitespace by default␤»\n\nsay GrammarAdvice.subparse(\"use tokens for insignificant whitespace by default\");\n# OUTPUT: «use tokens for insignificant whitespace by default␤»\n\nsay GrammarAdvice.subparse(\"use regexes for insignificant whitespace by default\");\n# OUTPUT: «use regexes for insignificant whitespace by default␤»\n\nsay GrammarAdvice.subparse(\"use regexes for significant whitespace by default\");\n# OUTPUT: #<failed match>\n=end code\n\n=head2 Attributes in grammars\n\nAttributes may be defined in grammars. However, they can only be accessed by\nmethods. Attempting to use them from within a token will throw an exception\nbecause tokens are methods of L<C<Match>|/type/Match>, not of the grammar itself.\nNote that mutating an attribute from within a method called in a token will\nI<only modify the attribute for that token's own match object>! Grammar\nattributes can be accessed in the match returned after parsing if made public:\n\n=begin code\ngrammar HTTPRequest {\n    has Bool $.invalid;\n\n    token TOP {\n        <type> <.ns> <path> <.ns> 'HTTP/1.1' <.crlf>\n        [ <field> <.crlf> ]+\n        <.crlf>\n        $<body>=.*\n    }\n\n    token type {\n        | [ GET | POST | OPTIONS | HEAD | PUT | DELETE | TRACE | CONNECT ] <.accept>\n        | <-[\\/]>+ <.error>\n    }\n\n    token path {\n        | '/' [[\\w+]+ % \\/] [\\.\\w+]? <.accept>\n        | '*' <.accept>\n        | \\S+ <.error>\n    }\n\n    token field {\n        | $<name>=\\w+ <.ns> ':' <.ns> $<value>=<-crlf>* <.accept>\n        | <-crlf>+ <.error>\n    }\n\n    method error(--> ::?CLASS:D) {\n        $!invalid = True;\n        self;\n    }\n\n    method accept(--> ::?CLASS:D) {\n        $!invalid = False;\n        self;\n    }\n\n    token crlf { # network new line (usually seen as \"\\r\\n\")\n        # Several internet protocols (such as HTTP, RF 2616) mandate\n        # the use of ASCII CR+LF (0x0D 0x0A) to terminate lines at\n        # the protocol level (even though, in practice, some applications\n        # tolerate a single LF).\n        # Raku, Raku grammars and strings (Str) adhere to Unicode\n        # conformance. Thus, CR+LF cannot be expressed unambiguously\n        # as \\r\\n in in Raku grammars or strings (Str), as Unicode\n        # conformance requires \\r\\n to be interpreted as \\n alone.\n        \\x[0d] \\x[0a]\n    }\n    token ns { # network space\n        # <ws> would consume, e.g., newlines, and \\h (and \\s) would accept\n        # more codepoints than just ASCII single space and the tab character.\n        [ ' ' | <[\\t]> ]*\n    }\n}\n\nmy $crlf = \"\\x[0d]\\x[0a]\";\nmy $header = \"GOT /index.html HTTP/1.1{$crlf}Host: docs.raku.org{$crlf}{$crlf}body\";\nmy $m = HTTPRequest.parse($header);\nsay \"type(\\\"$m.<type>\\\")={$m.<type>.invalid}\";\n# OUTPUT: type(\"GOT \")=True\nsay \"path(\\\"$m.<path>\\\")={$m.<path>.invalid}\";\n# OUTPUT: path(\"/index.html\")=False\nsay \"field(\\\"$m.<field>[0]\\\")={$m.<field>[0].invalid}\";\n# OUTPUT: field(\"Host: docs.raku.org\")=False\n=end code\n\nNotes: C<$crlf> and token C«<.crlf>» are required if we want to somehow (within\nthe context of this incomplete example) strictly adhere\nto HTTP/1.1 (RFC 2616). The reason is that Raku, in contrast to RFC 2616, is\nUnicode conformant, and \\r\\n needs to be interpreted as a sole \\n,\nthus preventing the grammar to properly parse a string containing \\r\\n in\nthe sense expected by the HTTP protocol.\nNotice how attribute C<invalid> is local to each component (e.g., the value for\nC«<type>» is C<True>, but for C«<path>» is C<False>). Notice also how we have a\nmethod for C<accept>, the reason being that attribute C<invalid> would be\nuninitialized (even if present) otherwise.\n\n=head2 Passing arguments into grammars\n\nTo pass arguments into a grammar, you can use the named argument of C<:args> on\nany of the parsing methods of grammar. The arguments passed should be in a\nC<list>.\n\n=begin code\ngrammar demonstrate-arguments {\n    rule TOP ($word) {\n    \"I like\" $word\n    }\n}\n\n# Notice the comma after \"sweets\" when passed to :args to coerce it to a list\nsay demonstrate-arguments.parse(\"I like sweets\", :args((\"sweets\",)));\n# OUTPUT: «｢I like sweets｣␤»\n=end code\n\nOnce the arguments are passed in, they can be used in a call to a named regex\ninside the grammar.\n\n=begin code\ngrammar demonstrate-arguments-again {\n    rule TOP ($word) {\n    <phrase-stem><added-word($word)>\n    }\n\n    rule phrase-stem {\n       \"I like\"\n    }\n\n    rule added-word($passed-word) {\n       $passed-word\n    }\n}\n\nsay demonstrate-arguments-again.parse(\"I like vegetables\", :args((\"vegetables\",)));\n# OUTPUT: ｢I like vegetables｣␤»\n# OUTPUT:  «phrase-stem => ｢I like ｣␤»\n# OUTPUT:  «added-word => ｢vegetables｣␤»\n=end code\n\nAlternatively, you can initialize dynamic variables and use any arguments that\nway within the grammar.\n\n=begin code\ngrammar demonstrate-arguments-dynamic {\n   rule TOP ($*word, $*extra) {\n      <phrase-stem><added-words>\n   }\n   rule phrase-stem {\n      \"I like\"\n   }\n   rule added-words {\n      $*word $*extra\n   }\n}\n\nsay demonstrate-arguments-dynamic.parse(\"I like everything else\",\n  :args((\"everything\", \"else\")));\n# OUTPUT: «｢I like everything else｣␤»\n# OUTPUT:  «phrase-stem => ｢I like ｣␤»\n# OUTPUT:  «added-words => ｢everything else｣␤»\n=end code\n\n=head1 X<Action objects|Regexes,Actions>\n\nA successful grammar match gives you a parse tree of L<C<Match>|/type/Match>\nobjects, and the deeper that match tree gets, and the more branches in the\ngrammar are, the harder it becomes to navigate the match tree to get the\ninformation you are actually interested in.\n\nTo avoid the need for diving deep into a match tree, you can supply an\nI<actions> object. After each successful parse of a named rule in your\ngrammar, it tries to call a method of the same name as the grammar rule,\ngiving it the newly created L<C<Match>|/type/Match> object as a positional\nargument. If no such method exists, it is skipped.\n\nHere is a contrived example of a grammar and actions in action:\n\n=begin code\ngrammar TestGrammar {\n    token TOP { \\d+ }\n}\n\nclass TestActions {\n    method TOP($/) {\n        make(2 + $/);\n    }\n}\n\nmy $match = TestGrammar.parse('40', actions => TestActions.new);\nsay $match;         # OUTPUT: «｢40｣␤»\nsay $match.made;    # OUTPUT: «42␤»\n=end code\n\nAn instance of C<TestActions> is passed as named argument C<actions> to the\nL<parse|/routine/parse> call, and when token C<TOP> has matched successfully,\nit automatically calls method C<TOP>, passing the match object as an argument.\n\nTo make it clear that the argument is a match object, the example uses C<$/>\nas a parameter name to the action method, though that's just a handy\nconvention, nothing intrinsic; C<$match> would have worked too, though using\nC<$/> does give the advantage of providing C«$<capture>» as a shortcut\nfor C«$/<capture>»; we use another argument, anyway, in the action for C<TOP>.\n\nA slightly more involved example follows:\n\n=begin code\ngrammar KeyValuePairs {\n    token TOP {\n        [<pair> \\v+]*\n    }\n\n    token pair {\n        <key=.identifier> '=' <value=.identifier>\n    }\n\n    token identifier {\n        \\w+\n    }\n}\n\nclass KeyValuePairsActions {\n    method pair      ($/) {\n        make $/<key>.made => $/<value>.made\n    }\n    method identifier($/) {\n        # subroutine `make` is the same as calling .make on $/\n        make ~$/\n    }\n\n    method TOP ($match) {\n        # can use any variable name for parameter, not just $/\n        $match.make: $match<pair>».made\n    }\n}\n\n\nmy $actions = KeyValuePairsActions;\nmy @res = KeyValuePairs.parse(q:to/EOI/, :$actions).made;\nsecond=b\nhits=42\nraku=d\nEOI\n\nfor @res -> $p {\n    say \"Key: $p.key()\\tValue: $p.value()\";\n}\n=end code\n\nThis produces the following output:\n\n=begin code :lang<text>\nKey: second     Value: b\nKey: hits       Value: 42\nKey: raku       Value: d\n=end code\n\nRule C<pair>, which parsed a pair separated by an equals sign, aliases the two\ncalls to token C<identifier> to separate capture names so that they are\navailable\nmore easily and intuitively, as they will be in the corresponding Action. The\ncorresponding action method constructs a\nL<C<Pair>|/type/Pair> object, and uses the C<.made> property of the sub match\nobjects. So it (like the action method C<TOP> too) exploits the fact that\naction methods for submatches are called before those of the calling/outer\nregex. So action methods are called in\nL<post-order|https://en.wikipedia.org/wiki/Tree_traversal#Post-order>.\n\nThe action method C<TOP> simply collects all the objects that were C<.made> by\nthe multiple matches of the C<pair> rule, and returns them in a list. Please\nnote that, in this case, we need to use the method form of\nL<C<make>|/routine/make>, since the routine form can only be used if the\nargument to the action method is C<$/>. Inversely, if the argument of the\nmethod is C<$/>, we can use simply C<make>, which is equivalent to C<$/.make>.\n\nAlso note that C<KeyValuePairsActions> was passed as a type object to method\nC<parse>, which was possible because none of the action methods use attributes\n(which would only be available in an instance).\n\nWe can extend above example by using inheritance.\n\n=begin code :skip-test<Incomplete example>\nuse KeyValuePairs;\n\nunit grammar ConfigurationSets is KeyValuePairs;\n\ntoken TOP {\n    <configuration-element>+ %% \\v\n}\n\ntoken configuration-element {\n    <pair>+ %% \\v\n}\n\ntoken comment {\n    \\s* '#' .+? $$\n}\n\ntoken pair {\n    <key=.identifier> '=' <value=.identifier> <comment>?\n}\n=end code\n\nWe are sub-classing (actually, sub-grammaring) the previous example; we have\noverridden the definition of C<pair> by adding a C<comment>; the previous\nC<TOP> rule has been demoted to C<configuration-element>, and there's a new\nC<TOP> which now considers sets of configuration elements separated by\nvertical space. We can also reuse actions by subclassing the action class:\n\n=begin code :skip-test<Incomplete example>\nuse KeyValuePairs;\n\nunit class ConfigurationSetsActions is KeyValuePairsActions;\n\nmethod configuration-element($match) {\n    $match.make: $match<pair>».made\n}\n\nmethod TOP ($match) {\n    my @made-elements = gather for $match<configuration-element> {\n        take $_.made\n    };\n    $match.make( @made-elements );\n\n}\n=end code\n\nAll existing actions are reused, although obviously new ones have to be\nwritten for the new elements in the grammar, including C<TOP>. These can be\nused together from this script:\n\n=begin code :skip-test<Incomplete example>\nuse ConfigurationSets;\nuse ConfigurationSetsActions;\n\nmy $actions = ConfigurationSetsActions;\nmy $sets = ConfigurationSets.parse(q:to/EOI/, :$actions).made;\nsecond=b # Just a thing\nhits=42\nraku=d\n\nthird=c # New one\nhits=33\nEOI\n\nfor @$sets -> $set {\n    say \"Element→ $set\";\n}\n=end code\n\nWhich will print\n\n=for code :lang<text>\nElement→ second b hits 42 raku d\nElement→ third c hits 33\n\n\n\nIn other cases, action methods might want to keep state in attributes. Then of\ncourse you must pass an instance to method parse.\n\nNote that C<token> C<ws> is special: when C<:sigspace> is enabled (and it is\nwhen we are using C<rule>), it replaces certain whitespace sequences. This is\nwhy the spaces around the equals sign in C<rule pair> work just fine and why\nthe whitespace before closing C<}> does not gobble up the newlines looked for\nin C<token TOP>.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/hashmap.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Hashes and maps\n\n=SUBTITLE Working with associative arrays/dictionaries/hashes\n\n=head1 The associative role and associative classes\n\nThe L<C<Associative>|/type/Associative> role underlies hashes and maps, as well as\nother classes such as L<C<MixHash>|/type/MixHash>. It defines the two types that\nwill be used in associative classes; by default, you can use anything\n(literally, since any class that subclasses L<C<Any>|/type/Any> can be used) L<as a\nkey|#Non-string_keys_(object_hash)>, although it will be coerced to a string,\nand any object as value. You can access these types using the C<of> and C<keyof>\nmethods.\n\nBy default, any object declared with the C<%> sigil will get the Associative\nrole, and will by default behave like a hash, but this role will only provide\nthe two methods above, as well as the default Hash behavior.\n\n    say (%).^name ; # OUTPUT: «Hash␤»\n\nInversely, you cannot use the C<%> sigil if the L<C<Associative>|/type/Associative> role is not mixed\nin, but since this role does not have any associated properties, you will have\nto redefine the behavior of the L<hash subscript\noperator|/language/operators#postcircumfix_{_}>. In order to do that, there\nare several functions you will have to override:\n\n=begin code\nclass Logger does Associative[Cool,DateTime] {\n    has %.store;\n\n    method log( Cool $event ) {\n        %.store{ DateTime.new( now ) } = $event;\n    }\n\n    multi method AT-KEY ( ::?CLASS:D: $key) {\n        my @keys = %.store.keys.grep( /$key/ );\n        %.store{ @keys };\n    }\n\n    multi method EXISTS-KEY (::?CLASS:D: $key) {\n        %.store.keys.grep( /$key/ )??True!!False;\n    }\n\n    multi method DELETE-KEY (::?CLASS:D: $key) {\n        X::Assignment::RO.new.throw;\n    }\n\n    multi method ASSIGN-KEY (::?CLASS:D: $key, $new) {\n        X::Assignment::RO.new.throw;\n    }\n\n    multi method BIND-KEY (::?CLASS:D: $key, \\new){\n        X::Assignment::RO.new.throw;\n    }\n}\nsay Logger.of;                   # OUTPUT: «(Cool)␤»\nmy %logger := Logger.new;\nsay %logger.of;                  # OUTPUT: «(Cool)␤»\n\n%logger.log( \"Stuff\" );\n%logger.log( \"More stuff\");\n\nsay %logger<2018-05-26>;         # OUTPUT: «(More stuff Stuff)␤»\nsay %logger<2018-04-22>:exists;  # OUTPUT: «False␤»\n=end code\n\nIn this case, we are defining a logger with Associative semantics that will be\nable to use dates (or a part of them) as keys. Since we are parameterizing\nL<C<Associative>|/type/Associative> to those particular classes, C<of> will return the value type we\nhave used, L<C<Cool>|/type/Cool> in this case (we can log lists or strings only). Mixing the\nL<C<Associative>|/type/Associative> role gives it the right to use the C<%> sigil; binding is needed\nin the definition since C<%>-sigiled variables get by default the L<C<Hash>|/type/Hash> type.\n\nThis log is going to be append-only, which is why we escape the associative\narray metaphor to use a C<log> method to add new events to the log. Once they\nhave been added, however, we can retrieve them by date or check if they exist.\nFor the first we have to override the C<AT-KEY> multi method, for the latter\nC<EXIST-KEY>. In the last two statements, we show how the subscript operation\ninvokes C<AT-KEY>, while the C<:exists> adverb invokes C<EXISTS-KEY>.\n\nWe override C<DELETE-KEY>, C<ASSIGN-KEY> and C<BIND-KEY>, but only to throw an\nexception. Attempting to assign, delete, or bind a value to a key will result in\na C<Cannot modify an immutable Str (value)> exception thrown.\n\nMaking classes associative provides a very convenient way of using and working\nwith them using hashes; an example can be seen in\nL<Cro|https://cro.services/docs/reference/cro-http-client#Setting_the_request_body>,\nwhich uses it extensively for the convenience of using hashes to define\nstructured requests and express its response.\n\n=head1 Mutable hashes and immutable maps\n\nA L«C<Hash>|/type/Hash» is a mutable mapping from keys to values (called I<dictionary>, I<hash\ntable> or I<map> in other programming languages). The values are all scalar\ncontainers, which means you can assign to them. L«C<Map>|/type/Map»s are, on the\nother hand, immutable. Once a key has been paired with a value, this pairing\ncannot be changed.\n\nMaps and hashes are usually stored in variables with the percent C<%> sigil,\nwhich is used to indicate they are Associative.\n\nHash and map elements are accessed by key via the C<{ }> postcircumfix operator:\n\n    say %*ENV{'HOME', 'PATH'}.raku;\n    # OUTPUT: «(\"/home/camelia\", \"/usr/bin:/sbin:/bin\")␤»\n\nThe general L<Subscript|/language/subscripts> rules apply providing shortcuts\nfor lists of literal strings, with and without interpolation.\n\n    my %h = oranges => 'round', bananas => 'bendy';\n    say %h<oranges bananas>;\n    # OUTPUT: «(round bendy)␤»\n\n    my $fruit = 'bananas';\n    say %h«oranges \"$fruit\"»;\n    # OUTPUT: «(round bendy)␤»\n\nYou can add new pairs simply by assigning to an unused key:\n\n    my %h;\n    %h{'new key'} = 'new value';\n\n=head1 Hash assignment\n\nAssigning a list of elements to a hash variable first empties the variable, and\nthen iterates the elements of the right-hand side (which must contain an even number\nof elements). Note that hash keys are always\ncoerced to be strings even if they are unquoted, but keys with spaces in their\nnames must be quoted. For example, using the common L<C<Pair>|/type/Pair> syntax:\n\n    my %h = 1 => 'a', b => 2, '1 2' => 3;\n    say %h.keys.sort.raku;       # OUTPUT: «(\"1\", \"1 2\", \"b\").Seq␤»\n    say %h.values.sort.raku      # OUTPUT: «(2, 3, \"a\").Seq␤»\n\nThe stringification of the keys can lead to surprising results. For example, the Raku\nmodule C<CSV::Parser> in one mode returns a CSV data line as a hash of C«{UInt => 'value'}» pairs\nwhich can look like this fragment of a 20-field line:\n\n    my %csv = '2' => 'a', '10' => 'b';\n    say %csv.keys.sort.raku;           # OUTPUT: «(\"10\", \"2\").Seq␤»\n\nThe sort result is not what one would normally want. We can use the power of Raku to coerce\nthe string values into integers for the sort. There are several ways that can be done but this\nmethod may present the least \"line noise\" to novices or non-Raku viewers:\n\n=for code :preamble<my %csv>\nsay %csv.keys.map(+*).sort.raku;   # OUTPUT: «(2, 10).Seq␤»\n\nIn a hash constructor list the L<C<Pair>|/type/Pair> syntax doesn't have to be used, or it may be intermixed\nwith ordinary list values as long as the list has an even number of elements in total as well\nas between L<C<Pair>|/type/Pair>s. If an element is a L<C<Pair>|/type/Pair> type (e.g., 'a => 1'), its key is taken as a\nnew hash key, and its value as the new hash value for that key. Otherwise the value is coerced\nto L<C<Str>|/type/Str> and used as a hash key, while the next element of the list is taken as the\ncorresponding value.\n\n    my %h = 'a', 'b', c => 'd', 'e', 'f';\n\nSame as\n\n    my %h = a => 'b', c => 'd', e => 'f';\n\nor\n\n    my %h = <a b c d e f>;\n\nor even\n\n    my %h = %( a => 'b', c => 'd', e => 'f' );\n\nIf you have an odd number of elements using most constructors you will see an error:\n\n    my %h = <a b c>; # OUTPUT: «hash initializer expected...␤»\n\nThere are two other valid ways of constructing a hash, but the user should be wary:\n\n    my %h = [ a => 'b', c => 'd', e => 'f' ]; # This format is NOT recommended.\n                                              # It cannot be a constant and there\n                                              # will be problems with nested hashes\n\nor\n\n    my $h = { a => 'b', c => 'd', e => 'f'};\n\nPlease note that curly braces are used only in the case that we are not\nassigning it to a C<%>-sigiled variable; in case we use it for a C<%>-sigiled\nvariable we will get an error of C<Potential difficulties:␤ Useless use of hash\ncomposer on right side of hash assignment; did you mean := instead?>. As\nthis error indicates, however, we can use curly braces as long as we use also\nbinding:\n\n    my %h := { a => 'b', c => 'd', e => 'f'};\n    say %h; # OUTPUT: «{a => b, c => d, e => f}␤»\n\nNested hashes can also be defined using the same syntax:\n\n     my %h =  e => f => 'g';\n     say %h<e><f>; # OUTPUT: «g␤»\n\nHowever, what you are defining here is a key pointing to a L<C<Pair>|/type/Pair>,\nwhich is fine if that is what you want and your nested hash has a single key.\nBut C<%h<e>> will point to a L<C<Pair>|/type/Pair> which will have these consequences:\n\n=begin code\nmy %h =  e => f => 'g';\n%h<e><q> = 'k';\n# OUTPUT: «Pair␤Cannot modify an immutable Str (Nil)␤  in block <unit>»\n=end code\n\nThis, however, will effectively define a nested hash:\n\n     my %h =  e => { f => 'g' };\n     say %h<e>.^name;  # OUTPUT: «Hash␤»\n     say %h<e><f>;     # OUTPUT: «g␤»\n\nIf a L<C<Pair>|/type/Pair> is encountered where a value is expected, it is used as\na hash value:\n\n    my %h = 'a', 'b' => 'c';\n    say %h<a>.^name;            # OUTPUT: «Pair␤»\n    say %h<a>.key;              # OUTPUT: «b␤»\n\nIf the same key appears more than once, the value associated with its last\noccurrence is stored in the hash:\n\n    my %h = a => 1, a => 2;\n    say %h<a>;                  # OUTPUT: «2␤»\n\n\nTo assign a hash to a variable which does not have the C<%> sigil, you may use\nthe C<%()> hash constructor:\n\n    my $h = %( a => 1, b => 2 );\n    say $h.^name;               # OUTPUT: «Hash␤»\n    say $h<a>;                  # OUTPUT: «1␤»\n\nIf one or more values reference the topic variable, C<$_>, the right-hand side\nof the assignment will be interpreted as a L<C<Block>|/type/Block>, not a Hash:\n\n=begin code :skip-test<illustrates error>\nmy @people = [\n    %( id => \"1A\", firstName => \"Andy\", lastName => \"Adams\" ),\n    %( id => \"2B\", firstName => \"Beth\", lastName => \"Burke\" ),\n    # ...\n];\n\nsub lookup-user (Hash $h) { #`(Do something...) $h }\n\nmy @names = map {\n    # While this creates a hash:\n    my  $query = { name => \"$person<firstName> $person<lastName>\" };\n    say $query.^name;      # OUTPUT: «Hash␤»\n\n    # Doing this will create a Block. Oh no!\n    my  $query2 = { name => \"$_<firstName> $_<lastName>\" };\n    say $query2.^name;       # OUTPUT: «Block␤»\n    say $query2<name>;       # fails\n\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::AdHoc: Type Block does not support associative indexing.␤»\n    lookup-user($query);\n    # Type check failed in binding $h; expected Hash but got Block\n}, @people;\n=end code\n\nThis would have been avoided if you had used the C<%()> hash constructor.\nOnly use curly braces for creating Blocks.\n\nX<|Language,hash slice>\n=head2 Hash slices\n\nYou can assign to multiple keys at the same time with a slice.\n\n    my %h; %h<a b c> = 2 xx *; %h.raku.say;  # OUTPUT: «{:a(2), :b(2), :c(2)}␤»\n    my %h; %h<a b c> = ^3;     %h.raku.say;  # OUTPUT: «{:a(0), :b(1), :c(2)}␤»\n\n=head2 X<Non-string keys (object hash)|Language,non-string keys>\n\nX<|Language,object hash>\nX<|Syntax,:{}>\nBy default keys in C<{ }> are forced to strings. To compose a hash with\nnon-string keys, use a colon prefix:\n\n    my $when = :{ (now) => \"Instant\", (DateTime.now) => \"DateTime\" };\n\nNote that with objects as keys, you often cannot use the C«<...>» construct\nfor key lookup, as it creates only strings and\nL<allomorphs|/language/glossary#Allomorph>. Use the C«{...}»\ninstead:\n\n    :{  0  => 42 }<0>.say;   # Int    as key, IntStr in lookup; OUTPUT: «(Any)␤»\n    :{  0  => 42 }{0}.say;   # Int    as key, Int    in lookup; OUTPUT: «42␤»\n    :{ '0' => 42 }<0>.say;   # Str    as key, IntStr in lookup; OUTPUT: «(Any)␤»\n    :{ '0' => 42 }{'0'}.say; # Str    as key, Str    in lookup; OUTPUT: «42␤»\n    :{ <0> => 42 }<0>.say;   # IntStr as key, IntStr in lookup; OUTPUT: «42␤»\n\nI<Note>: Rakudo implementation currently erroneously applies L<the same\nrules|/routine/{ }#(Operators)_term_{_}> for C<:{ }> as it does for C<{ }> and\ncan construct a L<C<Block>|/type/Block> in certain circumstances. To avoid that,\nyou can instantiate a parameterized Hash directly. Parameterization of\nC<%>-sigiled variables is also supported:\n\n    my Num %foo1      = \"0\" => 0e0; # Str keys and Num values\n    my     %foo2{Int} =  0  => \"x\"; # Int keys and Any values\n    my Num %foo3{Int} =  0  => 0e0; # Int keys and Num values\n    Hash[Num,Int].new: 0, 0e0;      # Int keys and Num values\n\nNow if you want to define a hash to preserve the objects you are using\nas keys I<as the B<exact> objects you are providing to the hash to use as keys>,\nthen object hashes are what you are looking for.\n\n=for code\nmy %intervals{Instant};\nmy $first-instant = now;\n%intervals{ $first-instant } = \"Our first milestone.\";\nsleep 1;\nmy $second-instant = now;\n%intervals{ $second-instant } = \"Logging this Instant for spurious raisins.\";\nfor %intervals.sort -> (:$key, :$value) {\n    state $last-instant //= $key;\n    say \"We noted '$value' at $key, with an interval of {$key - $last-instant}\";\n    $last-instant = $key;\n}\n\nThis example uses an object hash that only accepts keys of type\nL<C<Instant>|/type/Instant> to implement a rudimentary, yet type-safe, logging\nmechanism. We utilize a named L<state|/language/variables#The_state_declarator>\nvariable for keeping track of the previous L<C<Instant>|/type/Instant> so that we can provide an\ninterval.\n\nThe whole point of object hashes is to keep keys as objects-in-themselves.\nCurrently object hashes utilize the L<WHICH|/routine/WHICH> method of an object,\nwhich returns a unique identifier for every mutable object. This is the keystone\nupon which the object identity operator (L<===|/routine/===>) rests. Order and containers\nreally matter here as the order of C<.keys> is undefined and one anonymous list\nis never L<===|/routine/===> to another.\n\n=for code\nmy %intervals{Instant};\nmy $first-instant = now;\n%intervals{ $first-instant } = \"Our first milestone.\";\nsleep 1;\nmy $second-instant = now;\n%intervals{ $second-instant } = \"Logging this Instant for spurious raisins.\";\nsay ($first-instant, $second-instant) ~~ %intervals.keys;       # OUTPUT: «False␤»\nsay ($first-instant, $second-instant) ~~ %intervals.keys.sort;  # OUTPUT: «True␤»\nsay ($first-instant, $second-instant) === %intervals.keys.sort; # OUTPUT: «False␤»\nsay $first-instant === %intervals.keys.sort[0];                 # OUTPUT: «True␤»\n\nSince L<C<Instant>|/type/Instant> defines its own comparison methods, in our example a sort\naccording to L<cmp|/routine/cmp> will always provide the earliest instant object\nas the first element in the L<C<List>|/type/List> it returns.\n\nIf you would like to accept any object whatsoever in your hash, you can use\nL<C<Any>|/type/Any>!\n\n    my %h{Any};\n    %h{(now)} = \"This is an Instant\";\n    %h{(DateTime.now)} = \"This is a DateTime, which is not an Instant\";\n    %h{\"completely different\"} = \"Monty Python references are neither DateTimes nor Instants\";\n\nThere is a more concise syntax which uses binding.\n\n    my %h := :{ (now) => \"Instant\", (DateTime.now) => \"DateTime\" };\n\nThe binding is necessary because an object hash is about very solid, specific\nobjects, which is something that binding is great at keeping track of but about\nwhich assignment doesn't concern itself much.\n\nSince 6.d was released, L<C<Junction>s|/type/Junction> can also be used as hash\nkeys. The result will also be a L<C<Junction>|/type/Junction> of the same type used as key.\n\n    my %hash = %( a => 1, b => 2, c=> 3);\n    say %hash{\"a\"|\"c\"};   # OUTPUT: «any(1, 3)␤»\n    say %hash{\"b\"^\"c\"};   # OUTPUT: «one(2, 3)␤»\n    say %hash{\"a\" & \"c\"}; # OUTPUT: «all(1, 3)␤»\n\nIf a Junction of any kind is used to define a key, it will have the same effect\nof defining elements of the L<C<Junction>|/type/Junction> as separate keys:\n\n=for code\nmy %hash = %( \"a\"|\"b\" => 1, c => 2 );\nsay %hash{\"b\"|\"c\"};       # OUTPUT: «any(1, 2)␤»\n\n\n=head2 Constraint value types\n\nPlace a type object in-between the declarator and the name to constrain the type\nof all values of a L<C<Hash>|/type/Hash>.\n\n    my Int %h;\n    put %h<Goku>   = 900;\n\n    try {\n        %h<Vegeta> = \"string\";\n        CATCH { when X::TypeCheck::Binding { .message.put } }\n    }\n\n    # OUTPUT:\n    # 9001\n    # Type check failed in assignment to %h; expected Int but got Str (\"string\")\n\nYou can do the same by a more readable syntax.\n\n    my %h of Int; # the same as my Int %h\n\nIf you want to constraint the type of all keys of a L<C<Hash>|/type/Hash>, add C<{Type}> following\nthe name of variable.\n\n    my %h{Int};\n\nEven put these two constraints together.\n\n    my %h{Int} of Int;\n    put %h{21} = 42;\n\n    try {\n        %h{0} = \"String\";\n        CATCH { when X::TypeCheck::Binding { .message.put } }\n    }\n\n    try {\n        %h<string> = 42;\n        CATCH { when X::TypeCheck::Binding { .message.put } }\n    }\n\n    try {\n        %h<string> = \"String\";\n        CATCH { when X::TypeCheck::Binding { .message.put } }\n    }\n\n    # OUTPUT:\n    # 42\n    # Type check failed in binding to parameter 'assignval'; expected Int but got Str (\"String\")\n    # Type check failed in binding to parameter 'key'; expected Int but got Str (\"string\")\n    # Type check failed in binding to parameter 'key'; expected Int but got Str (\"string\")\n\n=head1 Looping over hash keys and values\n\nA common idiom for processing the elements in a hash is to loop over the\nkeys and values, for instance,\n\n    my %vowels = 'a' => 1, 'e' => 2, 'i' => 3, 'o' => 4, 'u' => 5;\n    for %vowels.kv -> $vowel, $index {\n      \"$vowel: $index\".say;\n    }\n\ngives output similar to this:\n\n=for code :lang<output>\na: 1\ne: 2\no: 4\nu: 5\ni: 3\n\nwhere we have used the C<kv> method to extract the keys and their respective\nvalues from the hash, so that we can pass these values into the loop.\n\nNote that the order of the keys and values printed cannot be relied upon; the\nelements of a hash are not always stored the same way in memory for different\nruns of the same program. In fact, since release 2018.05, the order is\nguaranteed to be different in every invocation.  Sometimes one wishes to process\nthe elements sorted on, e.g., the keys of the hash. If one wishes to print the\nlist of vowels in alphabetical order then one would write\n\n    my %vowels = 'a' => 1, 'e' => 2, 'i' => 3, 'o' => 4, 'u' => 5;\n    for %vowels.sort(*.key)>>.kv -> ($vowel, $index) {\n      \"$vowel: $index\".say;\n    }\n\nwhich prints\n\n=for code :lang<output>\na: 1\ne: 2\ni: 3\no: 4\nu: 5\n\nin alphabetical order as desired. To achieve this result, we sorted\nthe hash of vowels by key (C<%vowels.sort(*.key)>) which we then ask for its\nkeys and values by applying the C<.kv> method to each element via the unary\nC«>>» hyperoperator resulting in a L<C<List>|/type/List> of key/value lists.  To extract\nthe key/value the variables thus need to be wrapped in parentheses.\n\nAn alternative solution is to flatten the resulting list.  Then the key/value\npairs can be accessed in the same way as with plain C<.kv>:\n\n    my %vowels = 'a' => 1, 'e' => 2, 'i' => 3, 'o' => 4, 'u' => 5;\n    for %vowels.sort(*.key)>>.kv.flat -> $vowel, $index {\n      \"$vowel: $index\".say;\n    }\n\nYou can also loop over a L<C<Hash>|/type/Hash> using\nL<destructuring|/language/signatures#Destructuring_arguments>.\n\n=head2 In place editing of values\n\nThere may be times when you would like to modify the values of a hash while\niterating over them.\n\n    my %answers = illuminatus => 23, hitchhikers => 42;\n    # OUTPUT: «hitchhikers => 42, illuminatus => 23»\n    for %answers.values -> $v { $v += 10 }; # Fails\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::AdHoc: Cannot assign to a readonly variable or a value␤»\n\nThis is traditionally accomplished by sending both the key and the value as\nfollows.\n\n    my %answers = illuminatus => 23, hitchhikers => 42;\n    for %answers.kv -> $k,$v { %answers{$k} = $v + 10 };\n\nHowever, it is possible to leverage the signature of the block in order to\nspecify that you would like read-write access to the values.\n\n    my %answers = illuminatus => 23, hitchhikers => 42;\n    for %answers.values -> $v is rw { $v += 10 };\n\nIt is not possible directly to do in-place editing of hash keys, even in the\ncase of object hashes; however, a key can be deleted and a new key/value pair\nadded to achieve the same results. For example, given this hash:\n\n=begin code\nmy %h = a => 1, b => 2;\nfor %h.keys.sort -> $k {\n    # use sort to ease output comparisons\n    print \"$k => {%h{$k}}; \";\n}\nsay ''; # OUTPUT: «a => 1; b => 2; ␤»\n=end code\n\nreplace key 'b' with 'bb' but retain 'b's value as the new key's value:\n\n=begin code :preamble<my %h>\nfor %h.keys -> $k {\n    if $k eq 'b' {\n        %h<bb> = %h{$k}:delete;\n    }\n}\nfor %h.keys.sort -> $k {\n    print \"$k => {%h{$k}}; \";\n}\nsay ''; # OUTPUT: «a => 1; bb => 2; ␤»\n=end code\n\n=end pod\n"
  },
  {
    "path": "doc/Language/haskell-to-p6.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"migration\")\n\n=TITLE Haskell to Raku - nutshell\n\n=SUBTITLE Learning Raku from Haskell, in a nutshell\n\nHaskell and Raku are I<very> different languages. This is obvious.\nHowever, that does not mean there are not similarities or shared ideas!\nThis page attempts to get a Haskell user up and running with Raku. The\nHaskell user may find that they need not abandon all of their Haskelly\nthoughts while scripting in Raku.\n\nNote that this should not be mistaken for a beginner tutorial or overview of\nRaku; it is intended as a technical reference for Raku learners with a\nstrong Haskell background.\n\n\n=head1 Types\n\n=head2 Types vs values\n\nIn Haskell, you have type level programming and then value level programming.\n\n    =begin code :lang<haskell>\n    plusTwo :: Integer -> Integer   -- Types\n    plusTwo x = x + 2               -- Values\n    =end code\n\nYou do not mix types and values in Haskell like the below\n\n    =begin code :lang<haskell>\n    plusTwo 2          -- This is valid\n    plusTwo Integer    -- This is not valid\n    =end code\n\nIn Raku, types (AKA type objects) live on the same level as values\n\n    =begin code\n    sub plus-two(Int $x --> Int) { $x + 2 }\n\n    plus-two(2);    # This is valid\n    plus-two(Int);  # This is valid\n    =end code\n\nI will illustrate this unique aspect of Raku with one more example:\n\n    =begin code\n    multi is-string(Str $ --> True) {}\n    multi is-string(Any $ --> False) {}\n\n    is-string('hello');    #True\n    is-string(4);          #False\n    =end code\n\n=head2 Maybe\n\nIn Haskell, you have a Maybe type that allows you to forgo the worry of null types.\nLet's say you have a hypothetical function that parses a String to an Integer:\n\n    =begin code :lang<haskell>\n    parseInt :: String -> Maybe Integer\n\n    case parseInt myString of\n      Just x  -> x\n      Nothing -> 0\n    =end code\n\nIn Raku, since type objects coexist with regular objects, we have the concept\nof Defined and Undefined objects. Plain type objects are undefined while\ninstantiated objects are defined.\n\n    =begin code\n    sub parse-int(Str $s --> Int) { ... }\n\n    my $string = {...};\n    given parse-int($string) {\n      when Int:D { $_ }\n      when Int:U { 0 }\n    }\n    =end code\n\nSo in Raku we have type constraints that indicate the definedness of a type. These are\n\n    =begin code\n    Int:D; # This is a defined Int.\n    Int:U; # This is an undefined Int, AKA a type object\n    Int:_; # This is either defined or undefined.\n    =end code\n\nIf we wanted to be explicit in the above example (probably a good idea), we could add\nthe C<:_> constraint on the return type. This would let the user know that they should account\nfor both defined and undefined return values. We could also use other methods and constructs\nthat specifically test for definedness.\n\n    =begin code\n    sub parse-int(Str $s --> Int:_) { ... }\n\n    # One way to do it\n    my $string = {...};\n    given parse-int($string) {\n      when Int:D { $_ }\n      when Int:U { 0 }\n    }\n\n    # Another way to do it\n    my Int $number = parse-int($string);\n    if $number.defined { $number } else { 0 }\n\n\n    # A better way\n    with parse-int($string) { $_ } else { 0 }\n\n    # With the defined-or operator\n    parse-int($string) // 0\n    =end code\n\nThe C<with> operator that you see above is like C<if>, except it explicitly tests for definedness and then\npasses the result to the following block. Similarly, C<without> tests that the object is undefined and also\npasses the result to the following block.\n\nFor more natural control flow with undefined and defined types, Raku introduces C<andthen> and C<orelse>.\n\n    =begin code\n    sub parse-int(Str $s --> Int:_) { ... }\n\n    my $string = {...};\n    my $result = parse-int($string) orelse 0;\n\n    sub hello() { say 'hi' }\n    hello() andthen say 'bye';\n    =end code\n\n=begin comment\nTODO: include a better example for andthen that makes sense. Maybe using promise objects?\n=end comment\n\nSo in practice, Raku does not have the concept of a null type, but rather of\ndefined or undefined types.\n\n=head2 Data definitions\n\nRaku is fundamentally an object oriented language. However, it also gives you\nthe freedom to write in virtually any paradigm you wish. If you only want to\npure functions that take an object and return a new object, you can certainly do\nso.\n\nHere is a Haskell code example:\n\n    =begin code :lang<haskell>\n    data Point = Point x y\n\n    moveUp :: Point -> Point\n    moveUp (Point x y) = Point x (y + 1)\n    =end code\n\nAnd an equivalent Raku example:\n\n    =begin code\n    class Point { has $.x; has $.y; }\n\n    sub move-up(Point $p --> Point) {\n      Point.new(x => $p.x, y => $p.y + 1)\n    }\n    =end code\n\nThe code illustrated above is an example of a\nL<Product Type|https://wiki.haskell.org/Algebraic_data_type>. If instead you'd like to\nwrite a Sum Type, there is not an exact equivalent in Raku. The closest thing\nwould be an L<Enum|/language/typesystem#enum>.\n\n    =begin code :lang<haskell>\n    data Animal = Dog | Cat | Bird | Horse\n\n    testAnimal :: Animal -> String\n    testAnimal Dog   = \"Woof\"\n    testAnimal Horse = \"Neigh\"\n    =end code\n\nAlthough it does not fit the same exact use cases, it can be used in putting\nconstraints on types.\n\n    =begin code\n    enum Animal < Dog Cat Bird Horse >;\n\n    proto test-animal( Animal        ) {*}\n    multi test-animal( Dog           ) { 'Woof' }\n    multi test-animal( Animal::Horse ) { 'Neigh'  }   # more explicit\n\n    say test-animal Animal::Dog;                          # more explicit\n    say test-animal Horse;\n    =end code\n\n=head2 Type aliases and subsets\n\nIn Haskell, you can alias an existing type to simply increase clarity of intent\nand re-use existing types.\n\n    =begin code :lang<haskell>\n    type Name = String\n\n    fullName :: Name -> Name -> Name\n    fullName first last = first ++ last\n    =end code\n\nThe equivalent in Raku is the following.\n\n    =begin code\n    my constant Name = Str;\n\n    sub full-name ( Name \\first, Name \\last --> Name ) { first ~ last }\n    =end code\n\nIt should be noted that in Raku, one can also create a subset of an existing type.\n\n    =begin code\n    subset Name of Str where *.chars < 20;\n\n    sub full-name(Name $first, Name $last) {\n      $first ~ $last\n    }\n\n    full-name(\"12345678901234567890111\", \"Smith\") # This does not compile, as the first parameter\n                                                  # doesn't fit the Name type\n    =end code\n\n=head2 Typeclasses\n\nTODO\n\n=begin comment\nexplain how Raku roles compare to Haskell typeclasses\n=end comment\n\n=head1 Functions\n\n=head2 Definitions and signatures\n\n=head3 Pattern Matching\n\nHaskell makes heavy use of pattern matching in function definitions.\n\n    =begin code :lang<haskell>\n    greeting :: String -> String\n    greeting  \"\"   = \"Hello, World!\"\n    greeting \"bub\" = \"Hey bub.\"\n    greeting  name = \"Hello, \" ++ name ++ \"!\"\n    =end code\n\nRaku does this as well! You just use the C<multi> keyword to signify that it is a multiple dispatch\nfunction.\n\n    =begin code\n    proto greeting ( Str   --> Str ) {*}\n    multi greeting ( \"\"    --> \"Hello, World!\" ) {}\n    multi greeting ( \"bub\" --> \"Hey bub.\" ) {}\n    multi greeting ( \\name ) { \"Hello, \" ~ name ~ \"!\" }\n    =end code\n\nThe C<proto> declarator is not necessary, but can sometimes aid in making sure that all multis\nfollow your business rules. Using a variable name in the signature of the proto would provide\nmore information in error messages, and for introspection.\n\n    =begin code\n    proto greeting ( Str \\name --> Str ) {*}\n\n    say &greeting.signature;                  # OUTPUT: «(Str \\name --> Str)␤»\n    =end code\n\nAn interesting thing to note in the Raku code above is that passing values like C<'bub'> as a\nfunction parameter is just syntax sugar for a C<where> guard.\n\n=head3 Guards\n\nUsing the example from the \"Pattern Matching\" section of this page, you can see the guards that are\nused behind the scenes to constrain our function arguments.\n\n    =begin code\n    multi greeting ( \"\"    --> \"Hello, World!\" ) {}\n    multi greeting ( \"bub\" --> \"Hey bub.\" ) {}\n\n    # The above is the same as the below\n\n    multi greeting(Str \\name where ''    ) {'Hello, World!'}\n    multi greeting(Str \\name where 'bub' ) {'Hey bub.'}\n\n    # The above is the same as the below, again.\n\n    multi greeting(Str \\name where $_ ~~ ''   ) {'Hello, World!'}\n    multi greeting(Str \\name where $_ ~~ 'bub') {'Hey bub.'}\n    =end code\n\nC<$_> is known as the topic variable. It assumes the form of whatever is\nappropriate. The smartmatch operator C<~~> figures out the best way to determine\nif the left matches the right, be it number ranges, strings, etc. Our three\nexamples above go from most sugared (top), to least sugared (bottom).\n\nThe bottom examples above could be wrapped in curly braces, making it more\nobvious that it is a code block. Note that a where clause may also take an\nexplicit L<C<Callable>|/type/Callable>.\n\n    =begin code :preamble<sub some-subroutine {};>\n    multi greeting(Str \\name where { $_ ~~ '' } ) {'Hello, World!'}\n\n    multi greeting(Str \\name where -> $thing { $thing ~~ '' } ) {'Hello, World!'}\n\n    multi greeting ( Str \\name where { Bool.pick } --> 'True' ){}\n\n    multi greeting ( Str \\name where &some-subroutine ){…}\n    =end code\n\nIf you read the section in this page on subsets, you'll notice that \"where\" is used in the making of\nsubsets as well as here. The usage of \"where\" in both areas is exactly the same.\n\nWhen using C<where>, note that the order of definition is important, just like in Haskell.\n\n    =begin code\n    multi greeting ( Str \\name where '' --> 'Hello, World!' ){}\n    multi greeting ( Str \\name where { Bool.pick } --> 'True' ){}\n    multi greeting ( Str \\name where 'bub' --> 'Hey, bub.' ){}\n\n    say greeting ''   ; # will never say True\n    say greeting 'bub'; # about 50% of the time it will say True\n    =end code\n\n=head2 Argument Deconstruction\n\nTODO\n\n=head2 Currying / Partial Application\n\nHaskell functions are in curried form by default and as such they allow partial application directly.\n\n    =begin code :lang<haskell>\n    plus : Int -> Int -> Int\n    plus a b = a + b\n\n    plusTwo = plus 2\n    =end code\n\nIn raku, partial application can be achieved by C<assuming> method on any L<C<Callable>|/type/Callable> object.\n\n    =begin code\n    sub plus(Int $i, Int $j --> Int) { return $i + $j; }\n\n    my &plus-two = &plus.assuming(2, *);\n    =end code\n\n=head2 Composing\n\nTODO\n\nshow function composition operator. Maybe explain a more native Raku way to do this though.\n\n=head1 Case / matching\n\nHaskell makes heavy use of case matching like the below:\n\n    =begin code :lang<haskell>\n    case number of\n      2 -> \"two\"\n      4 -> \"four\"\n      8 -> \"eight\"\n      _ -> \"don't care\"\n    =end code\n\nIn Raku you can achieve this same thing with the given/when structure:\n\n    =begin code\n    my $number = {...};\n    given $number {\n      when 2  { \"two\" }\n      when 4  { \"four\" }\n      when 8  { \"eight\" }\n      default { \"don't care\" }\n    }\n    =end code\n\nNote that the order of the C<when>'s is also significant, just like with the C<where>'s in the\nguard section of this page.\n\n=head1 Lists\n\nTODO\n\nexplain differences between Raku Arrays, Sequences, and Lists. Explain data shapes in regards\nto the C<@> sigil. Explain how you can convert an Array to a flattened list of objects with C<|@>\n\ndata shapes become quite intuitive, but it takes a bit of practice.\n\n=head2 List comprehensions\n\nThere are no explicit list comprehensions in Raku. But you can achieve list comprehensions\na couple of different ways.\n\nHere is a trivial example in Haskell:\n\n    =begin code :lang<haskell>\n    evens = [ x | x <- [0..100], even x ]\n    =end code\n\nAnd now in Raku:\n\n    =begin code\n    # using `if` and `for`\n    my @evens = ($_ if $_ %% 2 for 0..100);\n\n    # using gather/take to build a Seq\n    my $evens = gather for 0..100 { take $_ if $_ %% 2 };\n\n    # using gather/take to build an Array\n    my @evens = gather for 0..100 { take $_ if $_ %% 2 };\n    =end code\n\nSince C<for> is always eager it is generally better to use C<map> or C<grep> which\nwill inherit the laziness or eagerness of its list argument.\n\n    =begin code\n    my @evens = map { $_ if $_ %% 2 }, 0..100;\n\n    my @evens = grep { $_ %% 2 }, 0..100;\n\n    # using a Whatever lambda\n    my @evens = grep  * %% 2,  0..100;\n    =end code\n\nHere is the creation of tuples in Haskell:\n\n    =begin code :lang<haskell>\n    tuples = [(i,j) | i <- [1,2],\n                      j <- [1..4] ]\n    -- [(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)]\n    =end code\n\nAnd in Raku:\n\n    =begin code\n    my @tuples = 1,2  X  1..4;\n    # [(1,1), (1,2), (1,3), (1,4), (2,1), (2,2), (2,3), (2,4)]\n    =end code\n\nSee this design document for more information on what kinds of list comprehensions are possible\nin: L<https://github.com/Raku/old-design-docs/blob/master/S04-control.pod#The_do-once_loop>.\n\nAs you can see, when you get into some more advanced Haskell list comprehensions, Raku\ndoes not translate exactly the same, but it's possible to do the same things, nonetheless.\n\n=head2 Fold\n\nFold in Haskell is called Reduce in Raku.\n\n    =begin code :lang<haskell>\n    mySum = foldl (+) 0 numList\n    =end code\n\n    =begin code\n    my @numbers = {...};\n    reduce { $^a + $^b }, 0, |@numbers;\n    @numbers.reduce: {$^a + $^b}\n    =end code\n\nHowever, in Raku, if you want to use an infix operator (+ - / % etc)\nthere is a nice little helper called the Reduction metaoperator.\n\n    =begin code\n    my @numbers = {...};\n    [+] @numbers     # This is the same\n    [+] 0, |@numbers # as this\n    =end code\n\nIt inserts the operator in between all values in the list and produces a result, just like Fold.\n\nIn Haskell you, you have foldl and foldr. In Raku, this difference is determined by the\nassociativity attached to the operator/subroutine.\n\n    =begin code\n    sub two-elem-list ( \\a, \\b ) { ( a, b ) }\n\n    # you can use a subroutine as an infix operator\n    say 'a' [&two-elem-list] 'b'; # OUTPUT: «(a b)␤»\n\n    # as the reduction prefix metaoperator takes an infix operator, it will work there too;\n    [[&two-elem-list]] 1..5;           # OUTPUT: «((((1 2) 3) 4) 5)␤»\n    say (1..5).reduce: &two-elem-list; # OUTPUT: «((((1 2) 3) 4) 5)␤»\n\n    # right associative\n    sub right-two-elem-list( \\a, \\b ) is assoc<right> { ( a, b ) }\n    say (1..5).reduce: &right-two-elem-list; # OUTPUT: «(1 (2 (3 (4 5))))␤»\n\n    # XXX there is possibly a bug here as this currently doesn't look at\n    # XXX the associativity of &right-two-elem-list and just always does left assoc\n    say [[&right-two-elem-list]] 1..5;\n\n    # chaining\n    say [<] 1..5;            # OUTPUT: «True␤»\n    say (1..5).reduce: &[<]; # OUTPUT: «True␤»\n    =end code\n\n=head2 C<takeWhile>\n\nThe C<takeWhile> function in Haskell runs over a list returning all elements\nuntil a condition is met:\n\n=for code :lang<haskell>\nfibs = 0 : 1 : zipWith (+) fibs (tail fibs)\ntakeWhile (<20) fibs -- Returns [0,1,1,2,3,5,8,13]\n\nThere's no single equivalent function in Raku; several alternatives have\nbeen proposed in the\nL<issue that originated this text|https://github.com/Raku/doc/issues/3932>.\nThis would be one of the alternatives:\n\n=for code\n[1, 2, 3, 40, 50, 60, 7, 8, 9] ...^ !(* < 10)\n\nAlthough it's not a single function, it's essentially a specific way of using\nthe L<sequence operator|/language/operators#infix_...> using the caret for\nexcluding the last term, and using a condition for ending the sequence. This\nspecific example would be equivalent to\n\n=for code :lang<haskell>\ntakeWhile (<10) [1, 2, 3, 40, 50, 60, 7, 8, 9]\n\n=head2 Map\n\nTODO\n\n=head2 Ranges\n\nHaskell and Raku both allow you to specify ranges of values.\n\n    =begin code :lang<haskell>\n    myRange1 = 10..100\n    myRange2 = 1..        -- Infinite\n    myRange3 = 'a'..'h'   -- Letters work too\n    =end code\n\n    =begin code\n    my $range1 = 10..100;\n    my $range2 = 1..*;      # Infinite\n    my $range3 = 'a'..'h';  # Letters work too\n    =end code\n\n=head2 Laziness vs eagerness\n\nIn the examples above, you have the concept of laziness displayed very plainly. Raku has laziness\nonly where it makes the most sense. For example, in the range 10..100, this is eager because it has\na definite end. If a list does not have a definite end, then the list should clearly be lazy.\n\n    =begin code\n    (1 .. 100).is-lazy; # False\n    (1 .. Inf).is-lazy; # True\n    =end code\n\nThese are the \"sane defaults\" that Raku takes pride in. But they are still defaults and can be\nchanged into one or the other.\n\n    =begin code\n    (1 .. 100).lazy.is-lazy;       # True\n    (1 .. 100).lazy.eager.is-lazy; # False\n    =end code\n\n=head1 Contexts (let-in / where)\n\nTODO\n\nexplain how C<given/when> and C<with/without> and C<for loops> open lexical scopes with the argument as the context.\n\ncompare it to let/in and where constructs maybe?\n\n=head1 Parsers\n\n=head2 Parser combinators vs grammars\n\nTODO\n\n=head1 Tail Call Optimization or Tail Call Elimination\n\nHaskell and many other functional programming languages use tail call optimization, also\nsometimes called tail call elimination, to remove the stack overhead of some types\nof recursive function calls.\n\nThere is nothing in the Raku language specification forbidding the implementation of this\nclass of optimization, but no current implementation has it.\n\nPlease note that many Haskell looping constructs use recursive function calls.  Haskell programs\nwould encounter stack overflow errors more often without tail call optimization. The standard\nRaku looping constructs are not built on recursive function calls, which makes the feature\nless important.\n\n=begin comment\n\n### Guidelines for contributions:\n\nHeaders should contain the text that a Haskell user might search for, since\nthose headings will be in the Table of Contents generated for the top of\nthe document.\n\nWe use POD =item instead of =head3 or =head4 for identical bits that need not\nappear in the table of contents.\n\nThis article does not describe in detail language features that Haskell doesn't\nhave at all, instead referring to other documents.\n\nExample code and links to other documents should be favored over long\nexplanations of details better found elsewhere.\n\nFinally, if a real user asks a Haskell to Raku question that is not being\nanswered here, please add it to the document. Even if we do not have a good\nanswer yet, that will be better than losing the information about a real need.\n\n=end comment\n\n=end pod\n"
  },
  {
    "path": "doc/Language/intro.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"beginning\")\n\n=TITLE Brief introduction\n\n=SUBTITLE Using Raku official documentation\n\nThis official documentation covers a variety of presentation styles.\nSee the main L</introduction> and L</reference> pages for a list of documents in\nthe following styles.\n\n=begin item\nRaku has a high level of L<unicode support|/language/unicode>, including\nmany unicode operators. While this may be daunting for those coming from an\nASCII background, we have some L<help|/language/unicode#Entering_unicode_codepoints_and_codepoint_sequences> introducing\nusers to how to use it in your program. Finally, if you would really prefer\nto use ASCII, you can in L<most cases|/language/unicode_ascii>.\n=end item\n\n=begin item\nFor programmers with experience in other languages, there are a number of\nB<Migration Guides> that compare and contrast the features of Raku with other\nlanguages, including Perl, JavaScript, and Haskell.\n=end item\n\n=begin item\nL<C<Signatures>|/type/Signature> - Each routine, which includes subroutines and\nmethods, has a signature. Understanding the information given in the signature\nof a C<sub> or C<method> provides a quick way to grasp the operation and effect\nof the routine, and if provided in the signature, this may not be called out\nexplicitly in the text.\n=end item\n\n=begin item\nL<C<Containers>|/language/containers> - Variables, which are like the nouns of\na computer language, are containers in which information is stored. The first\ncharacter in the name of a container, called a sigil, conveys information about\nthe container.  For example, the C<$> of C<$my-variable>, or\nC<@> of C<@an-array-of-things>, or C<%> of C<%scores-by-name>,\n\nI<Note you can store an\nL<C<Array>|/type/Array> in a C<$> container and treat it as a single object.>\n=end item\n\n=begin item\nL<C<Classes and Roles>|/language/classtut> - Raku is fundamentally based on\nobjects, which are described in terms of classes and roles. Raku, unlike some\nlanguages, does not B<impose> object-oriented programming practices, and useful\nprograms can be written in a procedural style. However,\ncomplex software, such as the Rakudo compiler of Raku, is made much simpler\nby writing in object-oriented idioms, which is why the Raku documentation is\nmore easily understood by reviewing what a class is and what a role is.\n=end item\n\n=begin item\nL<C<Traps to Avoid>|/language/traps> - Several common assumptions lead to code\nthat does not work as the programmer intended. This section identifies some\nof them.\n=end item\n\n=begin item\nThere are a number of L<C<useful resources>|https://raku.org> listed\non the raku.org site. These include articles, books, slide\npresentations, and videos.\n=end item\n\n=begin item\nYou will see examples throughout the document, like so:\n\n=for code\nmy @a = 1, 2, 3;\n@a»++;\nsay @a;             # OUTPUT: «[2 3 4]␤»\n\nNote on the last line, there is a comment, starting with C<# OUTPUT:>, that shows what the example outputs.\nThe output is wrapped in C<«»> quotes and may include a C<␤>, which\nis the Unicode character \"Symbol for Newline\", to indicate where in the actual output a literal newline would\nappear. (C<«»> quotes are also a valid L<quoting construct|/language/quoting> in Raku,\nbut with special semantics.)\n\n=end item\n\n=end pod\n"
  },
  {
    "path": "doc/Language/io-guide.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Input/Output the definitive guide\n\n=SUBTITLE Correctly use Raku IO\n\n=head1 The basics\n\nThe vast majority of common IO work is done by the L<C<IO::Path>|/type/IO::Path>\ntype. If you want to read from or write to a file in some form or shape, this\nis the class you want. It abstracts away the details of filehandles\n(or \"file descriptors\") and so you mostly don't even have to think about them.\n\nBehind the scenes, L<C<IO::Path>|/type/IO::Path> works with\nL<C<IO::Handle>|/type/IO::Handle>, a class which you can use directly if you\nneed a bit more control than what L<C<IO::Path>|/type/IO::Path> provides. When\nworking with other processes, e.g. via L<C<Proc>|/type/Proc> or\nL<C<Proc::Async>|/type/Proc::Async> types, you'll also be dealing with a\nI<subclass> of L<C<IO::Handle>|/type/IO::Handle>: the L<C<IO::Pipe>|/type/IO::Pipe>.\n\nLastly, you have the L<C<IO::CatHandle>|/type/IO::CatHandle>, as well as\nL<C<IO::Spec>|/type/IO::Spec> and its subclasses, that you'll rarely, if ever,\nuse directly. These classes give you advanced features, such as operating on\nmultiple files as one handle, or low-level path manipulations.\n\nAlong with all these classes, Raku provides several subroutines that\nlet you indirectly work with these classes. These come in handy if you like\nfunctional programming style or in Raku one liners.\n\nWhile L<C<IO::Socket>|/type/IO::Socket> and its subclasses also have to do with\nInput and Output, this guide does not cover them.\n\n=head1 Navigating paths\n\n=head2 What's an IO::Path anyway?\n\nTo represent paths as either files or directories, use\nL<C<IO::Path>|/type/IO::Path> type. The simplest way to obtain an object of that\ntype is to coerce a L<C<Str>|/type/Str> by calling the L«C<.IO>|/routine/IO» method\non it:\n\n    say 'my-file.txt'.IO; # OUTPUT: «\"my-file.txt\".IO␤»\n\nIt may seem like something is missing here—there is no volume or absolute\npath involved—but that information is actually present in the object. You can\nsee it by using L«C<.raku>|/routine/raku» method:\n\n    say 'my-file.txt'.IO.raku;\n    # OUTPUT: «IO::Path.new(\"my-file.txt\", :SPEC(IO::Spec::Unix), :CWD(\"/home/camelia\"))␤»\n\nThe two extra attributes—C<SPEC> and C<CWD>—specify what type of operating\nsystem semantics the path should use as well as the \"current working directory\"\nfor the path, i.e. if it's a relative path, then it's relative to that\ndirectory.\n\nThis means that regardless of how you made one, an L<C<IO::Path>|/type/IO::Path>\nobject technically always refers to an absolute path. This is why its\nL«C<.absolute>|/routine/absolute» and L«C<.relative>|/routine/relative»\nmethods return L<C<Str>|/type/Str> objects and they are the correct way to\nstringify a path.\n\nHowever, don't be in a rush to stringify anything. Pass paths around as\nL<C<IO::Path>|/type/IO::Path> objects. All the routines that operate on paths\ncan handle them, so there's no need to convert them.\n\n=head2 Path parts\n\nGiven a local file name, it's very easy to get its components.\nFor example, we have a file, \"financial.data\", in some\ndirectory, \"/usr/local/data\". Use Raku to analyze its path:\n\n=begin code\nmy $fname = \"financial.data\";\n# Stringify the full path name\nmy $f = $fname.IO.absolute;\nsay $f;\n#   OUTPUT: «/usr/local/data/financial.data␤»\n# Stringify the path's parts:\nsay $f.IO.dirname;                       # OUTPUT: «/usr/local/data␤»\nsay $f.IO.basename;                      # OUTPUT: «financial.data␤»\n# And the basename's parts:\n# Use a method for the extension:\nsay $f.IO.extension;                     # OUTPUT: «data␤»\n# Remove the extension by redefining it:\nsay ($f.IO.extension(\"\")).IO.basename;   # OUTPUT: «financial␤»\n=end code\n\n=head2 Working with files\n\n=head3 Writing into files\n\n=head4 Writing new content\n\nLet's make some files and write and read data from them! The\nL«C<spurt>|/routine/spurt» and L«C<slurp>|/routine/slurp» routines write and\nread the data in one chunk respectively. Unless you're working with very large\nfiles that are difficult to store entirely in memory all at the same time,\nthese two routines are for you.\n\n=for code\n\"my-file.txt\".IO.spurt: \"I ♥ Raku!\";\n\nThe code above creates a file named C<my-file.txt> in the current directory\nand then writes text C<I ♥ Raku!> into it. If Raku is your first language,\ncelebrate your accomplishment! Try to open the file you created with a\ntext editor to verify what you wrote with your program. If you already know\nsome other language, you may be wondering if this guide missed anything like\nhandling encoding or error conditions.\n\nHowever, that is all the code you need. The string will be encoded in C<utf-8>\nencoding by default and the errors are handled via the L<C<Failure>|/type/Failure>\nmechanism: these are exceptions you can handle using regular conditionals. In\nthis case, we're letting all potential L<C<Failure>|/type/Failure>s get sunk\nafter the call and so any L<C<Exceptions>|/type/Exception> they contain will be\nthrown.\n\n=head4 Appending content\n\nIf you wanted to add more content to the file we created in the previous\nsection, you could note the L«C<spurt> documentation|/routine/spurt» mentions\nC<:append> as one of its argument options. However, for finer control, let's\nget ourselves an L<C<IO::Handle>|/type/IO::Handle> to work with:\n\n=for code\nmy $fh = 'my-file.txt'.IO.open: :a;\n$fh.print: \"I count: \";\n$fh.print: \"$_ \" for ^10;\n$fh.close;\n\nThe L«C<.open>|/routine/open» method call opens our L<C<IO::Path>|/type/IO::Path>\nand returns an L<C<IO::Handle>|/type/IO::Handle>. We passed C<:a> as argument, to\nindicate we want to open the file for writing in append mode.\n\nIn the next two lines of code, we use the usual L«C<.print>|/routine/print»\nmethod on that L<C<IO::Handle>|/type/IO::Handle> to print a line with 11 pieces\nof text (the C<'I count: '> string and 10 numbers). Note that, once again,\nL<C<Failure>|/type/Failure> mechanism takes care of all the error checking for us.\nIf the L«C<.open>|/routine/open» fails, it returns a L<C<Failure>|/type/Failure>,\nwhich will throw when we attempt to call method the L«C<.print>|/routine/print»\non it.\n\nFinally, we close the L<C<IO::Handle>|/type/IO::Handle> by calling the\nL«C<.close>|/routine/close» method on it. It is\nI<important that you do it>, especially in large programs or ones that deal\nwith a lot of files, as many systems have limits to how many files a program\ncan have open at the same time. If you don't close your handles, eventually\nyou'll reach that limit and the L«C<.open>|/routine/open» call will fail.\nNote that unlike some other languages, Raku does not use reference counting,\nso the filehandles B<are NOT closed> when the scope they're defined in is left.\nThey will be closed only when they're garbage collected and failing to close\nthe handles may cause your program to reach the file limit I<before> the open\nhandles get a chance to get garbage collected.\n\n=head3 Reading from files\n\n=head4 Using IO::Path\n\nWe've seen in previous sections that writing stuff to files is a single-line\nof code in Raku. Reading from them, is similarly easy:\n\n=for code\nsay 'my-file.txt'.IO.slurp;        # OUTPUT: «I ♥ Raku!␤»\nsay 'my-file.txt'.IO.slurp: :bin;  # OUTPUT: «Buf[uint8]:0x<49 20 E2 99 A5 20 52 61 6B 75 21>␤»\n\nThe L«C<.slurp>|/routine/slurp» method reads entire contents of the file\nand returns them as a single L<C<Str>|/type/Str> object, or as a L<C<Buf>|/type/Buf>\nobject, if binary mode was requested, by specifying C<:bin> named argument.\n\nSince L«slurping|/routine/slurp» loads the entire file into memory, it's not\nideal for working with huge files.\n\nThe L<C<IO::Path>|/type/IO::Path> type offers two other handy methods:\nL«C<.words>|/type/IO::Path#method_words» and\nL«C<.lines>|/type/IO::Path#method_lines» that lazily read the file in smaller\nchunks and return L<C<Seq>|/type/Seq> objects that (by default) don't keep\nalready-consumed values around.\n\nHere's an example that finds lines in a text file that mention Raku and prints\nthem out. Despite the file itself being too large to fit into available\nL<RAM|https://en.wikipedia.org/wiki/Random-access_memory>, the program will\nnot have any issues running, as the contents are processed in small chunks:\n\n=for code\n.say for '500-PetaByte-File.txt'.IO.lines.grep: *.contains: 'Raku';\n\nHere's another example that prints the first 100 words from a file, without\nloading it entirely:\n\n=for code\n.say for '500-PetaByte-File.txt'.IO.words: 100\n\nNote that we did this by passing a limit argument to\nL«C<.words>|/type/IO::Path#method_words» instead of, say, using\nL<a list indexing operation|/language/operators#index-entry-array_indexing_operator-array_subscript_operator-array_indexing_operator>.\nThe reason for that is there's still a filehandle in use under the hood, and\nuntil you fully consume the returned L<C<Seq>|/type/Seq>, the handle will remain open.\nIf nothing references the L<C<Seq>|/type/Seq>, eventually the handle will get closed, during\na garbage collection run, but in large programs that work with a lot of files,\nit's best to ensure all the handles get closed right away. So, you should\nalways ensure the L<C<Seq>|/type/Seq> from L<C<IO::Path>|/type/IO::Path>'s\nL«C<.words>|/type/IO::Path#method_words» and\nL«C<.lines>|/type/IO::Path#method_lines» methods is\nL<fully reified|/language/glossary#Reify>; and the limit argument\nis there to help you with that.\n\n=head4 Using IO::Handle\n\nYou can read from files using the L<C<IO::Handle>|/type/IO::Handle>\ntype; this gives you a finer control over the process.\n\n=begin code\ngiven 'some-file.txt'.IO.open {\n    say .readchars: 8;  # OUTPUT: «I ♥ Raku␤»\n    .seek: 1, SeekFromCurrent;\n    say .readchars: 15;  # OUTPUT: «I ♥ Programming␤»\n    .close\n}\n=end code\n\nThe L<C<IO::Handle>|/type/IO::Handle> gives you\nL«.read|/type/IO::Handle#method_read»,\nL«.readchars|/type/IO::Handle#method_readchars»,\nL«.get|/type/IO::Handle#routine_get»,\nL«.getc|/type/IO::Handle#routine_getc»,\nL«.words|/type/IO::Handle#routine_words»,\nL«.lines|/type/IO::Handle#routine_lines»,\nL«.slurp|/type/IO::Handle#method_slurp»,\nL«.comb|/type/IO::Handle#method_comb»,\nL«.split|/type/IO::Handle#method_split»,\nand L«.Supply|/type/IO::Handle#method_Supply»\nmethods to read data from it. Plenty of\noptions; and the catch is you need to close the handle when you're done with it.\n\nUnlike some languages, the handle won't get automatically closed when the\nscope it's defined in is left. Instead, it'll remain open until it's garbage\ncollected. To make the closing business easier, some of the methods let you\nspecify a C<:close> argument, you can also use the\nL«C<will leave> trait|/language/phasers#index-entry-will_trait», or the\nC<does auto-close> trait provided by the\nL«C<Trait::IO>|https://raku.land/zef:raku-community-modules/Trait::IO» module.\n\n=head1 The wrong way to do things\n\nThis section describes how NOT to do Raku IO.\n\n=head2 Leave $*SPEC alone\n\nYou may have heard of L«C<$*SPEC>|/language/variables#Dynamic_variables» and\nseen some code or books show its usage for splitting and joining path fragments.\nSome of the routine names it provides may even look familiar to what you've\nused in other languages.\n\nHowever, unless you're writing your own IO framework,\nyou almost never need to use L«C<$*SPEC>|/language/variables#Dynamic_variables»\ndirectly. L«C<$*SPEC>|/language/variables#Dynamic_variables» provides low-level\nstuff and its use will not only make your code tough to read, you'll likely\nintroduce security issues (e.g. null characters)!\n\nThe L«C<IO::Path>|/type/IO::Path» type is the workhorse of Raku world. It\ncaters to all the path manipulation needs as well as provides shortcut routines\nthat let you avoid dealing with filehandles. Use that instead of the\nL«C<$*SPEC>|/language/variables#Dynamic_variables» stuff.\n\nTip: you can join path parts with C</> and feed them to\nL«C<IO::Path>|/type/IO::Path»'s routines; they'll still do The Right Thing™\nwith them, regardless of the operating system.\n\n=for code :preamble<my $file>\n# WRONG!! TOO MUCH WORK!\nmy $fh = open $*SPEC.catpath: '', 'foo/bar', $file;\nmy $data = $fh.slurp;\n$fh.close;\n\n=for code :preamble<my $file>\n# RIGHT! Use IO::Path to do all the dirty work\nmy $data = 'foo/bar'.IO.add($file).slurp;\n\nHowever, it's fine to use it for things not otherwise provided by L<C<IO::Path>|/type/IO::Path>.\nFor example, the L<C«.devnull» method|/routine/devnull>:\n\n=for code\n{\n    temp $*OUT = open :w, $*SPEC.devnull;\n    say \"In space no one can hear you scream!\";\n}\nsay \"Hello\";\n\n=head2 Stringifying IO::Path\n\nDon't use the C<.Str> method to stringify L«C<IO::Path>|/type/IO::Path» objects,\nunless you just want to display them somewhere for information purposes or\nsomething. The C<.Str> method returns whatever basic path string the\nL«C<IO::Path>|/type/IO::Path» was instantiated with. It doesn't consider the\nvalue of the L«C<$.CWD> attribute|/type/IO::Path#attribute_CWD». For example,\nthis code is broken:\n\n=for code\nmy $path = 'foo'.IO;\nchdir 'bar';\n# WRONG!! .Str DOES NOT USE $.CWD!\nrun <tar -cvvf archive.tar>, $path.Str;\n\nThe L«C<chdir>|/routine/chdir» call changed the value of the current directory,\nbut the C<$path> we created is relative to the directory before that change.\n\nHowever, the L«C<IO::Path>|/type/IO::Path» object I<does> know what directory\nit's relative to. We just need to use L«C<.absolute>|/routine/absolute» or\nL«C<.relative>|/routine/relative» to stringify the object. Both routines return\na L«C<Str>|/type/Str» object; they only differ in whether the result is an\nabsolute or relative path. So, we can fix our code like this:\n\n=for code\nmy $path = 'foo'.IO;\nchdir 'bar';\n# RIGHT!! .absolute does consider the value of $.CWD!\nrun <tar -cvvf archive.tar>, $path.absolute;\n# Also good:\nrun <tar -cvvf archive.tar>, $path.relative;\n\n=head2 Be mindful of $*CWD\n\nWhile usually out of view, every L«C<IO::Path>|/type/IO::Path» object, by\ndefault, uses the current value of\nL«C<$*CWD>|/language/variables#Dynamic_variables» to set its\nL«C<$.CWD> attribute|/type/IO::Path#attribute_CWD». This means there are two\nthings to pay attention to.\n\n=head3 temp the $*CWD\n\nThis code is a mistake:\n\n=for code\n# WRONG!!\nmy $*CWD = \"foo\".IO;\n\nThe C<my $*CWD> made L«C<$*CWD>|/language/variables#Dynamic_variables»\nundefined. The L«C<.IO>|/routine/IO» coercer\nthen goes ahead and sets the L«C<$.CWD> attribute|/type/IO::Path#attribute_CWD»\nof the path it's creating to the stringified version of the undefined C<$*CWD>;\nan empty string.\n\nThe correct way to perform this operation is use\nL«C<temp>|/routine/temp» instead of C<my>. It'll localize the effect of changes\nto L«C<$*CWD>|/language/variables#Dynamic_variables», just like C<my> would,\nbut it won't make it undefined, so the L«C<.IO>|/routine/IO» coercer will still\nget the correct old value:\n\n=for code\ntemp $*CWD = \"foo\".IO;\n\nBetter yet, if you want to perform some code in a localized\nL«C<$*CWD>|/language/variables#Dynamic_variables», use the\nL«C<indir> routine|/routine/indir» for that purpose.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/io.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"tutorial\")\n\n=TITLE Input/Output\n\n=SUBTITLE File-related operations\n\nHere we present a quick overview of the file-related input/output\noperations. Details can be found in the documentation for the\nL<C<IO>|/type/IO> role, as well as the L<C<IO::Handle>|/type/IO::Handle> and\nL<C<IO::Path>|/type/IO::Path> types.\n\nX<slurp>\n\n=head1 Reading from files\n\nOne way to read the contents of a file is to open the file via the C<open>\nfunction with the C<:r> (read) file mode option and slurp in the contents:\n\n=for code\nmy $fh = open \"testfile\", :r;\nmy $contents = $fh.slurp;\n$fh.close;\n\nHere we explicitly close the filehandle using the C<close> method on the\nL<C<IO::Handle>|/type/IO::Handle> object. This is a very traditional way of reading the\ncontents of a file. However, the same can be done more easily and clearly\nlike so:\n\n=for code\nmy $contents = \"testfile\".IO.slurp;\n# or in procedural form:\n$contents = slurp \"testfile\"\n\nBy adding the L<C<IO>|/type/IO> role to the file name string, we are effectively able to\nrefer to the string as the file object itself and thus slurp in its\ncontents directly. Note that the C<slurp> takes care of opening and closing\nthe file for you.\n\n=head2 Line by line\n\nWe also have the option to read a file line-by-line. The new line\nseparator (i.e., C<$*IN.nl-in>) will be excluded.\n\n=begin code\nfor 'huge-csv'.IO.lines -> $line {\n    # Do something with $line\n}\n\n# or if you'll be processing later\nmy @lines = 'huge-csv'.IO.lines;\n=end code\n\n=head1 Writing to files\n\nTo write data to a file, again we have the choice of the traditional method\nof calling the C<open> function – this time with the C<:w> (write) option –\nand printing the data to the file:\n\n=for code\nmy $fh = open \"testfile\", :w;\n$fh.print(\"data and stuff\\n\");\n$fh.close;\n\nOr equivalently with C<say>, thus the explicit newline is no longer necessary:\n\n=for code\nmy $fh = open \"testfile\", :w;\n$fh.say(\"data and stuff\");\n$fh.close;\n\nWe can simplify this by using C<spurt> to open the file in write mode,\nwriting the data to the file and closing it again for us:\n\n=for code\nspurt \"testfile\", \"data and stuff\\n\";\n\nBy default all (text) files are written as UTF-8, however if necessary, an\nexplicit encoding can be specified via the C<:enc> option:\n\n=for code\nspurt \"testfile\", \"latin1 text: äöüß\", enc => \"latin1\";\n\nTo write formatted strings to a file, use the L<printf|/routine/printf> function\nof L<C<IO::Handle>|/type/IO::Handle>.\n\n=for code\nmy $fh = open \"testfile\", :w;\n$fh.printf(\"formatted data %04d\\n\", 42);\n$fh.close;\n\nTo append to a file, specify the C<:a> option when opening the filehandle\nexplicitly,\n\n=for code\nmy $fh = open \"testfile\", :a;\n$fh.print(\"more data\\n\");\n$fh.close;\n\nor equivalently with C<say>, thus the explicit newline is no longer necessary,\n\n=for code\nmy $fh = open \"testfile\", :a;\n$fh.say(\"more data\");\n$fh.close;\n\nor even simpler with the C<:append> option in the call to C<spurt>:\n\n=for code\nspurt \"testfile\", \"more data\\n\", :append;\n\nTo explicitly write binary data to a file, open it with the C<:bin> option.\nThe input/output operations then will take place using the L<C<Buf>|/type/Buf> type instead\nof the L<C<Str>|/type/Str> type.\n\n=head1 Copying, renaming, and removing files\n\nRoutines C<copy>, C<rename>, C<move>, and C<unlink> are available to avoid low-level system\ncommands. See details at L<copy|/routine/copy>, L<rename|/routine/rename>,\nL<move|/routine/move>, and L<unlink|/routine/unlink>. Some examples:\n\n=begin code\nmy $filea = 'foo';\nmy $fileb = 'foo.bak';\nmy $filec = '/disk1/foo';\n# note 'diskN' is assumed to be a physical storage device\n\ncopy $filea, $fileb;              # overwrites $fileb if it exists\ncopy $filea, $fileb, :createonly; # fails if $fileb exists\n\nrename $filea, 'new-foo';              # overwrites 'new-foo' if it exists\nrename $filea, 'new-foo', :createonly; # fails if 'new-foo' exists\n\n# use move when a system-level rename may not work\nmove $fileb, '/disk2/foo';              # overwrites '/disk2/foo' if it exists\nmove $fileb, '/disk2/foo', :createonly; # fails if '/disk2/foo' exists\n\nunlink $filea;\n$fileb.IO.unlink;\n=end code\n\nThe two C<unlink> sentences remove their argument if it exists, unless the\nuser does not have the correct permissions to do so; in that case, it raises\nan exception.\n\n=head1 Checking files and directories\n\nUse the C<e> method on an L<C<IO::Path>|/type/IO::Path> object to test whether the file or\ndirectory exists.\n\n=for code\nif \"nonexistent_file\".IO.e {\n    say \"file exists\";\n}\nelse {\n    say \"file doesn't exist\";\n}\n\nIt is also possible to use the colon pair syntax to achieve the same thing:\n\n=for code\nif \"path/to/file\".IO ~~ :e {\n    say 'file exists';\n}\n\n=for code\nmy $file = \"path/to/file\";\nif $file.IO ~~ :e {\n    say 'file exists';\n}\n\nSimilarly to the file existence check, one can also check to see if a path\nis a directory. For instance, assuming that the file C<testfile> and the\ndirectory C<lib> exist, we would obtain from the existence test method C<e>\nthe same result, namely that both exist:\n\n=for code\nsay \"testfile\".IO.e;  # OUTPUT: «True␤»\nsay \"lib\".IO.e;       # OUTPUT: «True␤»\n\nHowever, since only one of them is a directory, the directory test method\nC<d> will give a different result:\n\n=for code\nsay \"testfile\".IO.d;  # OUTPUT: «False␤»\nsay \"lib\".IO.d;       # OUTPUT: «True␤»\n\nNaturally the tables are turned if we check to see if the path is a file via\nthe file test method C<f>:\n\n=for code\nsay \"testfile\".IO.f;  # OUTPUT: «True␤»\nsay \"lib\".IO.f;       # OUTPUT: «False␤»\n\nThere are other methods that can be used to query a file or directory,\nsome useful ones are:\n\n=begin code\nmy $f = \"file\";\n\nsay $f.IO.modified; # return time of last file (or directory) change\nsay $f.IO.accessed; # return last time file (or directory) was read\nsay $f.IO.s;        # return size of file (or directory inode) in bytes\n=end code\n\nSee more methods and details at L<C<IO::Path>|/type/IO::Path>.\n\n=head1 Getting a directory listing\n\nTo list the contents of the current directory, use the C<dir> function. It\nreturns a list of L<C<IO::Path>|/type/IO::Path> objects.\n\n    say dir;          # OUTPUT: «\"/path/to/testfile\".IO \"/path/to/lib\".IO␤»\n\nTo list the files and directories in a given directory, simply pass a path\nas an argument to C<dir>:\n\n    say dir \"/etc/\";  # OUTPUT: «\"/etc/ld.so.conf\".IO \"/etc/shadow\".IO ....␤»\n\n=head1 Creating and removing directories\n\nTo create a new directory, simply call the C<mkdir> function with the\ndirectory name as its argument:\n\n=for code\nmkdir \"newdir\";\n\nThe function returns the name of the created directory on success and L<C<Nil>|/type/Nil>\non failure. Thus the standard Perl idiom works as expected:\n\n=for code\nmkdir \"newdir\" or die \"$!\";\n\nUse C<rmdir> to remove I<empty> directories:\n\n=for code\nrmdir \"newdir\" or die \"$!\";\n\n=end pod\n"
  },
  {
    "path": "doc/Language/ipc.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"tutorial\")\n\n=TITLE Inter-process communication\n\n=SUBTITLE Programs running other programs and communicating with them\n\nX<|Language,IPC>\n=head1 X<Running programs|Reference,Running programs>\n\nMany programs need to be able to run other programs, and we need to pass\ninformation to them and receive their output and exit status. Running a program\nin Raku is as easy as:\n\n    run 'git', 'status';\n\nThis line runs the program named \"git\" and passes \"git\" and \"status\" to its\ncommand-line. It will find the program using the C«%*ENV<PATH>» setting.\n\nIf you would like to run a program by sending a command-line to the shell,\nthere's a tool for that as well. All shell metacharacters are interpreted by\nthe shell, including pipes, redirects, environment variable substitutions and so\non.\n\n    shell 'ls -lR | gzip -9 > ls-lR.gz';\n\nCaution should be taken when using C<shell> with user input.\n\n=head1 The L<C<Proc>|/type/Proc> object\n\nBoth C<run> and C<shell> return a L<C<Proc>|/type/Proc> object, which can be used\nto communicate with the process in more detail. Please note that unless you\nclose all output pipes, the program will usually not terminate.\n\n    my $git = run 'git', 'log', '--oneline', :out;\n    for $git.out.lines -> $line {\n        my ($sha, $subject) = $line.split: ' ', 2;\n        say \"$subject [$sha]\";\n    }\n    $git.out.close();\n\nIf the program fails (exits with a non-zero exit code), it will throw\nan exception when the returned L<C<Proc>|/type/Proc> object is sunk. You can save it into\na variable, even anonymous one, to prevent the sinking:\n\n    $ = run '/bin/false'; # does not sink the Proc and so does not throw\n\nYou can tell the L<C<Proc>|/type/Proc> object to capture output as a filehandle by passing\nthe C<:out> and C<:err> flags. You may also pass input via the C<:in> flag.\n\n    my $echo = run 'echo', 'Hello, world', :out;\n    my $cat  = run 'cat', '-n', :in($echo.out), :out;\n    say $cat.out.get;\n    $cat.out.close();\n\nYou may also use L<C<Proc>|/type/Proc> to capture the PID, send signals to the application,\nand check the exitcode.\n\n    my $crontab = run 'crontab', '-l';\n    if $crontab.exitcode == 0 {\n        say 'crontab -l ran ok';\n    }\n    else {\n        say 'something went wrong';\n    }\n\n=head2 Example with shell\n\nSuppose there is a utility that will takes input from STDIN and outputs to STDOUT, but there\nisn't yet a Raku wrapper. For this example, lets use L<sass|https://sass-lang.com/documentation/cli/dart-sass/>,\nwhich preprocesses a more convenient form of CSS called SCSS into standard CSS. In a terminal the utility would\nbe used as\n    sass --stdin\n\nWe want to convert multiple strings of SCSS into CSS. The code below only converts one string and captures the output\ninto a variable, but it should be obvious how to adapt this into a loop.\n=begin code\n    #| process with utility, first check it exists in the environment\n    my $proc = shell( <<sass --version>>, :out, :merge);\n    exit note 'Cannot run sass' unless $proc.out.slurp(:close) ~~ / \\d \\. \\d+ /;\n\n    # start loop here for multiple SCSS strings\n    # set up the process for stdin.\n    $proc = shell( <<sass --stdin --style=compressed>>, :in, :err, :out );\n    my $scss = q:to/SCSS/;\n        div.rendered-formula {\n            display: flex;\n            justify-content: space-around;\n            align-items: center;\n            img.logo {\n                align-self: center;\n            }\n        }\n        SCSS\n    # now pipe the SCSS string into the process as STDIN (remembering to close the pipe)\n    $proc.in.spurt($scss,:close);\n    # extract the output or the error\n    my $error  = $_ with $proc.err.slurp(:close);\n    my $output = $_ with $proc.out.slurp(:close);\n\n    # end loop here\n=end code\n=head1 The L<C<Proc::Async>|/type/Proc::Async> object\n\nWhen you need more control over the communication with and from another process,\nyou will want to make use of L<C<Proc::Async>|/type/Proc::Async>. This class\nprovides support for asynchronous communication with a program, as well as the\nability to send signals to that program.\n\n    =begin code\n    # Get ready to run the program\n    my $log = Proc::Async.new('tail', '-f',  '/var/log/system.log');\n    $log.stdout.tap(-> $buf { print $buf });\n    $log.stderr.tap(-> $buf { $*ERR.print($buf) });\n\n    # Start the program\n    my $done = $log.start;\n    sleep 10;\n\n    # Tell the program to stop\n    $log.kill('QUIT');\n\n    # Wait for the program to finish\n    await $done;\n    =end code\n\nThe small program above uses the \"tail\" program to print out the contents of the\nlog named C<system.log> for 10 seconds and then tells the program to stop with a\nQUIT signal.\n\nWhereas L<C<Proc>|/type/Proc> provides access to output using L<C<IO::Handle>|/type/IO::Handle>s, L<C<Proc::Async>|/type/Proc::Async>\nprovides access using asynchronous supplies (see L<C<Supply>|/type/Supply>).\n\nIf you want to run a program and do some work while you wait for the original\nprogram to finish, the C<start> routine returns a L<C<Promise>|/type/Promise>,\nwhich is kept when the program quits.\n\nUse the C<write> method to pass data into the program.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/iterating.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"tutorial\")\n\n=TITLE Iterating\n\n=SUBTITLE Functionalities available for visiting all items in a complex data structure\n\n=head1 The L<C<Iterator>|/type/Iterator> and L<C<Iterable>|/type/Iterable> roles\n\nRaku is a functional language, but functions need something to hold on to when\nworking on complex data structures. In particular, they need a uniform interface\nthat can be applied to all data structures in the same way. One of these kind of\ninterfaces is provided by the L<C<Iterator>|/type/Iterator> and\nL<C<Iterable>|/type/Iterable> roles.\n\nThe L<C<Iterable>|/type/Iterable> role is relatively simple. It provides a stub for the\nC<iterator> method, which is the one actually used by statements such as C<for>.\nC<for> will call C<.iterator> on the variable it precedes, and then run a block\nonce for every item. Other methods, such as array assignment, will make the\nL<C<Iterable>|/type/Iterable> class behave in the same way.\n\n=begin code\nclass DNA does Iterable {\n    has $.chain;\n    method new ($chain where {\n                       $chain ~~ /^^ <[ACGT]>+ $$ / and\n                       $chain.chars %% 3 } ) {\n        self.bless( :$chain );\n    }\n\n    method iterator(DNA:D:){ $.chain.comb.rotor(3).iterator }\n};\n\nmy @longer-chain =  DNA.new('ACGTACGTT');\nsay @longer-chain.raku;\n# OUTPUT: «[(\"A\", \"C\", \"G\"), (\"T\", \"A\", \"C\"), (\"G\", \"T\", \"T\")]␤»\n\nsay  @longer-chain».join(\"\").join(\"|\"); # OUTPUT: «ACG|TAC|GTT␤»\n=end code\n\nIn this example, which is an extension of the L<example in C<Iterable> that\nshows how C<for> calls C<.iterator>|/type/Iterable>, the C<iterator> method will\nbe called in the appropriate context only when the created object is assigned to\na L<C<Positional>|/type/Positional> variable, C<@longer-chain>; this variable is an\nL<C<Array>|/type/Array> and we operate on it as such in the last example.\n\nThe (maybe a bit confusingly named) L<C<Iterator>|/type/Iterator> role is a bit more complex than\nL<C<Iterable>|/type/Iterable>. First, it provides a constant, C<IterationEnd>. Then, it also\nprovides a series of L<methods|/type/Iterator#Methods> such as C<.pull-one>,\nwhich allows for a finer operation of iteration in several contexts: adding or\neliminating items, or skipping over them to access other items. In fact, the\nrole provides a default implementation for all the other methods, so the only\none that has to be defined is precisely C<pull-one>, of which only a stub is\nprovided by the role. While L<C<Iterable>|/type/Iterable> provides the high-level interface loops\nwill be working with, L<C<Iterator>|/type/Iterator> provides the lower-level functions that will\nbe called in every iteration of the loop. Let's extend the previous example with\nthis role.\n\n=begin code\nclass DNA does Iterable does Iterator {\n    has $.chain;\n    has Int $!index = 0;\n\n    method new ($chain where {\n                       $chain ~~ /^^ <[ACGT]>+ $$ / and\n                       $chain.chars %% 3 } ) {\n        self.bless( :$chain );\n    }\n\n    method iterator( ){ self }\n    method pull-one( --> Mu){\n        if $!index < $.chain.chars {\n            my $codon = $.chain.comb.rotor(3)[$!index div 3];\n            $!index += 3;\n            return $codon;\n        } else {\n            return IterationEnd;\n        }\n    }\n};\n\nmy $a := DNA.new('GAATCC');\n.say for $a; # OUTPUT: «(G A A)␤(T C C)␤»\n=end code\n\nWe declare a C<DNA> class which does the two roles, L<C<Iterator>|/type/Iterator> and L<C<Iterable>|/type/Iterable>;\nthe class will include a string that will be constrained to have a length that\nis a multiple of 3 and composed only of ACGT.\n\nLet us look at the\nC<pull-one> method. This one is going to be called every time a new iteration\noccurs, so it must keep the state of the last one. An C<$.index> attribute will\nhold that state across invocations; C<pull-one> will check if the end of the\nchain has been reached and will return the C<IterationEnd> constant provided by\nthe role. Implementing this low-level interface, in fact, simplifies the\nimplementation of the L<C<Iterable>|/type/Iterable> interface. Now the iterator will be the object\nitself, since we can call C<pull-one> on it to access every member in turn;\nC<.iterator> will thus return just C<self>; this is possible since the object\nwill be, at the same time, L<C<Iterable>|/type/Iterable> and L<C<Iterator>|/type/Iterator>.\n\nThis need not always be the case, and in most cases C<.iterator> will have to\nbuild an iterator type to be returned (that will, for instance, keep track of\nthe iteration state, which we are doing now in the main class), such as we did\nin the previous example; however, this example shows the minimal code needed to\nbuild a class that fulfills the iterator and iterable roles.\n\n=head1 How to iterate: contextualizing and topic variables\n\nC<for> and other loops place the item produced in every iteration into the\nL<topic variable C<$_>|/language/variables#index-entry-topic_variable>, or\ncapture them into the variables that are declared along with the block. These\nvariables can be directly used inside the loop, without needing to declare them,\nby using the\nL<C<^> twigil|/syntax/$CIRCUMFLEX_ACCENT#(Traps_to_avoid)_twigil_^>.\n\nImplicit iteration occurs when using the L<sequence operator|/language/operators#infix_...>.\n\n    say 1,1,1, { $^a²+2*$^b+$^c } … * > 300; # OUTPUT: «(1 1 1 4 7 16 46 127 475)\n\nThe generating block is being run once while the condition to finish the\nsequence, in this case the term being bigger than 300, is not met. This has the\nside effect of running a loop, but also creating a list that is output.\n\nThis can be done more systematically through the use of the L<C<gather/take>\nblocks|/syntax/gather take>, which are a different kind of iterating construct\nthat instead of running in sink context, returns an item every iteration. This\nL<Advent Calendar tutorial|https://perl6advent.wordpress.com/2009/12/23/day-23-lazy-fruits-from-the-gather-of-eden/>\nexplains use cases for this kind of loops; in fact, gather is not so much a\nlooping construct, but a statement prefix that collects the items produced by\nC<take> and creates a list out of them.\n\n=head1 C<Classic> loops and why we do not like them\n\nClassic C<for> loops, with a loop variable being incremented, can be done in\nRaku through the L<C<loop> keyword|/language/control#loop>. Other\nL<repeat|/language/control#repeat/while,_repeat/until> and\nL<while|/language/control#while,_until> loops are also possible.\n\nHowever, in general, they are discouraged. Raku is a functional and concurrent\nlanguage; when coding in Raku, you should look at loops in a functional way:\nprocessing, one by one, the items produced by an iterator, that is, feeding an\nitem to a block without any kind of secondary effects. This functional view\nallows also easy parallelization of the operation via the\nL<C<hyper>|/routine/hyper> or L<C<race>|/routine/race> auto-threading methods.\n\nIf you feel more comfortable with your good old loops, the language allows you\nto use them. However, it is considered better practice in Raku to try and use, whenever\npossible, functional and concurrent iterating constructs.\n\nI<Note:> Since version 6.d loops can produce a list of values from the values of last statements.\n=end pod\n"
  },
  {
    "path": "doc/Language/js-nutshell.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"migration\")\n\n=TITLE JavaScript (Node.js) to Raku - nutshell\n\n=SUBTITLE Learning Raku from Node.js, in a nutshell\n\nThis page attempts to provide a way for users experienced in Node.js to learn\nRaku. Features shared between the two languages will be explained here, as\nwell as major differences in syntax and features.\n\nThis is not a tutorial for learning Raku; this is a reference for users who\nare already at an intermediate to advanced skill level with Node.js.\n\n=head1 Basic syntax\n\n=head2 \"Hello, world!\"\n\nLet's start with the typical first program when learning new languages. In\nNode.js, a hello world program would be written like this:\n\n=begin code :lang<javascript>\nconsole.log('Hello, world!');\n=end code\n\nHere are a couple ways to write this in the same way in Raku:\n\n=begin code\nsay('Hello, world!');\nsay 'Hello, world!';\n=end code\n\nParentheses are optional for function calls in Raku. While semicolons are,\nfor the most part, optional in Node.js, they are mandatory for expressions in\nRaku.\n\nNow that we've greeted the world, let's greet our good friend, Joe. We'll\nstart with Node.js again:\n\n=begin code :lang<javascript>\nlet name = 'Joe';\nconsole.log('What\\'s up,' + name + '?');\nconsole.log(`What's up, ${name}?`);\nconsole.log(\"What's up, \", name, \"?\");\n=end code\n\nSince he didn't hear us, let's greet him again, this time in Raku:\n\n=begin code\nmy $name = 'Joe';\nsay 'What\\'s up, ' ~ $name ~ '?';\nsay \"What's up, $name?\";\nsay \"What's up, \", $name, \"?\";\n=end code\n\nHere, there are only a couple differences: most variables in Raku have what\nare called sigils, which are what the C<$> in front of its name is, and string\nconcatenation uses the C<~> operator instead of C<+>. What the two languages\nshare in common here is support for string interpolation.\n\nNow that the basic examples are out of the way, let's explain the similarities\nbetween the two languages in greater detail.\n\n=head2 Variables\n\nVariables in Node.js can be defined like this:\n\n=begin code :lang<javascript>\nvar   foo = 1;  // Lexically scoped with functions and modules\nlet   foo = 1;  // Lexically scoped with blocks\nconst foo = 1;  // Lexically scoped with blocks; constant\n\n// No equivalent to Raku dynamic variables exists.\n\nglobal.foo = 1; // Globally scoped\nfoo = 1;        // Ditto, but implicit; forbidden in strict mode\n=end code\n\nIn Raku there is no equivalent to C<var>. An important note to make is that\nthere is no variable hoisting in Raku; variables are defined and assigned\nat the line they're on, not defined at the top of its scope and later assigned\nat that line.\n\nIn addition to regular variables, in Raku there are what is known as dynamic\nvariables. Dynamic variables are looked up using the caller's scope, rather\nthan the outer scope. This is what the equivalent variable declarations look\nlike in Raku:\n\n=for code\nmy $foo = 1; # Lexically scoped\nour $foo = 1; # Package scoped\n\n=for code\nmy constant foo = 1; # Lexically scoped; constant\n\n=for code\nconstant foo = 1; # Package scoped; constant\n\n=for code\nmy  $*foo = 1; # Dynamic variable; lexically scoped\nour $*foo = 1; # Dynamic variable; package scoped\n\n=for code\nGLOBAL::<$foo> := 1; # Globally scoped\n\nUse C<my> where you'd use C<let>, C<our> for variables you'd define in the\noutermost scope needed, and C<constant> where you'd use C<const>.\n\nYou may have noticed the C<$> and C<$*> symbols placed before variable names.\nThese are known as sigils and twigils respectively, and define what container\nthe variable has. Refer to the documentation on\nL<variables|/language/variables> for more information on sigils, twigils, and\ncontainers.\n\nVariables in Node.js can have the same name as others from outer scopes without\nconflicting (though linters will usually complain about it depending on how\nthey're configured):\n\n=begin code :lang<javascript>\nlet foo = 1;\nfunction logDupe() {\n    let foo = 2;\n    console.log(foo);\n}\n\nlogDupe();       // OUTPUT: 2\nconsole.log(foo); // OUTPUT: 1\n=end code\n\nRaku also allows this:\n\n=begin code\nmy $foo = 1;\nsub log-dupe {\n    my $foo = 2;\n    say $foo;\n}\n\nlog-dupe; # OUTPUT: 2\nsay $foo; # OUTPUT: 1\n=end code\n\n=head2 Operators\n\n=head3 Assignment\n\nThe C<=> operator works the same across both languages.\n\nThe C<:=> operator in Raku binds a value to a variable. Binding a variable\nto another variable gives them the same value and container, meaning mutating\nattributes of one will mutate the other's as well. Bound variables cannot be\nreassigned with C<=> or mutated with C<++>, C<-->, etc. but they can be bound\nto another value again:\n\n=begin code\nmy %map;            # This is a hash, roughly equivalent to a JS object or map\nmy %unbound = %map;\nmy %bound := %map;\n%map<foo> = 'bar';\nsay %unbound;       # OUTPUT: {}\nsay %bound;         # OUTPUT: {foo => bar}\n\n%bound := %unbound;\nsay %bound;         # OUTPUT: {}\n=end code\n\n=head3 Equality\n\nNode.js has two equality operators: C<==> and C<===>.\n\nC<==> is the loose equality operator. When comparing operands with the same\ntype, it will return true if both operands are equal. However, if the\noperands are different types, they are both cast to their primitives before\nbeing compared, meaning these will return true:\n\n=begin code :lang<javascript>\nconsole.log(1 == 1);   // OUTPUT: true\nconsole.log('1' == 1); // OUTPUT: true\nconsole.log([] == 0);  // OUTPUT: true\n=end code\n\nSimilarly, in Raku, both operands are cast to Numeric before comparison if\nthey don't share the same type:\n\n=begin code\nsay 1 == 1;       # OUTPUT: True\nsay '1' == 1;     # OUTPUT: True\nsay [1,2,3] == 3; # OUTPUT: True, since the array has three elements\n=end code\n\nThe inverse of C<==> is C<!=>.\n\nRaku has another operator similar to C<==>: C<eq>. Instead of casting operands\nto Numeric if they're different types, C<eq> will cast them to strings:\n\n=begin code\nsay '1' eq '1'; # OUTPUT: True\nsay 1 eq '1';   # OUTPUT: True\n=end code\n\nThe inverse of C<eq> is C<ne> or C<!eq>.\n\nC<===> is the strict equality operator. This returns true if both operands are\nthe same value. When comparing objects, this will I<only> return true if they\nare the exact same object:\n\n=begin code :lang<javascript>\nconsole.log(1 === 1);   // OUTPUT: true\nconsole.log('1' === 1); // OUTPUT: false\nconsole.log({} === {}); // OUTPUT: false\n\nlet obj = {};\nlet obj2 = obj;\nconsole.log(obj === obj2); // OUTPUT: true;\n=end code\n\nIn Raku, the operator behaves the same, with one exception: two objects that\nhave the same value, but different containers, will return false:\n\n=begin code\nsay 1 === 1;                    # OUTPUT: «True␤»\nsay '1' === 1;                  # OUTPUT: «False␤»\nsay 'ayy lmao' === 'ayy lmao';  # OUTPUT: «True␤»\nsay {} === {};                  # OUTPUT: «False␤»\n\nmy \\hash = {};\nmy %hash = hash;\nsay hash === %hash; # OUTPUT: False\n=end code\n\nIn the last case it's the same object, but containers are different, which is\nwhy it returns False.\n\nThe inverse of C<===> is C<!==>.\n\nThis is where Raku's other equality operators are useful. If the values have\ndifferent containers, the C<eqv> operator can be used. This operator can be also\nbe used to check for deep equality, which you would normally need to use a\nlibrary for in Node.js:\n\n=begin code\nsay {a => 1} eqv {a => 1}; # OUTPUT: True\n\nmy \\hash = {};\nmy %hash := hash;\nsay hash eqv %hash; # OUTPUT: True\n=end code\n\nIn the case you need to check if two variables have the same container and\nvalue, use the C<=:=> operator.\n\n=begin code\nmy @arr = [1,2,3];\nmy @arr2 := @arr;   # Bound variables keep the container of the other variable\nsay @arr =:= @arr2; # OUTPUT: True\n=end code\n\n=head3 Smartmatching\n\nRaku has one last operator for comparing values, but it is not exactly an\nequality operator. This is C<~~>, the smartmatch operator. This has several\nuses: it can be used like C<instanceof> in Node.js, to match a regex, and to\ncheck if a value is a key in a hash, bag, set, or map:\n\n=begin code\nsay 'ayy lmao' ~~ Str; # OUTPUT: True\n\nmy %hash = a => 1;\nsay 'a' ~~ %hash; # OUTPUT: True\n\nmy $str = 'abc';\n$str ~~ s/abc/def/; # Mutates $str, like foo.replace('abc', 'def')\nsay $str;           # OUTPUT: def\n=end code\n\nWhile we are talking about C<instanceof>, the equivalent to the C<constructor>\nproperty on Node.js objects in Raku is the C<WHAT> attribute:\n\n=begin code :lang<javascript>\nconsole.log('foo'.constructor); // OUTPUT: String\n=end code\n\n=begin code :ok-test<WHAT>\nsay 'foo'.WHAT; # OUTPUT: Str\n=end code\n\n=head3 Numeric\n\nNode.js has C<+>, C<->, C</>, C<*>, C<%>, and (in ES6) C<**> as numeric\noperators. When the operands are different types, similarly to the equality\noperators, are cast to their primitives before following through with the\noperation, making this possible:\n\n=begin code :lang<javascript>\nconsole.log(1 + 2);   // OUTPUT: 3\nconsole.log([] + {}); // OUTPUT: [object Object]\nconsole.log({} + []); // OUTPUT: 0\n=end code\n\nIn Raku, again, they are converted to a Numeric type, as before:\n\n=begin code\nsay 1 + 2;        # OUTPUT: 3\nsay [] + {};      # OUTPUT: 0\nsay {} + [1,2,3]; # OUTPUT: 3\n=end code\n\nIn addition, Raku has C<div> and C<%%>. C<div> behaves like C<int> division in\nC, while C<%%> checks if one number is cleanly divisible by another or not:\n\n=begin code\nsay 4 div 3; # OUTPUT: 1\nsay 4 %% 3;  # OUTPUT: False\nsay 6 %% 3;  # OUTPUT: True\n=end code\n\n=head3 Bitwise\n\nNode.js has C<&>, C<|>, C<^>, C<~>, C«<<», C«>>», C«>>>», and C<~> for bitwise\noperators:\n\n=begin code :lang<javascript>\nconsole.log(1 << 1);  // OUTPUT: 2\nconsole.log(1 >> 1);  // OUTPUT: 0\nconsole.log(1 >>> 1); // OUTPUT: 0\nconsole.log(1 & 1);   // OUTPUT: 1\nconsole.log(0 | 1);   // OUTPUT: 1\nconsole.log(1 ^ 1);   // OUTPUT: 0\nconsole.log(~1);      // OUTPUT: -2\n=end code\n\nIn Raku, there is no equivalent to C«>>>». All bitwise operators are\nprefixed with C<+>, however bitwise negation uses C<+^> instead of C<~>:\n\n=begin code\nsay 1 +< 1; # OUTPUT: 2\nsay 1 +> 1; # OUTPUT: 0\n            # No equivalent for >>>\nsay 1 +& 1; # OUTPUT: 1\nsay 0 +| 1; # OUTPUT: 1\nsay 1 +^ 1; # OUTPUT: 0\nsay +^1;    # OUTPUT: -2\n=end code\n\n=head3 Checking for definedness\n\nJavascript includes a nullish coalescing operator, C<??>, which progresses\nonly if null or undefined:\n\n=for code :lang<javascript>\nundefined || null || 0 || 1 ;   // => 1\nundefined ?? null ?? 0 ?? 1 ;   // => 0\n\nThis is very similar to Raku L<C<//>|/routine/$SOLIDUS$SOLIDUS> operator:\n\n=for code\nAny || Nil || 0 || 1 ;   # => 1\nAny // Nil // 0 // 1 ;   # => 0\n\n=head3 Custom operators and operator overloading\n\nNode.js does not allow operator overloading without having to use a Makefile or\nbuild Node.js with a custom version of V8. Raku allows custom operators and\noperator overloading natively! Since all operators are subroutines, you can\ndefine your own like so:\n\n=begin code\n# \"distance operator\": the distance of two numbers is the absolute value\n# of their difference\nmulti infix:<|-|>($a, $b) is equiv(&infix:<->) { abs $a - $b }\n\nsay -1 |-| 3; # OUTPUT: 4\n=end code\n\nOperators can be defined as C<prefix>, C<infix>, C<postfix> or C<circumfix>. The\nC<is tighter>, C<is equiv>, and C<is looser> traits optionally define the\noperator's precedence. In this case, C<|-|> has the same precedence as C<->.\n\nNote how C<multi> is used when declaring the operator subroutines. This allows\nmultiple subroutines with the same name to be declared while also having\ndifferent signatures. This will be explained in greater detail in the\nL<Functions|#Functions> section. For now, all we need to know is that it allows\nus to override any native operator we want:\n\n=begin code\n# Using the `is default` trait here forces this subroutine to be chosen first,\n# so long as the signature of the subroutine matches.\nmulti prefix:<++>($a) is default { $a - 1 }\n\nmy $foo = 1;\nsay ++$foo; # OUTPUT: 0\n=end code\n\n=head2 Control flow\n\n=head3 if/else\n\nYou should be familiar with how C<if>/C<else> looks in JavaScript:\n\n=begin code :lang<javascript>\nlet diceRoll = Math.ceil(Math.random() * 6) + Math.ceil(Math.random() * 6);\nif (diceRoll === 2) {\n    console.log('Snake eyes!');\n} else if (diceRoll === 12) {\n    console.log('Boxcars!');\n} else {\n    console.log(`Rolled ${diceRoll}.`);\n}\n=end code\n\nIn Raku, C<if>/C<else> works largely the same, with a few key differences.\nOne, parentheses are not required. Two, C<else if> is written as C<elsif>.\nThree, the if clause may be written I<after> a statement:\n\n=begin code\nmy Int $dice-roll = ceiling rand * 6 + ceiling rand * 6;\nif $dice-roll == 2 {\n    say 'Snake eyes!';\n} elsif $dice-roll == 12 {\n    say 'Boxcars!';\n} else {\n    say \"Rolled $dice-roll.\";\n}\n=end code\n\nAlternatively, though less efficient, this could be written to use C<if> after\nstatements:\n\n=begin code\nmy Int $dice-roll = ceiling rand * 6 + ceiling rand * 6;\nsay 'Snake eyes!'        if $dice-roll == 2;\nsay 'Boxcars!'           if $dice-roll == 12;\nsay \"Rolled $dice-roll.\" if $dice-roll != 2 && $dice-roll != 12;\n=end code\n\nRaku also has C<when>, which is like C<if>, but if the condition given is\ntrue, no code past the C<when> block within the block it's in is executed:\n\n=begin code\n{\n    when True {\n        say 'In when block!'; # OUTPUT: In when block!\n    }\n    say 'This will never be output!';\n}\n=end code\n\nAdditionally, Raku has C<with>, C<orwith>, and C<without>, which are like\nC<if>, C<else if>, and C<else> respectively, but instead of checking whether\ntheir condition is true, they check if it's defined.\n\n=head3 switch\n\nSwitch statements are a way of checking for equality between a given value and\na list of values and run some code if one matches. C<case> statements define\neach value to compare to. C<default>, if included, acts as a fallback for when\nthe given value matches no cases. After matching a case, C<break> is typically\nused to prevent the code from the cases that follow the one matched from being\nexecuted, though rarely this is intentionally omitted.\n\n=begin code :lang<javascript>\nconst ranklist = [2, 3, 4, 5, 6, 7, 8, 9, 'Jack', 'Queen', 'King', 'Ace'];\nconst ranks    = Array.from(Array(3), () => ranklist[Math.floor(Math.random() * ranks.length)]);\nlet   score    = 0;\n\nfor (let rank of ranks) {\n    switch (rank) {\n        case 'Jack':\n        case 'Queen':\n        case 'King':\n            score += 10;\n            break;\n        case 'Ace';\n            score += (score <= 11) ? 10 : 1;\n            break;\n        default:\n            score += rank;\n            break;\n    }\n}\n=end code\n\nIn Raku, C<given> can be used like switch statements. There is no equivalent\nto C<break> since C<when> blocks are most commonly used like C<case>\nstatements. One major difference between C<switch> and C<given> is that a value\npassed to a C<switch> statement will only match cases that are exactly equal to\nthe value; C<given> values are smartmatched (C<~~>) against the C<when> values.\n\n=begin code\nmy     @ranklist = [2, 3, 4, 5, 6, 7, 8, 9, 'Jack', 'Queen', 'King', 'Ace'];\nmy     @ranks    = @ranklist.pick: 3;\nmy Int $score    = 0;\n\nfor @ranks -> $rank {\n    # The when blocks implicitly return the last statement they contain.\n    $score += do given $rank {\n        when 'Jack' | 'Queen' | 'King' { 10                      }\n        when 'Ace'                     { $score <= 11 ?? 10 !! 1 }\n        default                        { $_                      }\n    };\n}\n=end code\n\nIf there are multiple C<when> blocks that match the value passed to C<given>\nand you wish to run more than one of them, use C<proceed>. C<succeed> may be\nused to exit both the C<when> block it's in and the given block, preventing any\nfollowing statements from being executed:\n\n=begin code\ngiven Int {\n    when Int     { say 'Int is Int';     proceed }\n    when Numeric { say 'Int is Numeric'; proceed }\n    when Any     { say 'Int is Any';     succeed }\n    when Mu      { say 'Int is Mu'               } # Won't output\n}\n\n# OUTPUT:\n# Int is Int\n# Int is Numeric\n# Int is Any\n=end code\n\n=head3 for, while, and do/while\n\nThere are three different types of for loops in JavaScript:\n\n=begin code :lang<javascript>\n// C-style for loops\nconst letters = {};\nfor (let ord = 0x61; ord <= 0x7A; ord++) {\n    let letter = String.fromCharCode(ord);\n    letters[letter] = letter.toUpperCase();\n}\n\n// for..in loops (typically used on objects)\nfor (let letter in letters) {\n    console.log(letters[letter]);\n}\n# OUTPUT:\n# A\n# B\n# C\n# etc.\n\n// for..of loops (typically used on arrays, maps, and sets)\nfor (let letter of Object.values(letters)) {\n    console.log(letter);\n}\n# OUTPUT:\n# A\n# B\n# C\n# etc.\n=end code\n\nRaku C<for> loops most closely resemble C<for..of> loops, since they work on\nanything as long as it's iterable. C-style loops are possible to write using\nC<loop>, but this is discouraged since they're better written as C<for> loops\nusing ranges. Like C<if> statements, C<for> may follow a statement, with the\ncurrent iteration being accessible using the C<$_> variable (known as \"it\").\nMethods on C<$_> may be called without specifying the variable:\n\n=begin code\nmy Str %letters{Str};\n%letters{$_} = .uc for 'a'..'z';\n.say for %letters.values;\n# OUTPUT:\n# A\n# B\n# C\n# etc.\n=end code\n\nC<while> loops work identically between JavaScript and Raku. Raku also has\nC<until> loops, where instead of iterating until the given condition is false,\nthey iterate until the condition is true.\n\nC<do/while> loops are known as C<repeat/while> loops in Raku. Likewise with\nC<while>, C<repeat/until> loops also exist and loop until the given condition\nis false.\n\nTo write infinite loops in Raku, use C<loop> rather than C<for> or C<while>.\n\nIn JavaScript, C<continue> is used to skip to the next iteration in a loop, and\nC<break> is used to exit a loop early:\n\n=begin code :lang<javascript>\nlet primes = new Set();\nlet i      = 2;\n\ndo {\n    let isPrime = true;\n    for (let prime of primes) {\n        if (i % prime == 0) {\n            isPrime = false;\n            break;\n        }\n    }\n    if (!isPrime) continue;\n    primes.add(i);\n} while (++i < 20);\n\nconsole.log(primes); # OUTPUT: Set { 2, 3, 5, 7, 11, 13, 17, 19 }\n=end code\n\nIn Raku, these are known as C<next> and C<last> respectively. There is also\nC<redo>, which repeats the current iteration without evaluating the loop's\ncondition again.\n\nC<next>/C<redo>/C<last> statements may be followed by a label defined before an\nouter loop to make the statement work on the loop the label refers to, rather\nthan the loop the statement is in:\n\n=begin code\nmy %primes is SetHash;\nmy Int $i = 2;\n\nOUTSIDE:\nrepeat {\n    next OUTSIDE if $i %% $_ for %primes.keys;\n    %primes{$i}++;\n} while ++$i < 20;\n\nsay %primes; # OUTPUT: SetHash(11 13 17 19 2 3 5 7)\n=end code\n\n=head3 do\n\nC<do> is not currently a feature in JavaScript, however a proposal has been made\nto L<add it to ECMAScript|https://github.com/tc39/proposal-do-expressions>.\nC<do> expressions evaluate a block and return the result:\n\n=begin code\nconstant VERSION        = v2.0.0;\nconstant VERSION_NUMBER = do {\n    my @digits = VERSION.Str.comb(/\\d+/);\n    :16(sprintf \"%02x%02x%04x\", |@digits)\n};\nsay VERSION_NUMBER; # OUTPUT: 33554432\n=end code\n\n=head2 Types\n\n=head3 Creating types\n\nIn JavaScript, types are created by making a class (or a constructor in ES5\nand earlier). If you've used TypeScript, you can define a type as a subset of\nother types like so:\n\n=begin code :lang<typescript>\ntype ID = string | number;\n=end code\n\nIn Raku, classes, roles, subsets, and enums are considered types. Creating\nclasses and roles will be discussed in\nL<the OOP section of this article|#Object-oriented_programming>. Creating an ID\nsubset can be done like so:\n\n=begin code\nsubset ID where Str | Int;\n=end code\n\nSee the documentation on L<subset|/language/typesystem#subset> and\nL<C<Junction>|/type/Junction> for more information.\n\nTypeScript enums may have numbers or strings as their values. Defining the\nvalues is optional; by default, the value of the first key is 0, the next key,\n1, the next, 2, etc. For example, here is an enum that defines directions for\nextended ASCII arrow symbols (perhaps for a TUI game):\n\n=begin code :lang<typescript>\nenum Direction (\n    UP    = '↑',\n    DOWN  = '↓',\n    LEFT  = '←',\n    RIGHT = '→'\n);\n=end code\n\nEnums in Raku may have any type as their keys' values. Enum keys (and\noptionally, values) can be defined by writing C<enum>, followed by the name\nof the enum, then the list of keys (and optionally, values), which can be done\nusing L«< >|/language/quoting#Word_quoting:_<_>»,\nL<« »|/language/quoting#Word_quoting_with_interpolation_and_quote_protection:_«_»>,\nor L<( )|/language/operators#term_(_)>. C<( )> must be used if you want to\ndefine values for the enum's keys. Here is the Direction enum as written in\nRaku:\n\n=begin code\nenum Direction (\n    UP    => '↑',\n    DOWN  => '↓',\n    LEFT  => '←',\n    RIGHT => '→'\n);\n=end code\n\nSee the documentation on L<enum|/language/typesystem#enum> for more information.\n\n=head3 Using types\n\nIn TypeScript, you can define the type of variables. Attempting to assign a\nvalue that doesn't match the type of the variable will make the transpiler\nerror out. This is done like so:\n\n=begin code :lang<typescript>\nenum Name (Phoebe, Daniel, Joe);\nlet name: string = 'Phoebe';\nname = Phoebe; # Causes tsc to error out\n\nlet hobbies: [string] = ['origami', 'playing instruments', 'programming'];\n\nlet todo: Map<string, boolean> = new Map([\n    ['clean the bathroom', false],\n    ['walk the dog', true],\n    ['wash the dishes', true]\n]);\n\nlet doJob: (job: string) => boolean = function (job: string): boolean {\n    todo.set(job, true);\n    return true;\n};\n=end code\n\nIn Raku, variables can be typed by placing the type between the declarator\n(C<my>, C<our>, etc.) and the variable name. Assigning a value that doesn't\nmatch the variable's type will throw either a compile-time or runtime error,\ndepending on how the value is evaluated:\n\n=begin code\nenum Name <Phoebe Daniel Joe>;\nmy Str $name = 'Phoebe';\n$name = Phoebe; # Throws a compile-time error\n\n# The type here defines the type of the elements of the array.\nmy Str @hobbies = ['origami', 'playing instruments', 'programming'];\n\n# The type between the declarator and variable defines the type of the values\n# of the hash.\n# The type in the curly braces defines the type of the keys of the hash.\nmy Bool %todo{Str} = (\n    'clean the bathroom' => False,\n    'walk the dog'       => True,\n    'wash the dishes'    => True\n);\n\n# The type here defines the return value of the routine.\nmy Bool &do-job = sub (Str $job --> Bool) {\n    %todo{$job} = True;\n};\n=end code\n\n=head3 Comparing JavaScript and Raku types\n\nHere is a table of some JavaScript types and their equivalents in Raku:\n\n=begin table\nJavaScript | Raku\n=============================\nObject     | Mu, Any, Hash\nArray      | List, Array, Seq\nString     | Str\nNumber     | Int, Num, Rat\nBoolean    | Bool\nMap        | Map, Hash\nSet        | Set, SetHash\n=end table\n\nC<Object> is both a superclass of all types in JavaScript and a way to create\na hash. In Raku, L<C<Mu>|/type/Mu> is a superclass of all types, though usually\nyou want to use L<C<Any>|/type/Any> instead, which is a subclass of L<C<Mu>|/type/Mu> but also\na superclass of nearly every type, with L<C<Junction>|/type/Junction> being an\nexception. When using C<Object> as a hash, L<C<Hash>|/type/Hash> is what you want\nto use. One key difference between C<Object> and L<C<Hash>|/type/Hash> is that C<Object>\npreserves the order of its keys; L<C<Hash>|/type/Hash> does not by default.\n\nThere are three types equivalent to L<C<Array>|/type/Array>. L<C<Array>|/type/Array> is most\nsimilar to L<C<Array>|/type/Array>, since it acts as a mutable array. L<C<List>|/type/List> is\nsimilar to L<C<Array>|/type/Array>, but is immutable. L<C<Seq>|/type/Seq> is used to create lazy\narrays.\n\nC<String> and L<C<Str>|/type/Str> are for the most part used identically.\n\nThere are several different types in Raku equivalent to C<Number>, but the\nthree you'll most commonly see are L<C<Int>|/type/Int>, L<C<Num>|/type/Num>, and\nL<C<Rat>|/type/Rat>. L<C<Int>|/type/Int> represents an integer. L<C<Num>|/type/Num> represents a\nfloating-point number, making it the most similar to C<Number>. L<C<Rat>|/type/Rat>\nrepresents a fraction of two numbers, and is used when L<C<Num>|/type/Num> cannot provide\nprecise enough values.\n\nC<Boolean> and L<C<Bool>|/type/Bool> are for the most part used identically.\n\nC<Map> has both a mutable and an immutable equivalent in Raku.\nL<C<Map>|/type/Map> is the immutable one, and L<C<Hash>|/type/Hash> is the mutable\none. Don't get them mixed up! Like C<Map> in JavaScript, L<C<Map>|/type/Map> and L<C<Hash>|/type/Hash> can\nhave any type of key or value, not just strings for keys.\n\nLike C<Map>, C<Set> also has both a mutable and an immutable equivalent in Raku.\nL<C<Set>|/type/Set> is the immutable one, and L<C<SetHash>|/type/SetHash> is the\nmutable one.\n\n=head2 Functions\n\n=comment TODO\n\n# TBD\n\n=head1 Object-oriented programming\n\n=comment TODO\n\n# TBD\n\n=head1 Asynchronous programming\n\n=comment TODO\n\n# TBD\n\n=head1 Buffers\n\nNodeJS handles raw binary data with the classes C<Buffer> and C<Blob>, while Raku\ndoes so with the roles L<C<Buf>|/type/Buf> and L<C<Blob>|/type/Blob>, which are\nmutable and immutable buffers respectively. In Raku, a `Buf` composes a `Blob`\nso all `Blob` methods are available to `Buf` objects.\n\nThe following table summarizes the similarities and differences between buffer\nconstructs in NodeJS and Raku:\n\n=begin table\n       Class/Role  | NodeJS      | Raku\n    ===============+=============+===========\n    `Buffer`/`Buf` | Fixed-length sequence of bytes (No methods such as `push`, `pop`, etc.) | Sequence of bytes that can grow or shrink dynamically. You can use methods such as `push`, `pop`, etc.\n                   | Iterable using the `for..of` syntax                                     | It can be iterated over using a looping construct.\n                   | Each byte can be updated using array indexing, e.g., `buf[i]++`.        | Same as NodeJS.\n    `Blob`         | Fixed-length sequence of bytes (No methods such as `push`, `pop`, etc.) | Same as NodeJS.\n                   | It's not iterable.                                                      | It can be iterated over using a looping construct.\n                   | Each byte is immutable.                                                 | Same as NodeJS.\n=end table\n\n=head2 Creating buffers\n\nIn NodeJS, there are a few ways to create a new buffer. You can use the static\nmethod C<Buffer.alloc> to allocate a buffer of C<n> bytes of zero, unless the\nC<fill> argument is provided.\n\n=begin code :lang<javascript>\nconst zeroBuf = Buffer.alloc(8);\nconst charBuf = Buffer.alloc(8, 97, 'utf-8');\nconsole.log(zeroBuf); // OUTPUT: «<Buffer 00 00 00 00 00 00 00 00>␤»\nconsole.log(charBuf); // OUTPUT: «<Buffer 61 61 61 61 61 61 61 61>␤»\n=end code\n\nIn Raku, you can use the L<C<allocate>|/routine/allocate> method:\n\n=begin code :lang<raku>\nmy $zero-blob = Blob.allocate(8);\nmy $char-blob = Blob.allocate(8, 97);\nsay $zero-blob; # OUTPUT: «Blob:0x<00 00 00 00 00 00 00 00>␤»\nsay $char-blob; # OUTPUT: «Blob:0x<61 61 61 61 61 61 61 61>␤»\n\nmy $zero-buf = Buf.allocate(8);\nmy $char-buf = Buf.allocate(8, 97);\nsay $zero-buf; # OUTPUT: «Buf:0x<00 00 00 00 00 00 00 00>␤»\nsay $char-buf; # OUTPUT: «Buf:0x<61 61 61 61 61 61 61 61>␤»\n=end code\n\nYou can also initialize a buffer to the contents of an array of integers:\n\n=begin code :lang<javascript>\nconst buf = Buffer.from([ 114, 97, 107, 117 ]);\nconsole.log(buf); // OUTPUT: «<Buffer 72 61 6b 75>␤»\n=end code\n\nIn Raku, you can do the same by using the L<C<new>|/type/Blob#method_new>\nconstructor:\n\n=begin code :lang<raku>\nmy $blob = Blob.new(114, 97, 107, 117);\nsay $blob; # OUTPUT: «Blob:0x<72 61 6B 75>␤»\n\nmy $buf = Buf.new(114, 97, 107, 117);\nsay $buf; # OUTPUT: «Buf:0x<72 61 6B 75>␤»\n=end code\n\nSimilarly, you can initialize a buffer to the binary encoding of a string using\nthe C<from> method:\n\n=begin code :lang<javascript>\nconst buf = Buffer.from('NodeJS & Raku', 'utf-8');\nconsole.log(buf); // OUTPUT: «<Buffer 4e 6f 64 65 4a 53 20 26 20 52 61 6b 75>␤»\n=end code\n\nIn Raku, you call the L<C<encode>|/routine/encode> method on a string which\nreturns a L<C<Blob>|/type/Blob>:\n\n=begin code :lang<raku>\nmy $blob = \"NodeJS & Raku\".encode('utf-8');\nsay $blob; # OUTPUT: «utf8:0x<4E 6F 64 65 4A 53 20 26 20 52 61 6B 75>␤»\n=end code\n\nB<Note:> In Raku, you must encode a character explicitly when passing its blob\nto a buffer-related method.\n\nTo decode a binary encoding of a string, you call the C<toString> method on the\nbuffer:\n\n=begin code :lang<javascript>\nconst buf = Buffer.from([ 114, 97, 107, 117 ]);\nconsole.log(buf.toString('utf-8')); // OUTPUT: «raku␤»\n=end code\n\nIn Raku, you call the L<C<decode>|/routine/decode> method on the buffer:\n\n=begin code :lang<raku>\nmy $blob = Blob.new(114, 97, 107, 117);\nsay $blob.decode('utf-8'); # OUTPUT: «raku␤»\n=end code\n\n=head2 Writing to a buffer\n\nIn NodeJS, you write to a buffer using the C<write> method:\n\n=begin code :lang<javascript>\nconst buf = Buffer.alloc(16);\nbuf.write('Hello', 0, 'utf-8');\nconsole.log(buf); // OUTPUT: «<Buffer 48 65 6c 6c 6f 00 00 00 00 00 00 00 00 00 00 00>␤»\nbuf.write(' world!', 5, 'utf-8');\nconsole.log(buf); // OUTPUT: «<Buffer 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 00 00 00 00>␤»\n=end code\n\nIn Raku, there's not a C<write> method. However you can use the\nL<C<splice>|/type/Buf#method_splice> method to overwrite elements of a buffer\nwith other elements:\n\n=begin code :lang<raku>\nmy $buf = Buf.allocate(16);\n$buf.splice(0, 5, 'Hello'.encode('utf-8'));\nsay $buf; # OUTPUT: «Buf:0x<48 65 6C 6C 6F 00 00 00 00 00 00 00 00 00 00 00>␤»\n$buf.splice(5, 7, ' world!'.encode('utf-8'));\nsay $buf; # OUTPUT: «Buf:0x<48 65 6C 6C 6F 20 77 6F 72 6C 64 21 00 00 00 00>␤»\n=end code\n\n=head2 Reading from a buffer\n\nThere are many ways to access data in a buffer, from accessing individual bytes\nto extracting the entire content to decoding its contents.\n\n=begin code :lang<javascript>\nconst buf = Buffer.from('Hello', 'utf-8');\nconsole.log(buf[0]); // OUTPUT: «72␤»\n=end code\n\nIn Raku, you can also index bytes of a buffer with\nL<C<[]>|/language/operators#postcircumfix_[_]>:\n\n=begin code :lang<raku>\nmy $blob = 'Hello'.encode('utf-8');\nsay $blob[0]; # OUTPUT: «72␤»\n=end code\n\nIn NodeJS the most common way to retrieve all data from a buffer is with the\nC<toString> method (assuming the buffer is encoded as text):\n\n=begin code :lang<javascript>\nconst buf = Buffer.from('Hello');\nconst buf = Buffer.alloc(16);\nbuf.write('Hello world', 0, 'utf-8');\nconsole.log(buf.toString('utf-8')); // OUTPUT: «Hello world!\\u0000t␤»\n=end code\n\nWe can provide an offset and a length to C<toString> to only read the relevant\nbytes from the buffer:\n\n=begin code :lang<javascript>\nconsole.log(buf.toString('utf-8', 0, 12)); // OUTPUT: «Hello world!␤»\n=end code\n\nIn Raku, you can do the same using the C<decode> method:\n\n=begin code :lang<raku>\nmy $buf = Buf.allocate(16);\n$buf.splice(0, 12, 'Hello world'.encode('utf-8'));;\nsay $buf.decode('utf-8').raku; # OUTPUT: «Hello world!\\0\\0\\0\\0>␤»\n=end code\n\nHowever, you cannot both slice and decode a buffer with C<decode>. Instead\nyou can use L<C<subbuf>|/routine/subbuf> to extract the relevant\npart from the invocant buffer and then C<decode> the returned buffer:\n\n=begin code :lang<raku> :preamble<my $buf>\nsay $buf.subbuf(0, 12).decode('utf-8').raku; # OUTPUT: «Hello world!>␤»\n=end code\n\n=head2 More useful methods\n\n=head3 C<Buffer.isBuffer>\n\nIn NodeJS, you can check if an object is a buffer using the C<isBuffer> method:\n\n=begin code :lang<javascript>\nconst buf = Buffer.from('hello');\nconsole.log(Buffer.isBuffer(buf)); // OUTPUT: «true␤»\n=end code\n\nIn Raku, you can smartmatch against either L<C<Blob>|/type/Blob> or L<C<Buf>|/type/Buf> (remember that\nL<C<Buf>|/type/Buf> composes L<C<Blob>|/type/Blob>):\n\n=begin code :lang<raku>\nmy $blob = 'hello'.encode();\nmy $buf = Buf.allocate(4);\nsay $blob ~~ Blob; # OUTPUT: «True␤»\nsay $blob ~~ Buf;  # OUTPUT: «False␤»\nsay $buf ~~ Buf;   # OUTPUT: «True␤»\nsay $buf ~~ Blob;  # OUTPUT: «True␤»\n=end code\n\n=head3 C<Buffer.byteLength>\n\nTo check the number of bytes required to encode a string, you can use\nC<Buffer.byteLength>:\n\n=begin code :lang<javascript>\nconst camelia = '🦋';\nconsole.log(Buffer.byteLength(camelia)); // OUTPUT: «4␤»\n=end code\n\nIn Raku, you can use the L<C<bytes>|/routine/bytes> method:\n\n=begin code :lang<raku>\nmy $camelia = '🦋';\nsay $camelia.encode.bytes; # OUTPUT: «4␤»\n=end code\n\nB<NOTE:> The number of bytes isn't the same as the string's length. This is\nbecause many characters require more bytes to be encoded than what their\nlengths let on.\n\n=head3 C<length>\n\nIn NodeJS, you use the C<length> method to determine how much memory is\nallocated by a buffer. This is not the same as the size of the buffer's\ncontents.\n\n=begin code :lang<javascript>\nconst buf = Buffer.alloc(16);\nbuf.write('🦋');\nconsole.log(buf.length); // OUTPUT: «16␤»\n=end code\n\nIn Raku, you can use the L<C<elems>|/routine/elems> method:\n\n=begin code :lang<raku>\nmy $buf = Buf.allocate(16);\n$buf.splice(0, '🦋'.encode.bytes, '🦋'.encode('utf-8'));\nsay $buf.elems; # OUTPUT: «16␤»\n=end code\n\n=head3 C<copy>\n\nYou use the C<copy> method to copy the contents of one buffer onto another.\n\n=begin code :lang<javascript>\nconst target = Buffer.alloc(24);\nconst source = Buffer.from('🦋', 'utf-8');\ntarget.write('Happy birthday! ', 'utf-8');\nsource.copy(target, 16);\nconsole.log(target.toString('utf-8', 0, 20)); // OUTPUT: «Happy birthday! 🦋␤»\n=end code\n\nThere's no C<copy> method in Raku, however you can use the C<splice> method for\nthe same result:\n\n=begin code :lang<raku>\nmy $target = Buf.allocate(24);\nmy $encoded-string = 'Happy birthday! '.encode('utf-8');\n$target.splice(0, $encoded-string.bytes, $encoded-string);\nmy $source = '🦋'.encode('utf-8');\n$target.splice(16, $source.bytes, $source);\nsay $target.subbuf(0, 20).decode('utf-8'); # OUTPUT: «Happy birthday! 🦋␤»\n=end code\n\n=head3 C<slice>\n\nYou can slice a subset of a buffer using the C<slice> method, which returns a\nreference to the subset of the memory space. Thus modifying the slice will also\nmodify the original buffer.\n\n=begin code :lang<javascript>\n// setup\nconst target = Buffer.alloc(24);\nconst source = Buffer.from('🦋', 'utf-8');\ntarget.write('Happy birthday! ', 'utf-8');\nsource.copy(target, 16);\n\n// slicing off buffer\nconst animal = target.slice(16, 20);\nanimal.write('🐪');\nconsole.log(animal.toString('utf-8'); // OUTPUT: «🐪␤»\n\nconsole.log(target.toString('utf-8', 0, 20)); // OUTPUT: «Happy birthday! 🐪␤»\n=end code\n\nHere we sliced off C<target> and stored the resulting buffer in C<animal>, which\nwe ultimately modified. This resulted on C<target> being modified.\n\nIn Raku, you can use the L<C<subbuf>|/routine/subbuf> method:\n\n=begin code :lang<raku>\n# setup\nmy $target = Buf.allocate(24);\nmy $encoded-string = 'Happy birthday! '.encode('utf-8');\n$target.splice(0, $encoded-string.bytes, $encoded-string);\nmy $source = '🦋'.encode('utf-8');\n$target.splice(16, $source.bytes, $source);\n\n# slicing off buffer\nmy $animal = $target.subbuf(16, 20);\n$animal.splice(0, $animal.bytes, '🐪'.encode('utf-8'));\nsay $animal.decode; # OUTPUT: «🐪␤»\n\nsay $target.subbuf(0, 20).decode('utf-8'); # OUTPUT: «Happy birthday! 🦋␤»\n=end code\n\nHowever, unlike NodeJS's C<slice> method, C<subbuf> returns a brand new buffer.\nTo get a hold of a writable reference to a subset of a buffer, use\nL<C<subbuf-rw>|/routine/subbuf-rw>:\n\n=begin code :lang<raku>\n# setup\nmy $target = Buf.allocate(24);\nmy $encoded-string = 'Happy birthday! '.encode('utf-8');\n$target.splice(0, $encoded-string.bytes, $encoded-string);\nmy $source = '🦋'.encode('utf-8');\n$target.splice(16, $source.bytes, $source);\n\n# slicing off buffer\n$target.subbuf-rw(16, 4) = '🐪'.encode('utf-8');\n\nsay $target.subbuf(0, 20).decode('utf-8'); # OUTPUT: «Happy birthday! 🐪␤»\n=end code\n\n=head1 The networking API\n\n=head2 Net\n\nIn Raku, there are two APIs for dealing with networking: L<C<IO::Socket::INET>|/type/IO::Socket::INET>\n(for synchronous networking), and L<C<IO::Socket::Async>|/type/IO::Socket::Async> (for asynchronous\nnetworking).\n\nL<C<IO::Socket::INET>|/type/IO::Socket::INET> currently only supports TCP connections. Its API resembles\nthat of C's socket API. If you're familiar with that, then it won't take long\nto understand how to use it. For example, here's an echo server that closes the\nconnection after receiving its first message:\n\n=begin code\nmy IO::Socket::INET $server .= new:\n    :localhost<localhost>,\n    :localport<8000>,\n    :listen;\n\nmy IO::Socket::INET $client .= new: :host<localhost>, :port<8000>;\n$client.print: 'Hello, world!';\n\nmy IO::Socket::INET $conn = $server.accept;\nmy Str $msg               = $conn.recv;\nsay $msg; # OUTPUT: Hello, world!\n$conn.print($msg);\n\nsay $client.recv; # OUTPUT: Hello, world!\n$conn.close;\n$client.close;\n$server.close;\n=end code\n\nBy default, L<C<IO::Socket::INET>|/type/IO::Socket::INET> connections are IPv4 only. To use IPv6 instead,\npass C<:family(PF_INET6)> when constructing a server or a client.\n\nIn contrast, L<C<IO::Socket::Async>|/type/IO::Socket::Async> supports both IPv4 and IPv6 without the need\nto specify which family you wish to use. It also supports UDP sockets. Here's\nhow you would write the same echo server as above asynchronously (note that\nC<Supply.tap> is multithreaded; if this is undesirable, use C<Supply.act>\ninstead:\n\n=begin code\nmy $supply = IO::Socket::Async.listen('localhost', 8000);\nmy $server = $supply.tap(-> $conn {\n    $conn.Supply.tap(-> $data {\n        say $data; # OUTPUT: Hello, world!\n        await $conn.print: $data;\n        $conn.close;\n    })\n});\n\nmy $client = await IO::Socket::Async.connect('localhost', 8000);\n$client.Supply.tap(-> $data {\n    say $data; # OUTPUT: Hello, world!\n    $client.close;\n    $server.close;\n});\n\nawait $client.print: 'Hello, world!';\n=end code\n\nThe equivalent code in Node.js looks like this:\n\n=begin code :lang<javascript>\nconst net = require('net');\n\nconst server = net.createServer(conn => {\n    conn.setEncoding('utf8');\n    conn.on('data', data => {\n        console.log(data); # OUTPUT: Hello, world!\n        conn.write(data);\n        conn.end();\n    });\n}).listen(8000, 'localhost');\n\nconst client = net.createConnection(8000, 'localhost', () => {\n    client.setEncoding('utf8');\n    client.on('data', data => {\n        console.log(data); # OUTPUT: Hello, world!\n        client.end();\n        server.close();\n    });\n    client.write(\"Hello, world!\");\n});\n=end code\n\n=head2 HTTP/HTTPS\n\nRaku doesn't natively support HTTP/HTTPS. However, CPAN packages such as\nL<Cro|https://cro.services/> help fill the gap.\n\n=head2 DNS\n\nRaku does not currently support the majority of the features that Node.js's DNS\nmodule implements. L<C<IO::Socket::INET>|/type/IO::Socket::INET> and L<C<IO::Socket::Async>|/type/IO::Socket::Async> can resolve\nhostnames, but features like resolving DNS records and reverse IP lookups are\nnot implemented yet. There are some modules that are a work in progress,\nsuch as L<Net::DNS::BIND::Manage|https://github.com/tbrowder/Net-DNS-BIND-Manage-Perl6/>,\nthat aim to improve DNS support.\n\n=head2 Punycode\n\nPunycode support is available through the L<Net::LibIDN|https://github.com/Kaiepi/p6-Net-LibIDN>,\nL<Net::LibIDN2|https://github.com/Kaiepi/p6-Net-LibIDN2>, and\nL<IDNA::Punycode|https://github.com/FROGGS/p6-IDNA-Punycode> modules on CPAN.\n\n=head1 The filesystem API\n\n=comment TODO\n\n# TBD\n\n=head1 Modules and packages\n\n=comment TODO\n\n# TBD\n\n=end pod\n"
  },
  {
    "path": "doc/Language/list.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Lists, sequences, and arrays\n\n=SUBTITLE Positional data constructs\n\nLists have been a central part of computing since before there were\ncomputers, during which time many devils have taken up residence in\ntheir details. They were actually one of the hardest parts of Raku to\ndesign, but through persistence and patience, Raku has arrived with an\nelegant system for handling them.\n\n=head1 Literal lists\n\nLiteral L<C<List>|/type/List>s are created with commas and semicolons, B<not>\nwith parentheses (which only group things), so:\n\n    1, 2;                # This is two-element list\n    our $list = (1, 2);  # This is also a List, in parentheses\n    $list = (1; 2);      # same List (see below)\n    $list = (1);         # This is not a List, just a 1 in parentheses\n    $list = (1,);        # This is a one-element List\n\nThere is one exception, empty lists are created with just a pair of parentheses:\n\n=for code\n();          # This is an empty List\n=for code :skip-test<syntax error>\n(,);         # This is a syntax error\n\nNote that hanging commas are just fine as long as the beginning and\nend of a list are clear, so feel free to use them for easy code editing.\n\nParentheses can be used to mark the beginning and end of a L<C<List>|/type/List>, so:\n\n    (1, 2), (1, 2); # This is a list of two lists.\n\nL<C<List>|/type/List>s of L<C<List>|/type/List>s can also be created by combining comma and semicolon.\nThis is also called multi-dimensional syntax, because it is most often used to\nindex multidimensional arrays.\n\n    say so (1,2; 3,4) eqv ((1,2), (3,4));\n    # OUTPUT: «True␤»\n    say so (1,2; 3,4;) eqv ((1,2), (3,4));\n    # OUTPUT: «True␤»\n    say so (\"foo\";) eqv (\"foo\") eqv ((\"foo\")); # not a list\n    # OUTPUT: «True␤»\n\nUnlike a comma, a hanging semicolon does not create a multidimensional list\nin a literal.  However, be aware that this behavior changes in most argument\nlists, where the exact behavior depends on the function... But will usually\nbe:\n\n    say('foo';);   # a list with one element and the empty list\n    # OUTPUT: «(foo)()␤»\n    say(('foo';)); # no list, just the string \"foo\"\n    # OUTPUT: «foo␤»\n\nBecause the semicolon doubles as a\nL<statement terminator|/language/control#Statements>\nit will end a literal list when used at the top level, instead creating\na statement list.  If you want to create a statement list inside parenthesis,\nuse a sigil before the parenthesis:\n\n    say so (42) eqv $(my $a = 42; $a;);\n    # OUTPUT: «True␤»\n    say so (42,42) eqv (my $a = 42; $a;);\n    # OUTPUT: «True␤»\n\nIndividual elements can be pulled out of a list using a subscript.  The\nfirst element of a list is at index number zero:\n\n=for code\nsay (1, 2)[0];  # says 1\nsay (1, 2)[1];  # says 2\nsay (1, 2)[2];  # says Nil\n\nCounting backwards from the end is done with the L<C<Whatever>|/type/Whatever> star\n(details on the page on L<Subscripts|/language/subscripts#From_the_end>):\n=for code :skip-test<syntax error>\nsay (1, 2)[*-1]; # says 2\nsay (1, 2)[-1];  # Error\n\nTo access elements of nested (multidimensional) lists,\nseparate the indices for different dimensions with semicolons:\n=for code\nsay ((<a b>,<c d>),(<e f>,<g h>))[1;0;1]; # says \"f\"\n\nPulling out multiple elements at once is possible\nby passing lists or ranges of indices;\nthis is described in sections L<Slice indexing context|#Slice_indexing_context>\nand L<Range as slice|#Range_as_slice>.\n\n=head1 The @ sigil\n\nVariables in Raku whose names bear the C<@> sigil are expected to\ncontain some sort of list-like object. Other variables may\nalso contain these objects, but C<@>-sigiled variables always do, and\nare expected to act the part.\n\nBy default, when you assign a L<C<List>|/type/List> to an C<@>-sigiled variable, you create an\nL<C<Array>|/type/Array>. Those are described below. If instead you want to refer directly to a\nL<C<List>|/type/List> object using an C<@>-sigiled variable, you can use binding with C<:=>\ninstead.\n\n    my @a := 1, 2, 3;\n\nOne of the ways C<@>-sigiled variables act like lists is by always supporting\nL<positional subscripting|/language/subscripts>. Anything bound to an\nC<@>-sigiled value must support the L<C<Positional>|/type/Positional> role which\nguarantees that the following is going to fail:\n\n    my @a := 1; # Type check failed in binding; expected Positional but got Int\n\n\n\n=head1 Reset a list container\n\nTo remove all elements from a Positional container assign\nL<C<Empty>|/type/Slip#constant_Empty>, the empty list C<()> or a L<C<Slip>|/type/Slip> of the empty\nlist to the container.\n\n    my @a = 1, 2, 3;\n    @a = ();\n    @a = Empty;\n    @a = |();\n\n=head1 Iteration\n\nAll lists may be iterated, which means taking each element from the\nlist in order and stopping after the last element:\n\n    for 1, 2, 3 { .say }  # OUTPUT: «1␤2␤3␤»\n\n=head2 X<Single Argument Rule|Language,Single Argument Rule>\n\nIt is the rule by which the set of parameters passed to an iterator such\nas C<for> is treated as a single argument, instead of several arguments;\nthat is C<some-iterator( a, b, c, ...)> will always be treated as\nC<some-iterator( list-or-array(a, b, c))>. In this example\n\n=begin code\nmy @list = [ (1, 2, 3),\n             (1, 2, ),\n             [<a b c>, <d e f>],\n             [[1]] ];\n\nfor @list -> @element {\n    say \"{@element} → {@element.^name}\";\n    for @element -> $sub-element {\n        say $sub-element;\n    }\n}\n# OUTPUT:\n#1 2 3 → List\n#1\n#2\n#3\n#1 2 → List\n#1\n#2\n#a b c d e f → Array\n#(a b c)\n#(d e f)\n#1 → Array\n#1\n=end code\n\nSince what C<for> receives is a single argument, it will be treated as a\nlist of elements to iterate over. The rule of thumb is that\nL<if there's a comma, anything preceding it is an element|https://perl6advent.wordpress.com/2015/12/14/day-15-2015-the-year-of-the-great-list-refactor/>\nand the list thus created becomes the I<single element>. That happens in\nthe case of the two arrays separated by a comma which is the third element in\nthe L<C<Array>|/type/Array> we are iterating in this example. In general, quoting the article\nlinked\nabove, the single argument rule I<... makes for behavior as the programmer\nwould expect>.\n\nThis rule is equivalent to saying that arguments to iterators will not\nflatten, will not de-containerize, and will behave as if a single argument\nhas been handed to them, whatever the shape that argument has.\n\n=for code\nmy @a = 1,2; .say for @a, |@a;     # OUTPUT: «[1 2]␤1␤2␤»\nmy @a = 1,2; .say for $[@a, |@a ]; # OUTPUT: «[[1 2] 1 2]␤»\n\nIn the second case, the single argument is a single element, since we have\nitemized the array. There's an exception to the single argument rule\nL<mentioned in the Synopsis|https://github.com/Raku/old-design-docs/blob/master/S07-lists.pod#The_single_argument_rule>:\nlists or arrays with a single element will be flattened:\n\n=for code\nmy @a = 1,2; .say for [[@a ]];     # OUTPUT: «1␤2␤»\n\nThe result may be a bit surprising in the case of using a trailing comma:\n=for code\nmy @a = 1,2; .say for @a,;         # OUTPUT: «[1 2]␤»\n\nBut the L<comma operator|/routine/,> is actually building a higher-order\nL<C<List>|/type/List> with a single element, which is also a L<C<List>|/type/List>. So not so surprising.\nSince it's got a single element, any higher-order list will be also flattened\nas above:\n\n=for code\nmy @a = 1,2; .say for [@a,];       # OUTPUT: «[1 2]␤»\n\n=head1 Testing for elements\n\nTo test for elements in a L<C<List>|/type/List> or L<C<Array>|/type/Array>, you can use the\nL<\"is element of\"|/language/setbagmix#infix_(elem),_infix_∈>\nL<C<Set>|/type/Set> operator.\n\n    my @a = <foo bar buzz>;\n    say 'bar' (elem) @a;    # OUTPUT: «True␤»\n    say 'bar' ∈ @a;         # same, using unicode version of operator\n\nThis is the equivalent of:\n\n=for code :preamble<my @a>\n'bar' (elem) @a.Set;    # convert the array to a Set first\n\nexcept that, if possible, it won't actually do the conversion.\n\nIt basically compares the value with each element in the array using the\nL<===|/routine/===> infix operator.  If you want to use another way to\ncompare values, you probably should use\nL<first|/routine/first#(List)_routine_first>.\n\n=head2 Sequences\n\nNot all lists are born full of elements.  Some only create as many\nelements as they are asked for.  These are called sequences, which are\nof type L<C<Seq>|/type/Seq>. As it so happens, loops return L<C<Seq>|/type/Seq>s.\n\n    (loop { 42.say })[2]  # OUTPUT: «42␤42␤42␤»\n\nSo, it is fine to have infinite lists in Raku, just so long as you\nnever ask them for all their elements.  In some cases, you may want to\navoid asking them how long they are too – Raku will try to return\nC<Inf> if it knows a sequence is infinite, but it cannot always know.\n\nThese lists can be built using the L<...|/language/operators#infix_...> operator,\nwhich builds lazy lists using a variety of generating expressions.\n\nAlthough the L<C<Seq>|/type/Seq> class does provide some positional subscripting, it\ndoes not provide the full interface of L<C<Positional>|/type/Positional>, so an C<@>-sigiled\nvariable may B<not> be bound to a L<C<Seq>|/type/Seq>, and trying to do so will yield\nan error.\n\n    my @s := <a b c>.Seq; CATCH { default { say .^name, ' ', .Str } }\n    # OUTPUT: «X::TypeCheck::Binding Type check failed in binding; expected Positional but got Seq ($((\"a\", \"b\",\"c\").Seq))␤»\n\nThis is because the L<C<Seq>|/type/Seq> does not keep values around after you have\nused them. This is useful behavior if you have a very long sequence, as\nyou may want to throw values away after using them, so that your program\ndoes not fill up memory. For example, when processing a file of a\nmillion lines:\n\n    =begin code :preamble<sub do-something-with($x){ }>\n    for 'filename'.IO.lines -> $line {\n        do-something-with($line);\n    }\n    =end code\n\nYou can be confident that the entire content of the file will not stay\naround in memory, unless you are explicitly storing the lines somewhere.\n\nOn the other hand, you may want to keep old values around in some cases.\nIt is possible to hide a L<C<Seq>|/type/Seq> inside a L<C<List>|/type/List>, which will still be\nlazy, but will remember old values. This is done by calling the C<.list>\nmethod. Since this L<C<List>|/type/List> fully supports L<C<Positional>|/type/Positional>, you may bind it\ndirectly to an C<@>-sigiled variable.\n\n    my @s := (loop { 42.say }).list;\n    @s[2]; # says 42 three times\n    @s[1]; # does not say anything\n    @s[4]; # says 42 two more times\n\nYou may also use the C<.cache> method instead of C<.list>, depending on\nhow you want the references handled.  See L<C<Seq>|/type/Seq> for details.\n\n=head2 Using C<.iterator>\n\nAll lists mix in the L<C<Iterator>|/type/Iterator> role, and as such have an\nC<.iterator> method they can use for a finer control over a list. We can use it\nlike this, for instance:\n\n=begin code\nmy @multiples-of-five = 0,5,10 … 500;\nmy $odd-iterator = @multiples-of-five.iterator;\nmy $odd;\nrepeat {\n    $odd-iterator.skip-one;\n    $odd = $odd-iterator.pull-one;\n    say \"→ $odd\";\n} until $odd.Str eq IterationEnd.Str;\n=end code\n\nInstead of using the iterator implicitly as we do in C<for> loops, we\nexplicitly assign it to the C<$odd-iterator> variable to work over the\nodd elements of the sequence only. That way, we can skip even elements\nusing C<.skip-one>. We do have to test explicitly for termination, which\nwe do in the C<until> expression. When there's nothing left to iterate,\nC<$odd> will have the value C<IterationEnd>. Please see\nL<C<Iterator>|/type/Iterator> for the methods and\nfunctions that are available.\n\n=head2 Slips\n\nSometimes you want to insert the elements of a list into another list.\nThis can be done with a special type of list called a\nL<C<Slip>|/type/Slip>.\n\n    say (1, (2, 3), 4) eqv (1, 2, 3, 4);         # OUTPUT: «False␤»\n    say (1, Slip.new(2, 3), 4) eqv (1, 2, 3, 4); # OUTPUT: «True␤»\n    say (1, slip(2, 3), 4) eqv (1, 2, 3, 4);     # OUTPUT: «True␤»\n\nAnother way to make a L<C<Slip>|/type/Slip> is with the C<|> prefix operator.  Note that\nthis has a tighter precedence than the comma, so it only affects a single\nvalue, but unlike the above options, it will break L<C<Scalar>|/type/Scalar>s.\n\n    say (1, |(2, 3), 4) eqv (1, 2, 3, 4);        # OUTPUT: «True␤»\n    say (1, |$(2, 3), 4) eqv (1, 2, 3, 4);       # OUTPUT: «True␤»\n    say (1, slip($(2, 3)), 4) eqv (1, 2, 3, 4);  # OUTPUT: «True␤»\n\n=head1 X<Lazy lists|Language,laziness in Iterable objects>\n\nL<C<List>|/type/List>s, L<C<Seq>|/type/Seq>s, L<C<Array>|/type/Array>s and any other class that implements the\nL<C<Iterator>|/type/Iterator> role can be lazy, which means that their values are\ncomputed on demand and stored for later use. One of the ways to create a lazy\nobject is to use L<gather/take|/language/control#gather/take> or the L<sequence\noperator|/language/operators#infix_...>. You can also write a class that\nimplements the role L<C<Iterator>|/type/Iterator> and returns C<True> on a call to\nL<is-lazy|/routine/is-lazy>. Please note that some methods like C<elems> cannot\nbe called on a lazy List and will result in a thrown\nL<C<Exception>|/type/Exception>.\n\n=begin code\n# This array is lazy and its elements will not be available\n# until explicitly requested.\n\nmy @lazy-array = lazy 1, 11, 121 ... 10**100;\nsay @lazy-array.is-lazy;     # OUTPUT: «True␤»\nsay @lazy-array[];           # OUTPUT: «[...]␤»\n\n# Once all elements have been retrieved, the list\n# is no longer considered lazy.\n\nmy @no-longer-lazy = eager @lazy-array;  # Forcing eager evaluation\nsay @no-longer-lazy.is-lazy;             # OUTPUT: «False␤»\nsay @no-longer-lazy[];\n# OUTPUT: (sequence starting with «[1 11 121» ending with a 300 digit number)\n=end code\n\nIn the example above, C<@lazy-array> is an L<C<Array>|/type/Array> which, through construction,\nis made C<lazy>. Calling C<is-lazy> on it actually calls the method mixed in by\nthe role L<C<Iterator>|/type/Iterator>, which, since it originates in a lazy list, is itself lazy.\n\nA common use case for lazy L<C<Seq>|/type/Seq>s is the processing of infinite sequences of\nnumbers, whose values have not been computed yet and cannot be computed in their\nentirety. Specific values in the List will only be computed when they are\nneeded.\n\n=for code\nmy  $l := 1, 2, 4, 8 ... Inf;\nsay $l[0..16];\n# OUTPUT: «(1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536)␤»\n\nYou can easily assign lazy objects to other objects, conserving their laziness:\n\n    my  $l := 1, 2, 4, 8 ... Inf; # This is a lazy Seq.\n    my  @lazy-array = $l;\n    say @lazy-array[10..15]; # OUTPUT: «(1024 2048 4096 8192 16384 32768)␤»\n    say @lazy-array.is-lazy; # OUTPUT: «True␤»\n\n=head1 Immutability\n\nThe lists we have talked about so far (L<C<List>|/type/List>, L<C<Seq>|/type/Seq> and L<C<Slip>|/type/Slip>)\nare all immutable.  This means you cannot remove elements from them,\nor re-bind existing elements:\n\n    =begin code\n    (1, 2, 3)[0]:delete; # Error Can not remove elements from a List\n    (1, 2, 3)[0] := 0;   # Error Cannot use bind operator with this left-hand side\n    (1, 2, 3)[0] = 0;    # Error Cannot modify an immutable Int\n    =end code\n\nHowever, if any of the elements is wrapped in a L<C<Scalar>|/type/Scalar> you\ncan still change the value which that L<C<Scalar>|/type/Scalar> points to:\n\n    my $a = 2;\n    (1, $a, 3)[1] = 42;\n    $a.say;            # OUTPUT: «42␤»\n\nthat is, it is only the list structure itself – how many elements there are\nand each element's identity – that is immutable.  The immutability is not\ncontagious past the identity of the element.\n\n=head1 List contexts\n\nSo far we have mostly dealt with lists in neutral contexts.  Lists are actually\nvery context sensitive on a syntactical level.\n\n=head2 List assignment context\n\nWhen a list (or something that is going to be converted into a list) appears on\nthe right-hand side of an assignment into an C<@>-sigiled variable, it is\n\"eagerly\" evaluated.  This means that a L<C<Seq>|/type/Seq> will be iterated until it can\nproduce no more elements, for instance.  This is one of the places you do not\nwant to put an infinite list, lest your program hang and, eventually, run out of\nmemory:\n\n    my @divisors = (gather {\n        for <2 3 5 7> {\n            take $_ if 70 %% $_;\n        }\n    });\n    say @divisors; # OUTPUT: «[2 5 7]␤»\n\nThe L<C<gather> statement|/language/control#gather/take>\ncreates a lazy list, which is eagerly evaluated when assigned to C<@divisors>.\n\n=head2 Flattening \"context\"\n\nWhen you have a list that contains sub-lists, but you only want one flat\nlist, you may flatten the list to produce a sequence of values as if all\nparentheses were removed. This works no matter how many levels deep the\nparentheses are nested.\n\n    say (1, (2, (3, 4)), 5).flat eqv (1, 2, 3, 4, 5) # OUTPUT: «True␤»\n\nThis is not really a syntactical \"context\" as much as it is a process of\niteration, but it has the appearance of a context.\n\nNote that L<C<Scalar>|/type/Scalar>s around a list will make it immune to\nflattening:\n\n    for (1, (2, $(3, 4)), 5).flat { .say } # OUTPUT: «1␤2␤(3 4)␤5␤»\n\n...but an C<@>-sigiled variable will spill its elements.\n\n    my @l := 2, (3, 4);\n    for (1, @l, 5).flat { .say };      # OUTPUT: «1␤2␤3␤4␤5␤»\n    my @a = 2, (3, 4);                 # Arrays are special, see below\n    for (1, @a, 5).flat { .say };      # OUTPUT: «1␤2␤(3 4)␤5␤»\n\n=head2 Argument list (Capture) context\n\nWhen a list appears as arguments to a function or method call, special\nsyntax rules are at play: the list is immediately converted into a\nL<C<Capture>|/type/Capture>.  A L<C<Capture>|/type/Capture> itself has a L<C<List>|/type/List> (C<.list>) and a L<C<Hash>|/type/Hash>\n(C<.hash>). Any L<C<Pair>|/type/Pair> literals whose keys are not quoted, or which are\nnot parenthesized, never make it into C<.list>.  Instead, they are\nconsidered to be named arguments and squashed into C<.hash>.  See\nL<C<Capture>|/type/Capture> for the details of this processing.\n\nConsider the following ways to make a new L<C<Array>|/type/Array> from a L<C<List>|/type/List>.\nThese ways place the L<C<List>|/type/List> in an argument list context and because of\nthat, the L<C<Array>|/type/Array> only contains C<1> and C<2> but not the L<C<Pair>|/type/Pair>\nC<:c(3)>, which is ignored.\n\n    Array.new(1, 2, :c(3));\n    Array.new: 1, 2, :c(3);\n    new Array: 1, 2, :c(3);\n\nIn contrast, these ways do not place the L<C<List>|/type/List> in argument list context,\nso all the elements, even the L<C<Pair>|/type/Pair> C<:c(3)>, are placed in the L<C<Array>|/type/Array>.\n\n    Array.new((1, 2, :c(3)));\n    (1, 2, :c(3)).Array;\n    my @a = 1, 2, :c(3); Array.new(@a);\n    my @a = 1, 2, :c(3); Array.new: @a;\n    my @a = 1, 2, :c(3); new Array: @a;\n\nIn argument list context the C<|> prefix operator applied to a L<C<Positional>|/type/Positional>\nwill always slip list elements as positional arguments to the Capture,\nwhile a C<|> prefix operator applied to an L<C<Associative>|/type/Associative> will slip pairs in\nas named parameters:\n\n    my @a := 2, \"c\" => 3;\n    Array.new(1, |@a, 4);    # Array contains 1, 2, :c(3), 4\n    my %a = \"c\" => 3;\n    Array.new(1, |%a, 4);    # Array contains 1, 4\n\n=head2 Slice indexing context\n\nFrom the perspective of the L<C<List>|/type/List> inside a L<slice subscript|/language/subscripts#Slices>,\nis only remarkable in that it is unremarkable: because\nL<adverbs|/language/subscripts#Adverbs> to a slice are attached after the C<]>,\nthe inside of a slice is B<not> an argument list, and no special processing\nof pair forms happens.\n\nMost L<C<Positional>|/type/Positional> types will enforce an integer coercion on each element\nof a slice index, so pairs appearing there will generate an error, anyway:\n\n    =begin code\n    (1, 2, 3)[1, 2, :c(3)] # OUTPUT: «Method 'Int' not found for invocant of class 'Pair'␤»\n    =end code\n\n...however this is entirely up to the type – if it defines an order\nfor pairs, it could consider C<:c(3)> a valid index.\n\nIndices inside a slice are usually not automatically flattened, but\nneither are sublists usually coerced to L<C<Int>|/type/Int>.  Instead, the list structure\nis kept intact, causing a nested slice operation that replicates the\nstructure in the result:\n\n    say (\"a\", \"b\", \"c\")[(1, 2), (0, 1)] eqv ((\"b\", \"c\"), (\"a\", \"b\")) # OUTPUT: «True␤»\n\nSlices can be taken also across several dimensions using I<semilists>, which are lists of slices separated by semicolons:\n\n    my @sliceable = [[ ^10 ], ['a'..'h'], ['Ⅰ'..'Ⅺ']];\n    say @sliceable[ ^3; 4..6 ]; # OUTPUT: «(4 5 6 e f g Ⅴ Ⅵ Ⅶ)␤»\n\nwhich is selecting the 4 to 6th element from the three first dimensions (C<^3>).\n\n=head2 Range as slice\n\nA L<C<Range>|/type/Range> is a container for a lower and an upper boundary,\neither of which may be excluded. Generating a slice with a L<C<Range>|/type/Range> will\ninclude any index between the bounds, though an infinite Range will\nL<truncate|/language/subscripts#Truncating_slices> non-existent elements.\nAn infinite range with excluded upper boundary (e.g. C<0..^Inf>) is still\ninfinite and will reach all elements.\n\n    my @a = 1..5;\n    say @a[0..2];     # OUTPUT: «(1 2 3)␤»\n    say @a[0..^2];    # OUTPUT: «(1 2)␤»\n    say @a[0..*];     # OUTPUT: «(1 2 3 4 5)␤»\n    say @a[0..^*];    # OUTPUT: «(1 2 3 4 5)␤»\n    say @a[0..Inf-1]; # OUTPUT: «(1 2 3 4 5)␤»\n\nNote that when the upper boundary is a L<C<WhateverCode>|/type/WhateverCode> instead of just a L<C<Whatever>|/type/Whatever>,\nthe range is not infinite but becomes a L<C<Callable>|/type/Callable> producing L<C<Range>|/type/Range>s. This is\nnormal behavior of the C<..> operator. The subscript operator\nL<[]|/language/subscripts#Slices> evaluates the L<C<WhateverCode>|/type/WhateverCode> providing the\nlist's C<.elems> as an argument and uses the resulting range to slice:\n\n    =begin code :preamble<my @a = 1..5>\n    say @a[0..*-1];   # OUTPUT: «(1 2 3 4 5)␤»\n    say @a[0..^*-1];  # OUTPUT: «(1 2 3 4)␤»\n    # Produces 0..^2.5 as the slice range\n    say @a[0..^*/2];  # OUTPUT: «(1 2 3)␤»\n    =end code\n\nNotice that C<0..^*> and C<0..^*+0> behave consistently in subscripts despite\none being an infinite range and the other a WhateverCode producing ranges,\nbut C<0..*+0> will give you an additional trailing L<C<Nil>|/type/Nil> because, unlike the\ninfinite range C<0..*>, it does not truncate.\n\n=head2 Array constructor context\n\nInside an Array Literal, the list of initialization values is not in capture\ncontext and is just a normal list.  It is, however, eagerly evaluated just as\nin assignment.\n\n    say so [ 1, 2, :c(3) ] eqv Array.new((1, 2, :c(3))); # OUTPUT: «True␤»\n    [while $++ < 2 { 42.say; 43 }].map: *.say;           # OUTPUT: «42␤42␤43␤43␤»\n    (while $++ < 2 { 42.say; 43 }).map: *.say;           # OUTPUT: «42␤43␤42␤43␤»\n\nWhich brings us to Arrays...\n\n=head1 Arrays\n\nL<C<Array>|/type/Array>s differ from lists in three major ways: Their elements may be typed,\nthey automatically itemize their elements, and they are mutable.  Otherwise\nthey are Lists and are accepted wherever lists are.\n\n    say Array ~~ List     # OUTPUT: «True␤»\n\nA fourth, more subtle, way they differ is that when working with Arrays, it\ncan sometimes be harder to maintain laziness or work with infinite sequences.\n\n=head2 X<Typing|Language,typed array>\n\nX<|Syntax,[ ] (typed array)>\nArrays may be typed such that their slots perform a typecheck whenever\nthey are assigned to.  An Array that only allows L<C<Int>|/type/Int> values to be assigned\nis of type C<Array[Int]> and one can create one with C<Array[Int].new>.  If\nyou intend to use an C<@>-sigiled variable only for this purpose, you may\nchange its type by specifying the type of the elements when declaring it:\n\n    =begin code\n    my Int @a = 1, 2, 3;              # An Array that contains only Ints\n    # the same as\n    my @a of Int = 1, 2, 3;           # An Array of Ints\n    my @b := Array[Int].new(1, 2, 3); # Same thing, but the variable is not typed\n    my @b := Array[Int](1, 2, 3);     # Rakudo shortcut for the same code\n    say @b eqv @a;                    # says True.\n    my @c = 1, 2, 3;                  # An Array that can contain anything\n    say @b eqv @c;                    # says False because types do not match\n    say @c eqv (1, 2, 3);             # says False because one is a List\n    say @b eq @c;                     # says True, because eq only checks values\n    say @b eq (1, 2, 3);              # says True, because eq only checks values\n\n    @a[0] = 42;                       # fine\n    @a[0] = \"foo\";                    # error: Type check failed in assignment\n    =end code\n\nIn the above example we bound a typed Array object to an C<@>-sigil variable for\nwhich no type had been specified. The other way around does not work – you may\nnot bind an Array that has the wrong type to a typed C<@>-sigiled variable:\n\n    =begin code\n    my @a := Array[Int].new(1, 2, 3);     # fine\n    @a := Array[Str].new(\"a\", \"b\");       # fine, can be re-bound\n    my Int @b := Array[Int].new(1, 2, 3); # fine\n    @b := Array.new(1, 2, 3);             # error: Type check failed in binding\n    =end code\n\nWhen working with typed arrays, it is important to remember that they are\nnominally typed. This means the declared type of an array is what matters.\nGiven the following sub declaration:\n\n    sub mean(Int @a) {\n        @a.sum / @a.elems\n    }\n\nCalls that pass an Array[Int] will be successful:\n\n    =begin code :preamble<sub mean(Int @a) {}>\n    my Int @b = 1, 3, 5;\n    say mean(@b);                       # @b is Array[Int]\n    say mean(Array[Int].new(1, 3, 5));  # Anonymous Array[Int]\n    say mean(my Int @ = 1, 3, 5);       # Another anonymous Array[Int]\n    =end code\n\nHowever, the following calls will all fail, due to passing an untyped array,\neven if the array just happens to contain Int values at the point it is\npassed:\n\n    =begin code :skip-test<illustrates error>\n    my @c = 1, 3, 5;\n    say mean(@c);                       # Fails, passing untyped Array\n    say mean([1, 3, 5]);                # Same\n    say mean(Array.new(1, 3, 5));       # Same again\n    =end code\n\nNote that in any given compiler, there may be fancy, under-the-hood, ways to\nbypass the type check on arrays, so when handling untrusted input, it can be\ngood practice to perform additional type checks, where it matters:\n\n    =begin code :preamble<my @a;my $i>\n    for @a -> Int $i { $_++.say };\n    =end code\n\nHowever, as long as you stick to normal assignment operations inside a trusted\narea of code, this will not be a problem, and typecheck errors will happen\npromptly during assignment to the array, if they cannot be caught at compile\ntime.  None of the core functions provided in Raku for operating on lists\nshould ever produce a wonky typed Array.\n\nNonexistent elements (when indexed), or elements to which L<C<Nil>|/type/Nil> has been\nassigned, will assume a default value.  This default may be adjusted on a\nvariable-by-variable basis with the C<is default> trait.  Note that an untyped\nC<@>-sigiled variable has an element type of L<C<Mu>|/type/Mu>, however its default value is\nan undefined L<C<Any>|/type/Any>:\n\n    my @a;\n    @a.of.raku.say;                 # OUTPUT: «Mu␤»\n    @a.default.raku.say;            # OUTPUT: «Any␤»\n    @a[0].say;                      # OUTPUT: «(Any)␤»\n    my Numeric @n is default(Real);\n    @n.of.raku.say;                 # OUTPUT: «Numeric␤»\n    @n.default.raku.say;            # OUTPUT: «Real␤»\n    @n[0].say;                      # OUTPUT: «(Real)␤»\n\n=head2 X<Fixed size arrays|Language,Shaped arrays>\n\nTo limit the dimensions of an L<C<Array>|/type/Array>, provide the dimensions separated by C<,>\nor C<;> in square brackets after the name of the array container in case there is more\nthan one dimension; these are called I<shaped> arrays too. The values of such a\nkind of L<C<Array>|/type/Array> will default to L<C<Any>|/type/Any>. The shape can be accessed at runtime\nvia the C<shape> method.\n\n    my @a[2,2];\n    say @a.raku;\n    # OUTPUT: «Array.new(:shape(2, 2), [Any, Any], [Any, Any])␤»\n    say @a.shape;         # OUTPUT: «(2 2)␤»\n    my @just-three[3] = <alpha beta kappa>;\n    say @just-three.raku;\n    # OUTPUT: «Array.new(:shape(3,), [\"alpha\", \"beta\", \"kappa\"])␤»\n\nShape will control the amount of elements that can be assigned by dimension:\n\n=begin code\nmy @just-two[2] = <alpha beta kappa>;\n# Will throw exception: «Index 2 for dimension 1 out of range (must be 0..1)»\n=end code\n\nAssignment to a fixed size L<C<Array>|/type/Array> will promote a List of Lists to an Array of\nArrays (making then mutable in the process).\n\n    my @a[2;2] = (1,2; 3,4);\n    say @a.Array; # OUTPUT: «[1 2 3 4]␤»\n    @a[1;1] = 42;\n    say @a.raku;\n    # OUTPUT: «Array.new(:shape(2, 2), [1, 2], [3, 42])␤»\n\nAs the third statement shows, you can assign directly to an element in a shaped\narray too. B<Note>: the second statement works only from release 2018.09.\n\nSince version 6.d,\nL<C<enum>s|/language/typesystem#enum> can be\nused also as shape parameters:\n\n=for code\nenum Cards <Trump Ace Deuce Trey>;\nmy @cards[Deuce;Deuce];\nsay @cards.shape; # OUTPUT: «(Deuce Deuce)␤»\n\n=head2 Itemization\n\nFor most uses, L<C<Array>|/type/Array>s consist of a number of slots each containing a\nL<C<Scalar>|/type/Scalar> of the correct type.  Every such L<C<Scalar>|/type/Scalar>, in turn, contains a value\nof that type. Raku will automatically type-check values and create Scalars to\ncontain them when Arrays are initialized, assigned to, or constructed.\n\nThis is actually one of the trickiest parts of Raku list handling to get a\nfirm understanding of.\n\nFirst, be aware that because itemization in Arrays is assumed, it essentially\nmeans that C<$(…)>s are being put around everything that you assign to an\narray, if you do not put them there yourself.  On the other side, Array.raku\ndoes not put C<$> to explicitly show scalars, unlike List.raku:\n\n    ((1, 2), $(3, 4)).raku.say; # says \"((1, 2), $(3, 4))\"\n    [(1, 2), $(3, 4)].raku.say; # says \"[(1, 2), (3, 4)]\"\n                                # ...but actually means: \"[$(1, 2), $(3, 4)]\"\n\nIt was decided all those extra dollar signs and parentheses were more of an\neye sore than a benefit to the user.  Basically, when you see a square bracket,\nremember the invisible dollar signs.\n\nSecond, remember that these invisible dollar signs also protect against\nflattening, so you cannot really flatten the elements inside of an Array\nwith a normal call to C<flat> or C<.flat>.\n\n    ((1, 2), $(3, 4)).flat.raku.say; # OUTPUT: «(1, 2, $(3, 4)).Seq␤»\n    [(1, 2), $(3, 4)].flat.raku.say; # OUTPUT: «($(1, 2), $(3, 4)).Seq␤»\n\nSince the square brackets do not themselves protect against flattening,\nyou can still spill the elements out of an Array into a surrounding list\nusing C<flat>.\n\n    (0, [(1, 2), $(3, 4)], 5).flat.raku.say; # OUTPUT: «(0, $(1, 2), $(3, 4), 5).Seq␤»\n\n...the elements themselves, however, stay in one piece.\n\nThis can irk users of data you provide if you have deeply nested Arrays\nwhere they want flat data.  Currently they have to deeply map the structure\nby hand to undo the nesting:\n\n    say gather [0, [(1, 2), [3, 4]], $(5, 6)].deepmap: *.take; # OUTPUT: «(0 1 2 3 4 5 6)␤»\n\n... Future versions of Raku might find a way to make this easier.\nHowever, not returning Arrays or itemized lists from functions, when\nnon-itemized lists are sufficient, is something that one should consider\nas a courtesy to their users:\n\n=item Use L<C<Slip>|/type/Slip>s when you want to always merge with surrounding lists.\n=item Use non-itemized lists when you want to make it easy for the user to flatten.\n=item Use itemized lists to protect things the user probably will not want flattened.\n=item Use L<C<Array>|/type/Array>s as non-itemized lists of itemized lists, if appropriate. (E.g. C<[$(1, 2), $(3, 4)]>.)\n=item Use L<C<Array>|/type/Array>s if the user is going to want to mutate the result without copying it first.\n\nThe fact that all elements of an array are itemized (in L<C<Scalar>|/type/Scalar>\ncontainers) is more a gentleman's agreement than a universally enforced\nrule, and it is less well enforced than typechecks in typed arrays.  See\nthe section below on binding to Array slots.\n\n=head2 Literal arrays\n\nLiteral L<C<Array>|/type/Array>s are constructed with a L<C<List>|/type/List> inside square brackets.\nThe L<C<List>|/type/List> is eagerly iterated (at compile time if possible) and values\nin it are each type-checked and itemized.  The square brackets\nthemselves will spill elements into surrounding lists when flattened,\nbut the elements themselves will not spill due to the itemization.\n\n=head2 Mutability\n\nUnlike lists, L<C<Array>|/type/Array>s are mutable.  Elements may deleted, added, or\nchanged.\n\n    my @a = \"a\", \"b\", \"c\";\n    @a.say;                  # OUTPUT: «[a b c]␤»\n    @a.pop.say;              # OUTPUT: «c␤»\n    @a.say;                  # OUTPUT: «[a b]␤»\n    @a.push(\"d\");\n    @a.say;                  # OUTPUT: «[a b d]␤»\n    @a[1, 3] = \"c\", \"c\";\n    @a.say;                  # OUTPUT: «[a c d c]␤»\n\n\n=head3 Assigning\n\nAssignment of a list to an L<C<Array>|/type/Array> is eager.  The list will be entirely\nevaluated, and should not be infinite or the program may hang.\nAssignment to a slice of an L<C<Array>|/type/Array> is, likewise, eager, but only up to\nthe requested number of elements, which may be finite:\n\n    my @a;\n    @a[0, 1, 2] = (loop { 42 });\n    @a.say;                     # OUTPUT: «[42 42 42]␤»\n\nDuring assignment, each value will be typechecked to ensure it is a\npermitted type for the L<C<Array>|/type/Array>.  Any L<C<Scalar>|/type/Scalar> will be stripped from\neach value and a new L<C<Scalar>|/type/Scalar> will be wrapped around it.\n\n=head3 Binding\n\nIndividual Array slots may be bound the same way C<$>-sigiled variables\nare:\n\n    my $b = \"foo\";\n    my @a = 1, 2, 3;\n    @a[2] := $b;\n    @a.say;          # OUTPUT: «[1 2 \"foo\"]␤»\n    $b = \"bar\";\n    @a.say;          # OUTPUT: «[1 2 \"bar\"]␤»\n\n... But binding L<C<Array>|/type/Array> slots directly to values is strongly\ndiscouraged.  If you do, expect surprises with built-in functions.  The\nonly time this would be done is if a mutable container that knows the\ndifference between values and L<C<Scalar>|/type/Scalar>-wrapped values is needed, or for\nvery large L<C<Array>|/type/Array>s where a native-typed array cannot be used. Arrays\nwith bound slots should never be supplied to unsuspecting users.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/making-modules/code.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Modules\") :category(\"tutorial\")\n\n=TITLE Making modules: the code\n\n=SUBTITLE How to organize your module with regard to its usage\n\n=head1 Modules on disk\n\nWhile C<.raku> and C<.rakumod> files are sometimes\nreferred to as \"modules\", they are really just normal files that\nare loaded and compiled when you write C<need>, C<use> or C<require>.\n\nFor a C<.rakumod> file to provide a module in the sense that we've been\nusing, it needs to declare one with C<module> as documented above.\nFor example, by placing module C<M> inside C<Foo.rakumod>, we can load\nand use the module as follows:\n\n=begin code :skip-test<needs dummy module>\nuse Foo;                # find Foo.rakumod, run need followed by import\nsay M::loud-greeting;   # OUTPUT: «GREETINGS, CAMELIA!␤»\nsay friendly-greeting;  # OUTPUT: «Greetings, friend!␤»\n=end code\n\nNote the decoupling between file and module names—a C<.rakumod> file\ncan declare zero or more modules with arbitrary identifiers.\n\n=head2 File and module naming\n\nOften we want a C<.rakumod> file to provide a I<single> module and\nnothing more. Here a common convention is for the file basename to\nmatch the module name. Returning to C<Foo.rakumod>, it is apparent that\nit only provides a single module, C<M>; in this case, we might want\nto rename C<M> to C<Foo>. The amended file would then read:\n\n=begin code\nmodule Foo {\n  sub greeting ($name = 'Camelia') { \"Greetings, $name!\" }\n  our sub loud-greeting (--> Str)  { greeting().uc       }\n  sub friendly-greeting is export  { greeting('friend')  }\n}\n=end code\n\nwhich can be used more consistently by the caller (note the\nrelationship between the C<use Foo> and C<Foo::>):\n\n=begin code :skip-test<needs dummy module>\nuse Foo;\nsay Foo::loud-greeting;  # OUTPUT: «GREETINGS, CAMELIA!␤»\nsay friendly-greeting;   # OUTPUT: «Greetings, friend!␤»\n=end code\n\nIf C<Foo.rakumod> is placed deeper within the source tree, e.g. at\nC<lib/Utils/Foo.rakumod>, we can elect to name the module C<Utils::Foo>\nto maintain consistency.\n\n\n=head3 The C<unit> keyword\n\nFiles that only provide a single module can be written more concisely\nwith the C<unit> keyword; C<unit module> specifies that the\nrest of the compilation unit is part of the declared module. Here's\nC<Foo.rakumod> rewritten with C<unit>:\n\n=begin code :solo\nunit module Foo;\n\nsub greeting ($name = 'Camelia') { \"Greetings, $name!\" }\nour sub loud-greeting (--> Str)  { greeting().uc       }\nsub friendly-greeting is export  { greeting('friend')  }\n=end code\n\nEverything following the unit declaration is part of the C<Foo>\nmodule specification.\n\n(Note that C<unit> can also be used with C<class>, C<grammar> and\nC<role>.)\n\n\n=head2 What happens if I omit C<module>?\n\nTo better understand what the C<module> declarator is doing in\nC<Foo.rakumod>, let's contrast it with a variant file, C<Bar.rakumod>, that\nomits the declaration. The subroutine definitions below are almost\nidentical (the only difference is in the body of C<greeting>,\nmodified for clarity):\n\n=begin code\nsub greeting ($name = 'Camelia') { \"Greetings from Bar, $name!\" }\nour sub loud-greeting (--> Str)  { greeting().uc                }\nsub friendly-greeting is export  { greeting('friend')           }\n=end code\n\nAs a reminder, here's how we used C<Foo.rakumod> before,\n\n=begin code :skip-test<needs dummy module>\nuse Foo;\nsay Foo::loud-greeting;  # OUTPUT: «GREETINGS, CAMELIA!␤»\nsay friendly-greeting;   # OUTPUT: «Greetings, friend!␤»\n=end code\n\nand here's how we use C<Bar.rakumod>,\n\n=begin code :skip-test<needs dummy module>\nuse Bar;\nsay loud-greeting;       # OUTPUT: «GREETINGS FROM BAR, CAMELIA!␤»\nsay friendly-greeting;   # OUTPUT: «Greetings from Bar, friend!␤»\n=end code\n\nNote the use of C<loud-greeting> rather than C<Bar::loud-greeting>\nas C<Bar> is not a known symbol (we didn't create a C<module> of\nthat name in C<Bar.rakumod>). But why is C<loud-greeting> callable even\nthough we didn't mark it for export? The answer is simply that\nC<Bar.rakumod> doesn't create a new package namespace—C<$?PACKAGE> is\nstill set to C<GLOBAL>—so when we declare C<loud-greeting> as C<our>,\nit is registered in the C<GLOBAL> symbol table.\n\n\n=head3 Lexical aliasing and safety\n\nThankfully, Raku protects us from accidentally clobbering call\nsite definitions (e.g. builtins). Consider the following addition\nto C<Bar.rakumod>:\n\n    our sub say ($ignored) { print \"oh dear\\n\" }\n\nThis creates a lexical alias, hiding the C<say> builtin I<inside>\nC<Bar.rakumod> but leaving the caller's C<say> unchanged. Consequently,\nthe following call to C<say> still works as expected:\n\n=begin code :skip-test<needs dummy module>\nuse Bar;\nsay 'Carry on, carry on...';  # OUTPUT: «Carry on, carry on...␤»\n=end code\n\n\n=head1 Documentation about Modules\n\n=item1 L<Using Modules: An Introduction|/language/using-modules/introduction>\n=item2 L<Using Modules: Finding and Installing|/language/using-modules/finding-installing>\n=item2 L<Using Modules: The Code|/language/using-modules/code>\n\n=item1 L<Making Modules: Introduction|/language/making-modules/introduction>\n=item2 L<Making Modules: The Code|/language/making-modules/code> (this page)\n\nWant to distribute your modules?\n=item1 L<Distributions: An introduction|/language/distributions/introduction>\n=item2 L<Distributions: The Configuration and Structure|/language/distributions/configuration-structure>\n=item2 L<Distributions: The Tools|/language/distributions/tools>\n=item2 L<Distributions: Testing|/language/distributions/testing>\n=item2 L<Distributions: Uploading|/language/distributions/uploading>\n\n\n=end pod\n"
  },
  {
    "path": "doc/Language/making-modules/introduction.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Modules\") :category(\"tutorial\")\n\n=TITLE Making modules: an introduction\n\n=SUBTITLE Understanding modules\n\nHere we need to distinguish between four things:\n\n=item A Distribution\n=item A C<package>\n=item A C<module>\n=item A C<class>/C<grammar>\n\n=head2 Distribution\n\nA Distribution is a set of related source files that are distributed together.\nThis usually includes some modules, some tests, and maybe some other resources.\n\nFor a full explanation, see\nL<Distributions: An introduction|/language/distributions/introduction>\nand the following documentation.\n\n=head2 C<package>\n\nPackages are nested namespaces of named program elements. Modules, classes and\ngrammars are all types of package.\n\nFor a full explanation see L<Packages|/language/packages>.\n\n=head2 C<module>\n\nModules are usually one or more source files that expose Raku constructs,\nsuch as classes, roles, grammars, subroutines and variables. Modules are\nusually used for distributing Raku code as libraries which can be used in\nanother Raku program.\n\nFor a full explanation see the pages linked from L<Using Modules: An Introduction|/language/using-modules/introduction>.\n\n=head2 C<class>\n\nClasses are a collection of methods and attributes grouped together for\nconvenience.  Being a package, they're also a nested namespace.\n\nFor further explanation, see:\n\n=item The L<C<class> section|/language/typesystem#class> of the Type system fundamentals\n=item The L<Classes and objects|/language/classtut> tutorial\n\n=head2 C<grammar>\n\nGrammars are a specific type of class intended for parsing text. Grammars are\ncomposed of rules, tokens and regexes which are actually methods, since grammars\nare classes.\n\nFor a full explanation see L<Grammars|/language/grammars>.\n\n=head1 Creating and using modules\n\nA module is usually a source file or set of source files that expose Raku\nconstructs N<Technically a module is a set of I<compunits> which are usually\nfiles but could come from anywhere as long as there is a I<compunit repository>\nthat can provide it. See L<S11|https://github.com/Raku/old-design-docs/blob/master/S11-modules.pod>.>.\n\nModules are typically packages (L<classes|/language/objects#Classes>,\nL<roles|/language/objects#Roles>, L<grammars|/type/Grammar>),\nL<subroutines|/language/functions>, and sometimes\nL<variables|/language/variables>. In Raku I<module> can also refer to a type of\npackage declared with the C<module> keyword (see L<Module\nPackages|/language/module-packages> and the examples below) but here we mostly\nmean \"module\" as a set of source files in a namespace.\n\n\n=head1 Documentation about Modules\n\n=item1 L<Using Modules: An Introduction|/language/using-modules/introduction>\n=item2 L<Using Modules: Finding and Installing|/language/using-modules/finding-installing>\n=item2 L<Using Modules: The Code|/language/using-modules/code>\n\n=item1 L<Making Modules: Introduction|/language/making-modules/introduction> (this page)\n=item2 L<Making Modules: The Code|/language/making-modules/code>\n\nWant to distribute your modules?\n=item1 L<Distributions: An introduction|/language/distributions/introduction>\n=item2 L<Distributions: The Configuration and Structure|/language/distributions/configuration-structure>\n=item2 L<Distributions: The Tools|/language/distributions/tools>\n=item2 L<Distributions: Testing|/language/distributions/testing>\n=item2 L<Distributions: Uploading|/language/distributions/uploading>\n\n\n=end pod\n"
  },
  {
    "path": "doc/Language/math.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"tutorial\")\n\n=TITLE Doing math with Raku\n\n=SUBTITLE Different mathematical paradigms and how they are implemented in this language\n\n=head1 Arithmetic\n\nRaku can do arithmetic using different data types. L<C<Num>|/type/Num>, L<C<Rat>|/type/Rat> and\nL<C<Complex>|/type/Complex> can all operate as a L<field under the operations of addition, subtraction, multiplication and division|https://en.wikipedia.org/wiki/Field_(mathematics)>\n(technically, it should be noted that data types dealing with floating point number representations are not a field in the mathematical sense due to the inherent\nimprecisions of their arithmetic. However, they constitute an approximate enough, computer friendly version of such mathematical objects for most of the cases).\nThe equivalent mathematical fields are:\n\n=begin table\nRaku class       Field\n=============    ==============================================\nRat              ℚ\nNum              ℝ\nComplex          ℂ\n=end table\n\nThe integers (L<C<Int>|/type/Int>), or ℤ, as they're usually called in mathematics, are not a\nmathematical field but rather a ring, since they are not closed under\nmultiplicative inverses. However, if the integer division C<div> is used, their operations will always\nyield other integers; if C</> is used, on the other hand, in general the result will be a\nL<C<Rat>|/type/Rat>.\n\nBesides, L<C<Int>|/type/Int> can do infinite-precision arithmetic (or at least infinite as\nmemory allows; C<Numeric overflow> can still occur), without falling back to\nL<C<Num>|/type/Num> if the number is too big:\n\n    my @powers = 2, 2 ** * ... Inf; say @powers[4].chars; # OUTPUT: «19729␤»\n\nAlso strictly speaking, the Rational class that behaves like a mathematical\nfield is L<C<FatRat>|/type/FatRat>. For efficiency reasons, operating with L<C<Rat>|/type/Rat>s will fall\nback to L<C<Num>|/type/Num> when the numbers are big enough or when there is a big\ndifference between numerator and denominator. L<C<FatRat>|/type/FatRat> can work with arbitrary\nprecision, the same as the default L<C<Int>|/type/Int> class.\n\nSome modules in the ecosystem can work with additional data types\nmathematically:\n\n=item L<C<Math::Vector>|https://github.com/colomon/Math-Vector>\nbasic operations for L<vectors|https://en.wikipedia.org/wiki/Coordinate_vector>.\n\n=item L<C<Math::Matrix>|https://github.com/pierre-vigier/Perl6-Math-Matrix>\noperates on L<matrices rings over numeric rings|https://en.wikipedia.org/wiki/Matrix_(mathematics)>.\n\n=item L<C<Math::Quaternion>|https://github.com/Util/Perl6-Math-Quaternion>\noperates on the L<quaternion algebra, ℍ|https://en.wikipedia.org/wiki/Quaternion>,\nwhich are a generalization of complex numbers.\n\n=item L<C<Math::Polynomial>|https://github.com/colomon/Math-Polynomial> works\nwith polynomials, and is able to do simple arithmetic with them.\n\n=item L<C<Math::Symbolic>|https://github.com/raydiak/Math-Symbolic>, for\nsymbolic math.\n\nNumbers are duck-typed automatically to the numeric class they actually\nrepresent:\n\n    .^name.say for (4, ⅗, 1e-9, 3+.1i); # OUTPUT: «Int␤Rat␤Num␤Complex␤»\n\nArithmetic operations are performed by taking into account the type of operands:\n\n    say .33-.22-.11 == 0; # OUTPUT: «True␤»\n\nIn this case, all numbers are interpreted as L<C<Rat>|/type/Rat>s, which makes the operation\nexact. In general, most other languages would interpret them as floating point\nnumbers, which can also be achieved in Raku if needed:\n\n    say .33.Num -.22.Num - .11.Num; # OUTPUT: «1.3877787807814457e-17␤»\n\nFor cases such as this, Raku also includes an C<approximately equal> operator,\nL<≅|/language/operators#infix_=~=>\n\n    say .33.Num -.22.Num - .11.Num ≅ 0; # OUTPUT: «True␤»\n\n\n=head1 Sets\n\nRaku includes the L<C<Set>|/type/Set> data type, as well as support for\nL<most set operations|/language/setbagmix#Operators_with_set_semantics>.\nL<Union and intersection|https://en.wikipedia.org/wiki/Algebra_of_sets>\nare not only native operations, they use their I<natural> symbols, ∩ and ∪. For\ninstance, this code would check the fundamental laws of the arithmetic of sets\nfor a limited number of sets:\n\n=begin code\nmy @arbitrary-numbers = ^100;\nmy \\U = @arbitrary-numbers.Set;\n\nmy @sets;\n\n@sets.push: Set.new( @arbitrary-numbers.pick( @arbitrary-numbers.elems.rand)) for @arbitrary-numbers;\n\nmy (@union, @intersection);\n\nfor @sets -> $set {\n    @union.push: $set ∩ $set === $set;\n    @intersection.push: $set ∪ $set === $set;\n}\n\nsay \"Idempotent union is \", so @union.all;\n# OUTPUT: «Idempotent union is True␤»\nsay \"Idempotent intersection is \", so @intersection.all;\n# OUTPUT: «Idempotent intersection is True␤»\nmy (@universe, @empty-set, @id-universe, @id-empty);\n\nfor @sets -> \\A {\n    @universe.push: A ∪ U === U;\n    @id-universe.push: A ∩ U === A;\n    @empty-set.push: A ∩ ∅ === ∅;\n    @id-empty.push: A ∪ ∅ === A;\n}\n\nsay \"Universe dominates \", so @universe.all;    # OUTPUT: «Universe dominates True␤»\nsay \"Empty set dominates \", so @empty-set.all;  # OUTPUT: «Empty set dominates True␤»\n\nsay \"Identity with U \", so @id-universe.all;    # OUTPUT: «Identity with U True␤»\nsay \"Identity with ∅ \", so @id-empty.all;       # OUTPUT: «Identity with ∅ True»\n=end code\n\nIn this code, which uses the L<empty set|/language/setbagmix#term_%E2%88%85>\nwhich is already defined by Raku, not only do we check if the equalities in the\nalgebra of sets hold, we also use, via L<sigilless variables|/language/variables#index-entry-\\_(sigilless_variables)> and the\nUnicode form of the set operators, expressions that are as close as possible to\nthe original form; C<A ∪ U === U>, for example, except for the use of the\nL<value identity operator C<===>|/routine/===> is very close to the actual\nmathematical expression in the L<Wikipedia entry|https://en.wikipedia.org/wiki/Algebra_of_sets>.\n\nWe can even test De Morgan's law, as in the code below:\n\n=begin code\nmy @alphabet = 'a'..'z';\nmy \\U = @alphabet.Set;\nsub postfix:<⁻>(Set $a) { U ⊖ $a }\nmy @sets;\n@sets.push: Set.new( @alphabet.pick( @alphabet.elems.rand)) for @alphabet;\nmy ($de-Morgan1,$de-Morgan2) = (True,True);\nfor @sets X @sets -> (\\A, \\B){\n    $de-Morgan1 &&= (A ∪ B)⁻  === A⁻ ∩ B⁻;\n    $de-Morgan2 &&= (A ∩ B)⁻  === A⁻ ∪ B⁻;\n}\nsay \"1st De Morgan is \", $de-Morgan1;\nsay \"2nd De Morgan is \", $de-Morgan2;\n=end code\n\nWe declare C<⁻> as the I<complement> operation, which computes the symmetrical\ndifference ⊖ between the Universal set C<U> and our set. Once that is declared,\nit is relatively easy to express operations such as the complementary of the\nunion of A and B, C<(A ∪ B)⁻>, with a notation that is very close to the original\nmathematical notation.\n\n=head1 Sequences\n\nA L<sequence|https://en.wikipedia.org/wiki/Sequence> is an I<enumerated>\ncollection of objects in which repetitions are allowed, and also a first-class\ndata type in Raku called L<C<Seq>|/type/Seq>. L<C<Seq>|/type/Seq> is able to represent infinite\nsequences, like the natural numbers:\n\n    my \\𝕟 = 1,2 … ∞;\n    say 𝕟[3];         # OUTPUT: «4␤»\n\nInfinite sequences use ∞, C<Inf> or C<*> (Whatever) as terminator. L<…|/language/operators#infix_...> is the\nlist generator, which in fact can understand arithmetic and geometric\nprogression sequences as long as you insert the first numbers:\n\n    say 1,5,9 … * > 100;\n    # OUTPUT: «(1 5 9 13 17 21 25 29 33 37 41 45 49 53 57 61 65 69 73 77 81 85 89 93 97 101)␤»\n    say 1,3,9 … * > 337; # OUTPUT: «(1 3 9 27 81 243 729)␤»\n\nThe first sequence will be terminated when the generated number is bigger than\n100; the second sequence, which is a geometric progression, when it is bigger\nthan 337.\n\nThe fact that an arbitrary generator can be used makes easy to generate\nsequences such as L<Fibonacci numbers|https://en.wikipedia.org/wiki/Fibonacci_number>:\n\n    say 1,1, * + * … * > 50;#  OUTPUT: «(1 1 2 3 5 8 13 21 34 55)␤»\n\nWe can, in fact, compute the approximation to the L<golden ratio|https://en.wikipedia.org/wiki/Golden_ratio> this way:\n\n    my @phis = (2.FatRat, 1 + 1 / * ... *);\n    my @otherphi = (1 - @phis[200], 1 + 1 / * ... *);\n    say @otherphi[^10, |(20, 30 ... 100)];  # OUTPUT:\n    # «((-0.61803398874989484820458683436563811772030918\n    # -0.61803398874989484820458683436563811772030918\n    # -0.61803398874989484820458683436563811772030918\n    # -0.61803398874989484820458683436563811772030918\n    # -0.61803398874989484820458683436563811772030918\n    # -0.618033…»\n\nThe L<Math::Sequences|https://github.com/ajs/perl6-Math-Sequences> module\nincludes many mathematical sequences, already defined for you. It has many\nL<sequences from the encyclopedia|https://oeis.org/>, some of them with their\noriginal name, such as ℤ.\n\nSome set operators also operate on sequences, and they can be used to find out if an object is part of it:\n\n    say 876 ∈ (7,14 … * > 1000) ; # OUTPUT: «False␤»\n\nIn this particular case, we can find out if C<876> is a multiple of 7 straight\naway, but the same principle holds for other sequences using complicated\ngenerators. And we can use set inclusion operators too:\n\n    say (55,89).Set ⊂ (1,1, * + * … * > 200); # OUTPUT: «True␤»\n\nThat said, it does not take into account if it is effectively a subsequence, just\nthe presence of the two elements here. Sets have no order, and even if you don't\nexplicitly cast the subsequence into a Set or explicitly cast it into a L<C<Seq>|/type/Seq>\nit will be coerced into such for the application of the inclusion operator.\n\n\n=head1 Mathematical constants\n\nRaku includes a set of mathematical constants:\n\n    say π; # OUTPUT: «3.141592653589793␤»\n    say τ; # Equivalent to 2π; OUTPUT: «6.283185307179586␤»\n    say 𝑒; # OUTPUT: «2.718281828459045␤»\n\nThese constants are also available\nthrough L<ASCII equivalents|/language/unicode_ascii>: C<e>, C<pi> and C<tau>.\n\nThe L<Math::Constants|https://github.com/JJ/p6-math-constants> module\nincludes an additional series of physical and mathematical constants such as the\npreviously mentioned golden ratio φ or the Planck's constant ℎ.\n\nSince Raku allows for definition of variables that use Unicode graphemes, and\nalso variable and constant names without any kind of sigil, it is considered a\ngood practice to use the actual mathematical name of concepts to denominate them\nwherever possible.\n\n=head1 Numerical integration of ordinary differential equations\n\nRaku is an amazing programming language, and you can do a\nlot of cool math with it. A great amount of work during an applied\nmathematician's work is to simulate the models they create. For this\nreason, in every coding language, a numerical integrator is a must-have.\nLearning how to do this in Raku can be very useful.\n\n=head2 Requirements\n\nIn Raku there are some modules in the ecosystem that can make it easier:\n=item L<C<Math::Model>|https://github.com/moritz/Math-Model>\nwhich lets you write mathematical and physical models in an easy and\nnatural way.\n=item L<C<Math::RungeKutta>|https://github.com/moritz/Math-RungeKutta>\nRunge-Kutta integration for systems of ordinary, linear differential\nequations.\n\nFor this example we are going to use\nL<C<Math::Model>|https://github.com/moritz/Math-Model> for its\nuseful syntax, but remember that this module requires\nL<C<Math::RungeKutta>|https://github.com/moritz/Math-RungeKutta> as well.\nSimply install them with I<zef> before using these examples.\n\n=head2 Malthus model\n\nLet's start with the I<'Hello World'> of mathematical Ecology:\nL<Malthusian growth model|https://en.wikipedia.org/wiki/Malthusian_growth_model>.\nA Malthusian growth model, sometimes called a simple exponential growth\nmodel, is essentially exponential growth based on the idea of the\nfunction being proportional to the speed to which the function grows.\nThe equation, then, looks like this:\n\nI<dx/dt = g*x>\n\nI<x(0) = x_0>\n\nWhere I<g> is the population growth rate, sometimes called Malthusian\nparameter.\n\nHow can we translate that into Raku? Well Math::Model brings some help\nwith a very understandable way to do that:\n\n=begin code :skip-test<needs ecosystem>\nuse Math::Model;\n\nmy $m = Math::Model.new(\n    derivatives => {\n        velocity => 'x',\n    },\n    variables   => {\n        velocity           => { $:growth_constant * $:x },\n        growth_constant    => { 1 }, # basal growth rate\n    },\n    initials    => {\n        x       => 3,\n    },\n    captures    => ('x'),\n);\n\n$m.integrate(:from(0), :to(8), :min-resolution(0.5));\n$m.render-svg('population growth malthus.svg', :title('population growth'));\n=end code\n\nTo fully understand what is going on, let's go through it step by step.\n\n=head3 Step by step explanation\n\n=begin item\nFirst we load the module that make\nthe calculations: L<C<Math::Model>|https://github.com/moritz/Math-Model>.\n\n=begin code :skip-test<Snippet for explanation purposes>\nuse Math::Model;\n=end code\n=end item\n\n=begin item\nWe create the model to add all the information in it.\n=begin code :skip-test<Snippet for explanation purposes>\nmy $m = Math::Model.new(\n=end code\n=end item\n\n=begin item\nWe declare the derivatives that are in our model. In this case, if\nyou remember our equation, we have our variable I<x> and its derivative\nI<x'> (usually know as the velocity).\n\n=begin code\nderivatives => {\n    velocity => 'x',\n},\n=end code\n=end item\n\n=begin item\nAfter that, we declare how our models evolve. We just need\nformulas for the derivatives that are not also integration variables\n(in this case, only I<x>), and for other variables we use in the formulas\n (the growth rate).\n\n=begin code\nvariables   => {\n    velocity           => { $:growth_constant * $:x},\n    growth_constant    => { 1 }, # basal growth rate\n},\n=end code\n=end item\n\n\n=begin item\nFinally we declare our initial conditions and use I<captures> to\ntell L<C<Math::Model>|https://github.com/moritz/Math-Model> which\nvariable or variables to record while the simulation is running.\n\n=begin code\ninitials    => {\n    x       => 3,\n},\ncaptures    => ('x'),\n=end code\n=end item\n\n\nAt this point our model is set. We need to run the simulation and render\n a cool plot about our results:\n=begin code :preamble<my $m>\n$m.integrate(:from(0), :to(8), :min-resolution(0.5));\n$m.render-svg('population growth malthus.svg', :title('population growth'));\n=end code\n\nThere, we select our time limits and the resolution. Next, we generate a\n plot.\nAll understood? Well, let's see our result!\n\nL<link to the image|https://rawgit.com/thebooort/perl-6-math-model-tutorial/master/population%20growth%20malthus.svg>\n\nLooks great! But to be honest, it is quite unrepresentative. Let's explore\nother examples from more complex situations!\n\n=head2 Logistic model\n\nResources aren't infinite and our population is not going to grow\nforever. P-F Verhulst thought the same thing, so he presented the\nL<logistic model|https://en.wikipedia.org/wiki/Logistic_function>. This\n model is a common model of population growth, where the rate of\n reproduction is proportional to both the existing population and the\n  amount of available resources, all else being equal.\nIt looks like this:\n\nI<dx/dt = g*x*(1-x/k)>\n\nI<x(0)=x_0>\n\nwhere the constant g defines the growth rate and k is the carrying\n capacity.\nModifying the above code we can simulate its behavior in time:\n\n=begin code :skip-test<needs ecosystem>\nuse Math::Model;\n\nmy $m = Math::Model.new(\n    derivatives => {\n        velocity => 'x',\n    },\n    variables   => {\n        velocity           => { $:growth_constant * $:x - $:growth_constant * $:x * $:x / $:k },\n        growth_constant    => { 1 },   # basal growth rate\n        k                  => { 100 }, # carrying capacity\n    },\n    initials    => {\n        x       => 3,\n    },\n    captures    => ('x'),\n);\n\n$m.integrate(:from(0), :to(8), :min-resolution(0.5));\n$m.render-svg('population growth logistic.svg', :title('population growth'));\n=end code\n\nLet's look at our cool plot:\nL<link to the image|https://rawgit.com/thebooort/perl-6-math-model-tutorial/master/population%20growth%20logistic.svg>\n\nAs you can see population growths till a maximum.\n\n=head2 Strong Allee Effect\n\nInteresting, isn't it? Even if these equations seem basic they are\nlinked to a lot of behaviors in our world, like tumor growth. But,\nbefore end, let me show you a curious case.\nLogistic model could be accurate but... What happens when, from a\ncertain threshold, the population size is so small that the survival\nrate and / or the reproductive rate drops due to the individual's inability\n to find other ones?\n\nWell, this is an interesting phenomenon described by W.C.Allee, usually\nknown as L<Allee effect|https://en.wikipedia.org/wiki/Allee_effect>.\nA simple way to obtain different behaviors associated with this effect\nis to use the logistic model as a departure, add some terms, and get a\ncubic growth model like this one:\n\nI<dx/dt=r*x*(x/a-1)*(1-x/k)>\n\nwhere all the constants are the same as before and A is called\nI<critical point>.\n\nOur code would be:\n\n=begin code :skip-test<needs ecosystem>\nuse Math::Model;\n\nmy $m = Math::Model.new(\n    derivatives => {\n        velocity_x    => 'x',\n    },\n    variables   => {\n        velocity_x           => { $:growth_constant * $:x *($:x/$:a -1)*(1- $:x/$:k) },\n        growth_constant    => { 0.7 },   # basal growth rate\n        k                  => { 100 }, # carrying capacity\n        a                  => { 15 },  # critical point\n    },\n    initials    => {\n        x       => 15,\n    },\n    captures    => ('x'),\n);\n\n$m.integrate(:from(0), :to(100), :min-resolution(0.5));\n$m.render-svg('population growth allee.svg', :title('population growth'));\n=end code\n\nTry to execute this one yourself to see the different behaviors that\narise when you change the initial condition around the critical point!\n\n=head2 Weak Allee Effect\n\nWhilst the strong Allee effect is a demographic Allee effect with a critical\npopulation size or density, the weak Allee effect is a demographic Allee effect\nwithout a critical population size or density, i.e., a population exhibiting a\nweak Allee effect will possess a reduced per capita growth rate at lower population\ndensity or size. However, even at this low population size or density, the population\nwill always exhibit a positive per capita growth rate. This model differs lightly from\nthe strong one, getting a new formula:\n\nI<dx/dt=r*x*(1-x/k)*(x/a)**n>, with n>0\n\nOur code would be:\n\n=begin code :skip-test<needs ecosystem>\nuse Math::Model;\n\nmy $m = Math::Model.new(\n    derivatives => {\n        velocity_x => 'x',\n    },\n    variables   => {\n        velocity_x           => { $:growth_constant * $:x *(1- $:x/$:k)*($:x/$:a)**$:n },\n        growth_constant    => { 0.7 },   # basal growth rate\n        k                  => { 100 }, # carrying capacity\n        a                  => { 15 },  # critical point\n        n                  => { 4  }\n    },\n    initials    => {\n        x       => 15,\n    },\n    captures    => ('x'),\n);\n\n$m.integrate(:from(0), :to(100), :min-resolution(0.5));\n$m.render-svg('population growth allee.svg', :title('population growth'));\n=end code\n\n\n\n=head2 Extra info\n\nDo you like physics? Check the original post by the creator of the\nmodules that have been used, Moritz Lenz:\nL<https://perlgeek.de/blog-en/perl-6/physical-modelling.html>.\n\n\n=end pod\n"
  },
  {
    "path": "doc/Language/module-packages.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"tutorial\")\n\n=TITLE Module packages\n\n=SUBTITLE Creating module packages for code reuse\n\n=head1 Documentation about Modules\n\n=item1 L<Using Modules: An Introduction|/language/using-modules/introduction>\n=item2 L<Using Modules: Finding and Installing|/language/using-modules/finding-installing>\n=item2 L<Using Modules: The Code|/language/using-modules/code>\n\n=item1 L<Making Modules: Introduction|/language/making-modules/introduction>\n=item2 L<Making Modules: The Code|/language/making-modules/code>\n\nWant to distribute your modules?\n=item1 L<Distributions: An introduction|/language/distributions/introduction>\n=item2 L<Distributions: The Configuration and Structure|/language/distributions/configuration-structure>\n=item2 L<Distributions: The Tools|/language/distributions/tools>\n=item2 L<Distributions: Testing|/language/distributions/testing>\n=item2 L<Distributions: Uploading|/language/distributions/uploading>\n\n\n=end pod\n"
  },
  {
    "path": "doc/Language/modules-core.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"tutorial\")\n\n=TITLE Core modules\n\n=SUBTITLE Core modules that may be useful to module authors\n\nSee L<Making Modules: The Tools|/language/distributions/tools>\n\n=end pod\n"
  },
  {
    "path": "doc/Language/modules-extra.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"tutorial\")\n\n=TITLE Module development utilities\n\n=SUBTITLE What can help you write/test/improve your module(s)\n\nSee L<Making Modules: The Tools|/language/distributions/tools>\n\n=end pod\n"
  },
  {
    "path": "doc/Language/modules.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"tutorial\")\n\n=TITLE Modules\n\n=SUBTITLE How to use, create, and distribute Raku modules\n\n=head1 Creating and using modules\n\nA module is usually a source file or set of source files that expose Raku\nconstructs N<Technically a module is a set of I<compunits> which are usually\nfiles but could come from anywhere as long as there is a I<compunit repository>\nthat can provide it. See L<S11|https://github.com/Raku/old-design-docs/blob/master/S11-modules.pod>.>.\n\nModules are typically packages (L<classes|/language/objects#Classes>,\nL<roles|/language/objects#Roles>, L<grammars|/type/Grammar>),\nL<subroutines|/language/functions>, and sometimes\nL<variables|/language/variables>. In Raku I<module> can also refer to a type of\npackage declared with the C<module> keyword (see L<Module\nPackages|/language/module-packages> and the examples below) but here we mostly\nmean \"module\" as a set of source files in a namespace.\n\n=head1 Using Modules\n\n=head2 Introduction\n\nSee L<Using Modules: An Introduction|/language/using-modules/introduction>\n\n=head2 Looking for and installing modules\n\nSee L<Using Modules: Finding and Installing|/language/using-modules/finding-installing>\n\n=head2 Loading and using modules\n\nSee L<Using Modules|/language/using-modules/code>\n\n=head1 Making Modules\n\n=head2 Terminology and basic structure\n\nSee L<Making Modules|/language/making-modules/introduction>\n\n=head2 How to organize your module with regard to its usage\n\nSee L<Making Modules|/language/making-modules/code>\n\n=head1 Distributing modules\n\nSee L<Distributions: An Introduction|/language/distributions/introduction>.\n\n=head2 Preparing the module\n\nSee L<Distributions: The Configuration and Structure|/language/distributions/configuration-structure>\n\n=head2 Tools that help with module authoring\n\nSee L<Distributions: The Tools|/language/distributions/tools>\n\n=head2 Testing modules and a distribution\n\nSee L<Distributions: Testing|/language/distributions/testing>.\n\n=head2 Uploading the module\n\nSee L<Distributions: Uploading|/language/distributions/uploading>.\n\n=head2 Discussing module development\n\nSee L<Distributions: An Introduction|/language/distributions/introduction#Contact_information>\n\n=end pod\n"
  },
  {
    "path": "doc/Language/mop.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Metaobject protocol (MOP)\n\n=SUBTITLE Introspection and the Raku object system\n\nX<|Language,MOP>\nX<|Language,Introspection>\n\nRaku is built on a metaobject layer. That means that there are objects\n(the I<metaobjects>) that control how various object-oriented constructs\n(such as classes, roles, methods, attributes or enums) behave.\n\nThe metaobject has a practical benefit to the user when a normal object's type\nis needed. For example:\n\n=begin code\nmy $arr = [1, 2];\nsay $arr.^name;   # OUTPUT: «Array␤»\n=end code\n\nTo get a more in-depth understanding of the metaobject for a C<class>, here is\nan example repeated twice: once as normal declarations in Raku, and once\nexpressed through the L<metamodel|/type/Metamodel::ClassHOW>:\n\n    class A {\n        method x() { say 42 }\n    }\n\n    A.x();\n\ncorresponds to:\n\n    constant A := Metamodel::ClassHOW.new_type( name => 'A' );  # class A {\n    A.^add_method('x', my method x(A:) { say 42 });             #   method x()\n    A.^compose;                                                 # }\n\n    A.x();\n\n(except that the declarative form is executed at compile time, and the latter\nform does not).\n\nThe metaobject behind an object can be obtained with C<$obj.HOW>, where HOW\nstands for Higher Order Workings (or, I<HOW the *%@$ does this work?>).\n\nHere, the calls with C<.^> are calls to the metaobject, so C<A.^compose> is\na shortcut for C<A.HOW.compose(A)>. The invocant is passed in the parameter\nlist as well, to make it possible to support prototype-style type systems,\nwhere there is just one metaobject (and not one metaobject per type, as\nstandard Raku does it).\n\nAs the example above demonstrates, all object oriented features are\navailable to the user, not just to the compiler. In fact the compiler just\nuses such calls to metaobjects.\n\n=head1 Metamethods\n\nThese are introspective macros that resemble method calls.\n\nMetamethods are generally named with ALLCAPS, and it is considered good style\nto avoid creating your own methods with ALLCAPS names (since they are used\nconventionally for things like L<phasers|/syntax/Phasers>. This will avoid\nconflicts with any metamethods that may appear in future versions of the\nlanguage.\n\nDefining a method with the same name as a metamethod will B<not> hide that\nmetamethod's functionality because they have special handling in the grammar.\n\n=head2 X<WHAT|Syntax,WHAT>\n\nThe type object of a value.  For example C<42.WHAT> returns the L<C<Int>|/type/Int>\ntype object.\n\n=head2 X<WHICH|Syntax,WHICH>\n\nThe object's identity value. This can be used for hashing and identity\ncomparison, and is how the C<===> infix operator is implemented.\n\n=head2 X<WHO|Syntax,WHO>\n\nThe package supporting the object.\n\n=head2 X<WHERE|Syntax,WHERE>\n\nThe memory address of the object. Note that this is not stable in\nimplementations with moving/compacting garbage collectors. Use C<WHICH> for\na stable identity indicator.\n\n=head2 X<HOW|Syntax,HOW>\n\nReturns the metaclass object, as in \"Higher Order Workings\".\n\n    say (%).HOW.^name # OUTPUT: «Perl6::Metamodel::ClassHOW+{<anon>}␤»\n\nC<HOW> returns an object of type C<Perl6::Metamodel::ClassHOW> in this case;\nobjects of this type are used to build classes. The same operation on the C<&>\nsigil will return C<Perl6::Metamodel::ParametricRoleGroupHOW>. You will be\ncalling this object whenever you use the C<^> syntax to access metamethods. In\nfact, the code above is equivalent to C<say (&).HOW.HOW.name(&)> which is much\nmore unwieldy. L<C<Metamodel::ClassHOW>|/type/Metamodel::ClassHOW> is part of the\nRakudo implementation, so use with caution.\n\n=head2 X<WHY|Syntax,WHY>\n\nThe attached L<Pod|/language/pod> value.\n\n=head2 X<DEFINITE|Syntax,DEFINITE>\n\nThe object has a valid concrete representation.  Returns C<True> for instances\n(even if they have the \"defined\" method overloaded, such as in L<C<Failure>|/type/Failure>\nobjects) and C<False> for type objects.\n\n=head2 X<VAR|Syntax,VAR>\n\nReturns the underlying L<C<Scalar>|/type/Scalar> object, if there is one.\n\nX<|Language,is itemized?>\nThe presence of a L<C<Scalar>|/type/Scalar> object indicates that the object is \"itemized\".\n\n    .say for (1, 2, 3);           # OUTPUT: «1␤2␤3␤», not itemized\n    .say for $(1, 2, 3);          # OUTPUT: «(1 2 3)␤», itemized\n    say (1, 2, 3).VAR ~~ Scalar;  # OUTPUT: «False␤»\n    say $(1, 2, 3).VAR ~~ Scalar; # OUTPUT: «True␤»\n\nPlease refer to the L<section on item\ncontext|/language/contexts#Item_context> for more information.\n\n=head1 Metaclass methods\n\nSame as you can define object and class methods (which do not have access to\nthe instance variables), you can define metaclass methods, which will work on\nthe metaclass. These are conventionally defined by a caret (C<^>) at the\nfront of the method identifier. These metaclass methods might return a type\nobject or a simple object; in general, they are only conventionally related\nto the metaobject protocol and are, otherwise, simple methods with a peculiar\nsyntax.\n\nThese methods will get called with the type name as first argument, but this\nneeds to be declared explicitly.\n\n=for code\nclass Foo {\n    method ^bar( Mu \\foo) {\n        foo.^set_name( foo.^name ~ \"[þ]\" );\n    }\n}\nmy $foo = Foo.new();\nsay $foo.^name; # OUTPUT: «Foo␤»\nFoo.^bar();\nsay $foo.^name; # OUTPUT: «Foo[þ]␤»\n\nThis metaclass method will, via invoking class metamethods, change the name\nof the class it's been declared. Since this has been acting on the metaclass,\nany new object of the same class will receive the same name; invoking C<say Foo\n.new().^name> will return the same value. As it can be seen, the metaclass\nmethod is\ninvoked with no arguments; C<\\foo> will, in this case, become the C<Foo> when\ninvoked.\n\nThe metaclass methods can receive as many arguments as you want.\n\n=for code\nclass Foo {\n    method ^bar( Mu \\foo, Str $addenda) {\n        foo.^set_name( foo.^name ~ $addenda );\n    }\n}\nFoo.new().^bar(  \"[baz]\" );\nmy $foo = Foo.new();\nsay $foo.^name;  # OUTPUT: «Foo[baz]␤»\n\nAgain, implicitly, the method call will furnish the first argument, which is\nthe type object. Since they are metaclass methods, you can invoke them on a\nclass (as above) or on an object (as below). The result will be exactly the\nsame.\n\n=head1 Structure of the metaobject system\n\nB<Note:> this documentation largely reflects the metaobject system as\nimplemented by the L<Rakudo Raku compiler|https://rakudo.org/>, since the\nL<design documents|https://design.raku.org/> are very light on details.\n\nFor each type declarator keyword, such as C<class>, C<role>, C<enum>, C<module>,\nC<package>, C<grammar> or C<subset>, there is a separate metaclass in the\nC<Metamodel::> namespace. (Rakudo implements them in the C<Perl6::Metamodel::>\nnamespace, and then maps C<Perl6::Metamodel> to C<Metamodel>).\n\nMany of these metaclasses share common functionality. For example roles,\ngrammars and classes can all contain methods and attributes, as well as being\nable to do roles.  This shared functionality is implemented in roles which are\ncomposed into the appropriate metaclasses. For example, the role L<C<Metamodel::RoleContainer>|/type/Metamodel::RoleContainer> implements the\nfunctionality that a type can hold roles and\nL<C<Metamodel::ClassHOW>|/type/Metamodel::ClassHOW>, which is the metaclass behind\nthe C<class> keyword, does this role.\n\nMost metaclasses have a C<compose> method that you must call when you're done\ncreating or modifying a metaobject. It creates method caches, validates things\nand so on, and weird behavior ensues if you forget to call it, so don't :-).\n\n=head2 Bootstrapping concerns\n\nYou might wonder how L<C<Metamodel::ClassHOW>|/type/Metamodel::ClassHOW> can be a class, when being a\nclass is defined in terms of L<C<Metamodel::ClassHOW>|/type/Metamodel::ClassHOW>, or how the roles\nresponsible for role handling can be roles. The answer is I<by magic>.\n\nJust kidding. Bootstrapping is implementation specific. Rakudo does it by\nusing the object system of the language in which itself is implemented,\nwhich happens to be (nearly) a subset of Raku known as\nL<NQP|/language/faq#What_language_is_NQP_written_in?>. NQP\nhas a primitive, class-like kind called C<knowhow>, which is used to\nbootstrap its own classes and roles implementation. C<knowhow> is built on\nprimitives that the virtual machine under NQP provides.\n\nSince the object model is bootstrapped in terms of lower-level types,\nintrospection can sometimes return low-level types instead of the ones you\nexpect, like an NQP-level routine instead of a normal L<C<Routine>|/type/Routine>\nobject, or a bootstrap-attribute instead of L<C<Attribute>|/type/Attribute>.\n\n=head2 Composition time and static reasoning\n\nIn Raku, a type is constructed as it is parsed, so in the beginning, it must\nbe mutable. However if all types were always mutable, all reasoning about them\nwould get invalidated at any modification of a type. For example the list of\nparent types and thus the result of type checking can change during that time.\n\nSo to get the best of both worlds, there is a time when a type transitions from\nmutable to immutable. This is called I<composition>, and for syntactically\ndeclared types, it happens when the type declaration is fully parsed (so usually\nwhen the closing curly brace is parsed).\n\nIf you create types through the metaobject system directly, you must call\nC<.^compose> on them before they become fully functional.\n\nMost metaclasses also use composition time to calculate some properties like\nthe method resolution order, publish a method cache, and other house-keeping\ntasks. Meddling with types after they have been composed is sometimes\npossible, but usually a recipe for disaster. Don't do it.\n\n=head2 Power and responsibility\n\nThe metaobject protocol offers much power that regular Raku code\nintentionally limits, such as calling private methods on classes that don't\ntrust you, peeking into private attributes, and other things that usually\nsimply aren't done.\n\nRegular Raku code has many safety checks in place; not so the metamodel. It\nis close to the underlying virtual machine, and violating the contracts with\nthe VM can lead to all sorts of strange behaviors that, in normal code, would\nobviously be bugs.\n\nSo be extra careful and thoughtful when writing metatypes.\n\n=head2 Power, convenience and pitfalls\n\nThe metaobject protocol is designed to be powerful enough to implement the\nRaku object system. This power occasionally comes at the cost of convenience.\n\nFor example, when you write C<my $x = 42> and then proceed to call methods on\nC<$x>, most of these methods end up acting on the L<integer|/type/Int> 42, not\non the L<scalar container|/type/Scalar> in which it is stored. This is a piece\nof convenience found in ordinary Raku. Many parts of the metaobject\nprotocol cannot afford to offer the convenience of automatically ignoring\nscalar containers, because they are used to implement those scalar containers\nas well. So if you write C<my $t = MyType; ... ; $t.^compose> you are\ncomposing the Scalar that the C<$>-sigiled variable implies, not C<MyType>.\n\nThe consequence is that you need to have a rather detailed understanding of\nthe subtleties of Raku in order to avoid pitfalls when working with the MOP,\nand can't expect the same L<\"do what I mean\"|/language/glossary#DWIM>\nconvenience that ordinary Raku code offers.\n\n=head1 Archetypes\n\nTypically, when multiple kinds of types share a property, it is\nimplemented with a metarole to be mixed into their metaclasses. However,\nnot all common properties of types can be implemented as mixins. Certain\nproperties are common to various kinds of types, but do not share enough\nbehavior to be possible to implement as mixins. These properties are\nknown as I<archetypes>.\n\nHOWs should provide an C<archetypes> metamethod that takes no arguments\nand returns a C<Metamodel::Archetypes> instance. This is used by the\ncompiler to determine what archetypes are supported by metaobjects.\nThe rest of this section will cover how each of the archetypes that\nexist in Rakudo work.\n\nX<|Language,Parameterization>\n\n=head2 parametric\n\nParametric types are incomplete types that may have an arbitrary number\nof type parameters. Here, type parameters refer to parameters of the\ntype itself; these may be any object that a signature allows you to\ninclude, not just types alone. When parameterized with type arguments,\nparametric types will produce a more complete type of some sort.\n\nIf a HOW supports parameterization, it should have the C<parametric>\narchetype and must provide a C<parameterize> metamethod. The\nC<parameterize> metamethod must accept a metaobject and may accept\nany number of type parameters as arguments, returning a metaobject.\nFor example, a C<parameterize> metamethod that allows a type to be\nparameterized with any type arguments may have this signature:\n\n    method parameterize(Mu $obj is raw, |parameters --> Mu)\n\n=head3 Parametric classes and grammars\n\nBecause of how the parametric archetype is implemented, it's possible\nfor classes and grammars to be augmented with support for\nparameterization by giving them a C<parameterize> metamethod, despite\nthe type not having the C<parametric> archetype. This can be useful in\ncases where the features of roles make them inappropriate to use for a\nparametric type.\n\nOne scenario where parametric classes and grammars are useful is when\nparameterizations of a type should override or add multiple dispatch\ncandidates to existing methods or regexes on the original parametric\ntype. This is the case with parameterizations of types like\nL<C<Array>|/type/Array> and L<C<Hash>|/type/Hash>, which may optionally be\nparameterized to mix in more type-safe versions of their methods that\nwork with instances' values directly. In Rakudo, these are implemented\nas parametric classes using the metamethods provided by\nL<C<Metamodel::Mixins>|/type/Metamodel::Mixins> and\nL<C<Metamodel::Naming>|/type/Metamodel::Naming> to create a mixin of the\nmetaobject given and reset its name before returning it. This technique\ncan be used to write extensible grammars when used in combination with\nmulti tokens, for instance:\n\n=begin code\ngrammar Bot::Grammar {\n    token TOP { <topic> || .+ }\n\n    proto token topic {*}\n    multi token topic:sym<command> { <command> <.ws> <command-args> }\n\n    token command      { '$' <!ws>+ }\n    token command-args { <!ws>+ % <.ws> }\n\n    method ^parameterize(::?CLASS:U $this is raw, +roles) {\n        my Str:D $name   = self.name: $this;\n        my Mu    $mixin := $this.^mixin: |roles;\n        $mixin.^set_name: [~] $name, '[', roles.map(*.^name).join(','), ']';\n        $mixin\n    }\n}\n\nrole Greetings[Str:D $name] {\n    multi token topic:sym<greeting> { ^ [ 'hi' | 'hello' | 'hey' | 'sup' ] <.ws> $name }\n}\n\nmy constant GreetBot = Bot::Grammar[Greetings['GreetBot']];\nGreetBot.parse: 'sup GreetBot';\nsay ~$/; # OUTPUT: «sup GreetBot␤»\n=end code\n\nParametric classes can also be used to simulate support for\nparameterization on other kinds. For instance, the\nL<Failable|https://modules.raku.org/dist/Failable:cpan:KAIEPI> ecosystem\nmodule is a parametric class that produces a subset upon\nparameterization. While the module itself does some caching to ensure no\nmore type objects are made than what's necessary, a more basic version\nof it can be implemented like so:\n\n=begin code\nclass Failable {\n    method ^parameterize(Failable:U $this is raw, Mu $obj is raw --> Mu) {\n        Metamodel::SubsetHOW.new_type:\n            name       => $this.^name ~ '[' ~ $obj.^name ~ ']',\n            refinee    => Metamodel::Primitives.is_type($obj, Any) ?? Any !! Mu,\n            refinement => $obj | Failure\n    }\n}\n=end code\n\n=end pod\n"
  },
  {
    "path": "doc/Language/nativecall.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Native calling interface\n\n=SUBTITLE Call into dynamic libraries that follow the C calling convention\n\n=head1 Getting started\n\nX<|Language,nativecall>\nX<|Traits,is native>\n\nThe simplest imaginable use of C<NativeCall> would look something like this:\n\n    use NativeCall;\n    sub some_argless_function() is native('something') { * }\n    some_argless_function();\n\nThe first line imports various traits and types. The next line looks like\na relatively ordinary Raku sub declaration—with a twist. We use the\nC<native> trait in order to specify that the sub is actually defined in a\nnative library. The platform-specific extension (e.g., C<.so> or C<.dll>),\nas well as any customary prefixes (e.g., C<lib>) will be added for you.\n\nThe first time you call \"some_argless_function\", the \"libsomething\" will be\nloaded and the \"some_argless_function\" will be located in it. A call will then\nbe made. Subsequent calls will be faster, since the symbol handle is retained.\n\nOf course, most functions take arguments or return values—but everything else\nthat you can do is just adding to this simple pattern of declaring a Raku sub,\nnaming it after the symbol you want to call and marking it with the C<native>\ntrait.\n\nYou will also need to declare and use native types, which cannot be imported\nfrom the shared library in the same way. Please check\nL<the native types page|/language/nativetypes> for more information.\n\nExcept in the case you are using your own compiled libraries, or any other\nkind of bundled library, shared libraries are versioned, i.e., they will be\nin a file C<libfoo.so.x.y.z>, and this shared library will be symlinked to\nC<libfoo.so.x>. By default, Raku will pick up that file if it's the only\nexisting one. This is why it's safer, and advisable, to always include a\nversion, this way:\n\n=for code :skip-test<simple snippet>\nsub some_argless_function() is native('foo', v1.2.3) { * }\n\nPlease check the\nL<section on the ABI/API version|/language/nativecall#ABI/API_version> for\nmore information.\n\n=head2 NativeCall helper module\n\nA non-core Raku module, B<App::GPTrixie>, has a\nRaku program, C<gptrixie>, to establish a starting code framework when\ninitiating a new NativeCall project.  It describes itself as I<A tool\nto generate NativeCall code from C headers> and its Github repository\nis L<here|https://github.com/Skarsnik/gptrixie>. For now it is only for the I<C>\nlanguage but I<C++> support is planned.\n\n=head1 Changing names\n\nSometimes you want the name of your Raku subroutine to be different from the\nname used in the library you're loading.  Maybe the name is long or has\ndifferent casing or is otherwise cumbersome within the context of the module you\nare trying to create.\n\nNativeCall provides a C<symbol> trait for you to specify the name of the native\nroutine in your library that may be different from your Raku subroutine name.\n\n=begin code :solo\nunit module Foo;\nuse NativeCall;\nour sub init() is native('foo') is symbol('FOO_INIT') { * }\n=end code\n\nInside of C<libfoo> there is a routine called C<FOO_INIT> but, since we're\ncreating a module called C<Foo> and we'd rather call the routine as\nC<Foo::init> (instead of C<Foo::FOO_INIT>), we use the C<symbol> trait to specify\nthe name of the symbol in C<libfoo> and call the subroutine whatever we want\n(C<init> in this case).\n\n=head1 Passing and returning values\n\nNormal Raku signatures and the C<returns> trait are used in order to convey\nthe type of arguments a native function expects and what it returns. Here is\nan example.\n\n    use NativeCall;\n    sub add(int32, int32) returns int32 is native(\"calculator\") { * }\n\nHere, we have declared that the function takes two 32-bit integers and returns a\n32-bit integer. You can find the other types that you may pass in the\nL<native types|/language/nativetypes> page. Note that the lack of a C<returns>\ntrait may be used to indicate I<C> C<void> return; the actual return is a L<C<Mu>|/type/Mu>\ntype object.\n\nDo I<not> use the C<void> type anywhere except in a C<Pointer> parameterization.\n\nFor strings, there is an additional C<encoded> trait to give some extra hints on\nhow to do the marshaling.\n\n    use NativeCall;\n    sub message_box(Str is encoded('utf8')) is native('gui') { * }\n\nTo specify how to marshal string return types, just apply this trait to the\nroutine itself.\n\n    use NativeCall;\n    sub input_box() returns Str is encoded('utf8') is native('gui') { * }\n\nNote that a C<NULL> string pointer can be passed by using the L<C<Str>|/type/Str> type\nobject; a C<NULL> return will also be represented by the type object.\n\nIf the C function requires the lifetime of data, say some buffer of type\nC<CArray[uint8]>, passed by pointer to exceed the function call, you have\nto ensure that the backing C<CArray[uint8]> Raku object is not destroyed\nbefore the C function expects it.\n\nThis is particularly important for strings, as the (usually preferable)\nC<is encoded>-way of passing strings creates only a temporary object that\nis automatically destroyed after the call. In this case, the argument\nmust be manually encoded:\n\n    use NativeCall;\n    # void set_foo(const char *)\n    # Records a char pointer for later usage\n    sub set_foo(CArray[uint8]) is native('foo') { * }\n    # void use_foo(void)\n    # Uses the pointer stored by set_foo()\n    sub use_foo() is native('foo') { * }\n\n    my $string = \"FOO\";\n    # Manually marshal the $string into $array. Take care that $array\n    # is not destroyed (e.g. by going out of scope) while the library\n    # still holds on to it, after set_foo().\n    #\n    # $string.encode takes care of UTF-8 encoding. If $array is used\n    # as a string by the native function, don't forget to append the\n    # NUL byte that terminates a C string: ------------v\n    my $array = CArray[uint8].new($string.encode.list, 0);\n\n    set_foo($array);\n    # ...\n    use_foo();\n    # It's fine if $array goes out of scope starting from here.\n\nX<|Traits,is repr>X<|Types,CStruct (native representation)>\n=head1 Specifying the native representation\n\nWhen working with native functions, sometimes you need to specify what kind of\nnative data structure is going to be used. C<is repr> is the term employed for\nthat.\n\n=begin code\nuse NativeCall;\n\nclass timespec is repr('CStruct') {\n    has uint32 $.tv_sec;\n    has long $.tv_nanosecs;\n}\n\nsub clock_gettime(uint32 $clock-id, timespec $tspec --> uint32) is native { * };\n\nmy timespec $this-time .=new;\n\nmy $result = clock_gettime( 0, $this-time);\n\nsay \"$result, $this-time\"; # OUTPUT: «0, timespec<65385480>␤»\n=end code\n\nThe original function we are calling,\nL<clock_gettime|https://www.man7.org/linux/man-pages/man3/clock_gettime.3.html>, uses a pointer to\nthe C<timespec> struct as second argument. We declare it as a\nL<class|/syntax/class> here, but specify its representation as C<is\nrepr('CStruct')>, to indicate it corresponds to a C data structure. When we\ncreate an object of that class, we are creating exactly the kind of pointer\nC<clock_gettime> expects. This way, data can be transferred seamlessly to and\nfrom the native interface.\n\nX<|Reference,Pointer>\n=head1 Basic use of pointers\n\nWhen the signature of your native function needs a pointer to some native type\n(C<int32>, C<uint32>, etc.) all you need to do is declare the argument C<is rw>:\n\n    use NativeCall;\n    # C prototype is void my_version(int *major, int *minor)\n    sub my_version(int32 is rw, int32 is rw) is native('foo') { * }\n    my_version(my int32 $major, my int32 $minor); # Pass a pointer to\n\nWhen you just want to use/pass a pointer using the C<Pointer> class you have to\ncreate the pointers when declaring them; then you can do this without specifying\nwhat type it points to. Here is an example:\n\n    use NativeCall;\n    # C prototype is void create_object(void **object)\n    sub create_object(Pointer is rw) is native('foo') { * }\n    my Pointer $p = Pointer.new();\n    create_object($p); # pointer is set by create_object\n\nThe C<Pointer> class can be used with types as well e.g. C<Pointer[Str]>.\nNote that Str is a pointer to a string (C<char *> in C/C++). So in that case, you\ncan use C<Pointer[Str]> or L<C<Str>|/type/Str>.\n\nSometimes you need to get a pointer (for example, a filehandle) back from a\nC library. You don't care about what it points to - you just need to grab hold\nof it. The C<Pointer> type provides for this.\n\n    use NativeCall;\n    sub Foo_init() returns Pointer is native(\"foo\") { * }\n    sub Foo_free(Pointer) is native(\"foo\") { * }\n\nThis works out OK, but you may fancy working with a type named something better\nthan C<Pointer>. It turns out that any class with the representation C<CPointer>\ncan serve this role. This means you can expose libraries that work on handles\nby writing a class like this:\n\n=begin code\nuse NativeCall;\n\nclass FooHandle is repr('CPointer') {\n    # Here are the actual NativeCall functions.\n    sub Foo_init() returns FooHandle is native(\"foo\") { * }\n    sub Foo_free(FooHandle) is native(\"foo\") { * }\n    sub Foo_query(FooHandle, Str) returns int8 is native(\"foo\") { * }\n    sub Foo_close(FooHandle) returns int8 is native(\"foo\") { * }\n\n    # Here are the methods we use to expose it to the outside world.\n    method new {\n        Foo_init();\n    }\n\n    method query(Str $stmt) {\n        Foo_query(self, $stmt);\n    }\n\n    method close {\n        Foo_close(self);\n    }\n\n    # Free data when the object is garbage collected.\n    submethod DESTROY {\n        Foo_free(self);\n    }\n}\n=end code\n\nNote that the C<CPointer> representation can do nothing more than hold a C pointer.\nThis means that your class cannot have extra attributes. However, for simple\nlibraries this may be a neat way to expose an object oriented interface to it.\n\nYou can always have an empty class:\n\n    class DoorHandle is repr('CPointer') { }\n\nAnd just use the class as you would use C<Pointer>, but with potential for\nbetter type safety and more readable code.\n\nOnce again, type objects are used to represent C<NULL> pointers.\n\n=head1 Function pointers\n\nC libraries can expose pointers to C functions as return values of functions and as\nmembers of structures such as structs and unions.\n\nExample of invoking a function pointer C<$fptr> returned by a function C<f>,\nusing a signature defining the desired function parameters and return value:\n\n=begin code :skip-test<external dependency>\nsub f() returns Pointer is native('mylib') { * }\n\nmy $fptr    = f();\nmy &newfunc = nativecast(:(Str, size_t --> int32), $fptr);\n\nsay newfunc(\"test\", 4);\n=end code\n\n=head1 Arrays\n\nNativeCall has some support for arrays. It is constrained to work with machine-size\nintegers, doubles and strings, sized numeric types, arrays of pointers, arrays of\nstructs, and arrays of arrays.\n\nRaku arrays, which support amongst other things laziness, are laid out in memory\nin a radically different way to C arrays. Therefore, the NativeCall library offers\na much more primitive CArray type, which you must use if working with C arrays.\n\nHere is an example of passing a C array.\n\n=begin code :skip-test<external dependency>\nsub RenderBarChart(Str, int32, CArray[Str], CArray[num64]) is native(\"chart\") { * }\nmy @titles := CArray[Str].new;\n@titles[0]  = 'Me';\n@titles[1]  = 'You';\n@titles[2]  = 'Hagrid';\nmy @values := CArray[num64].new;\n@values[0]  = 59.5e0;\n@values[1]  = 61.2e0;\n@values[2]  = 180.7e0;\nRenderBarChart('Weights (kg)', 3, @titles, @values);\n=end code\n\nNote that binding was used to C<@titles>, I<not> assignment! If you assign, you\nare putting the values into a Raku array, and it will not work out. If this\nall freaks you out, forget you ever knew anything about the C<@> sigil and just\nuse C<$> all the way when using NativeCall.\n\n    use NativeCall;\n    my $titles = CArray[Str].new;\n    $titles[0] = 'Me';\n    $titles[1] = 'You';\n    $titles[2] = 'Hagrid';\n\nGetting return values for arrays works out just the same.\n\nSome library APIs may take an array as a buffer that will be populated by the\nC function and, for instance, return the actual number of items populated:\n\n    use NativeCall;\n    sub get_n_ints(CArray[int32], int32) returns int32 is native('ints') { * }\n\nIn these cases it is important that the CArray has at least the number of\nelements that are going to be populated before passing it to the native\nsubroutine, otherwise the C function may stomp all over Raku's memory\nleading to possibly unpredictable behavior:\n\n=begin code :preamble<use NativeCall; sub get_n_ints($, $) {}>\nmy $number_of_ints = 10;\nmy $ints = CArray[int32].allocate($number_of_ints); # instantiates an array with 10 elements\nmy $n = get_n_ints($ints, $number_of_ints);\n=end code\n\nI<Note>: C<allocate> was introduced in Rakudo 2018.05. Before that, you had to\nuse this mechanism to extend an array to a number of elements:\n\n=begin code :preamble<use NativeCall>\nmy $ints = CArray[int32].new;\nmy $number_of_ints = 10;\n$ints[$number_of_ints - 1] = 0; # extend the array to 10 items\n=end code\n\nIt is important that you understand how arrays manage memory. When you create an\narray yourself, then you can add elements to it as you wish and it will be\nexpanded for you as required. However, this may result in it being moved in\nmemory (assignments to existing elements will never cause this, however). This\nmeans you'd best know what you're doing if you twiddle with an array after\npassing it to a C library.\n\nBy contrast, when a C library returns an array to you, then the memory can not\nbe managed by C<NativeCall>, and it doesn't know where the array ends.\nPresumably, something in the library API tells you this (for example, you know\nthat when you see a null element, you should read no further). Note that\nC<NativeCall> can offer you no protection whatsoever here - do the wrong thing,\nand you will get a segfault or cause memory corruption. This isn't a shortcoming\nof C<NativeCall>, it's the way the big bad native world works. Scared? Here,\nhave a hug. Good luck!\n\nX<|Types,CArray>\nX<|Reference,CArray methods>\n=head2 CArray methods\n\nBesides the usual methods available on every Raku instance,\nC<CArray> provides the following methods that can be used to interact with it\nfrom the Raku point of view:\n\n=item C<elems> provides the number of elements within the array;\n\n=item C<AT-POS> provides a specific element at the given position (starting\nfrom zero). This method is not intended to be used directly, but invoked\nusing the subscript notation C<[]>.\n\n=item C<list> provides the L<C<List>|/type/List> of elements within the array building\nit from the native array iterator.\n\nAs an example, consider the following simple piece of code:\n\n=begin code\nuse NativeCall;\n\nmy $native-array = CArray[int32].new( 1, 2, 3, 4, 5 );\nsay 'Number of elements: ' ~ $native-array.elems;\n\n# walk the array\nfor $native-array.list -> $elem {\n    say \"Current element is: $elem\";\n}\n\n# get every element by its index-based position\nfor 0..$native-array.elems - 1 -> $position {\n    say \"Element at position $position is \"\n          ~ $native-array[ $position ];\n}\n=end code\n\nthat produces the following output\n\n=for code :lang<output>\nNumber of elements: 5\nCurrent element is: 1\nCurrent element is: 2\nCurrent element is: 3\nCurrent element is: 4\nCurrent element is: 5\nElement at position 0 is 1\nElement at position 1 is 2\nElement at position 2 is 3\nElement at position 3 is 4\nElement at position 4 is 5\n\n=head2 CArray sub-arrays\n\nTo use a sub-array of a given CArray is a simple exercise of pointer math.\nFeel free to use the following example to create your own:\n\n=begin code :preamble<use NativeCall;>\nsub subarray (\n  $a, #= The CArray to use\n  $o  #= The offset into the array where the subarray should start\n) is export {\n  my $b = nativecast(Pointer[$a.of], $a);\n  nativecast(CArray[$a.of], $b.add($o) );\n}\n=end code\n\n=head1 Structs\n\nThanks to representation polymorphism, it's possible to declare a normal looking\nRaku class that, under the hood, stores its attributes in the same way a C\ncompiler would lay them out in a similar struct definition. All it takes is a\nquick use of the C<repr> trait:\n\n    class Point is repr('CStruct') {\n        has num64 $.x;\n        has num64 $.y;\n    }\n\nThe attributes can only be of the types that NativeCall knows how to marshal into\nstruct fields. Currently, structs can contain machine-sized integers, doubles,\nstrings, and other NativeCall objects (C<CArray>s, and those using the C<CPointer> and\nC<CStruct> reprs). Other than that, you can do the usual set of things you would with\na class; you could even have some of the attributes come from roles or have them\ninherited from another class. Methods are completely fine too. Go wild!\n\nC<CStruct> objects are passed to native functions by reference and native functions\nmust also return C<CStruct> objects by reference. The memory management\nrules for these references are very much like the rules for arrays, though simpler\nsince a struct is never resized. When you create a struct, the memory is managed for\nyou and when the variable(s) pointing to the instance of a C<CStruct> go away, the memory\nwill be freed when the GC gets to it. When a C<CStruct>-based type is used as the return\ntype of a native function, the memory is not managed for you by the GC.\n\nNativeCall currently doesn't put object members in containers, so assigning new values\nto them (with C<=>) doesn't work. Instead, you have to bind (with C<:=>) new\nvalues to the private members:\n\n=begin code :skip-test<continued example>\nclass MyStruct is repr('CStruct') {\n    has CArray[num64] $!arr;\n    has Str $!str;\n    has Point $!point; # Point is a user-defined class shown above\n\n    submethod TWEAK {\n        my $arr := CArray[num64].new;\n        $arr[0] = 0.9e0;\n        $arr[1] = 0.2e0;\n        $!arr := $arr;\n        $!str := 'Raku is fun';\n        $!point := Point.new;\n    }\n}\n=end code\n\nAs you may have predicted by now, a C<NULL> pointer is represented by the\ntype object of the struct type.\n\n=head2 C<CUnion>s\n\nLikewise, it is possible to declare a Raku class that stores its\nattributes the same way a C compiler would lay them out in a similar\nC<union> definition; using the C<CUnion> representation:\n\n=begin code\nuse NativeCall;\n\nclass MyUnion is repr('CUnion') {\n    has int32 $.flags32;\n    has int64 $.flags64;\n}\n\nsay nativesizeof(MyUnion.new);  # OUTPUT: «8␤»\n                                # ie. max(sizeof(MyUnion.flags32), sizeof(MyUnion.flags64))\n=end code\n\n=head2 Embedding CStructs, CUnions and CArrays with X<C<HAS>|Syntax,HAS>\n\nC<CStruct>s, C<CUnion>s and C<CArrays> can be in turn referenced by—or embedded into—a\nsurrounding C<CStruct> and C<CUnion>. To say the former we use C<has>\nas usual, and to do the latter we use the C<HAS> declarator\ninstead.\n\nTo embed an array, you need to provide the dimensions so the size of the array is fixed.\n\n=begin code :skip-test<continued example>\nclass MyStruct is repr('CStruct') {\n    has Point $.point;  # referenced\n    has int32 $.flags;\n}\n\nsay nativesizeof(MyStruct.new);  # OUTPUT: «16␤»\n                                 # ie. Point* + int32 + padding\n                                 # ie. 8      + 4     + 4\n\nclass MyStruct2 is repr('CStruct') {\n    HAS Point $.point;  # embedded\n    has int32 $.flags;\n    HAS int32 @.b[4] is CArray;\n}\n\nsay nativesizeof(MyStruct2.new);  # OUTPUT: «40␤»\n                                  # ie. Point + int32 + padding + 4 * int32\n                                  # ie. 16    + 4     + 4       + 4 * 4\n=end code\n\n\n=head2 Notes on memory management\n\nWhen allocating a struct for use as a struct, make sure that you allocate your\nown memory in your C functions. If you're passing a struct into a C function\nwhich needs a L<C<Str>|/type/Str>/C<char*> allocated ahead of time, be sure to assign a\ncontainer for a variable of type L<C<Str>|/type/Str> prior to passing your struct into the\nfunction.\n\n=head3 In your Raku code...\n\n=begin code :skip-test<external dependency>\nclass AStringAndAnInt is repr(\"CStruct\") {\n  has Str $.a_string;\n  has int32 $.an_int32;\n\n  sub init_struct(AStringAndAnInt is rw, Str, int32) is native('simple-struct') { * }\n\n  submethod BUILD(:$a_string, :$an_int) {\n    init_struct(self, $a_string, $an_int);\n  }\n}\n=end code\n\nIn this code we first set up our members, C<$.a_string> and\nC<$.an_int32>. After that we declare our C<init_struct()> function for\nthe C<init()> method to wrap around; this function is then called from\nC<BUILD> to effectively assign the values before returning the created\nobject.\n\nPlease note that BUILD is binding attributes of native types, such as\nC<$.an_int32>. You can always bind native types this way.\n\n=head3 In your C code...\n\n=begin code :lang<C>\ntypedef struct a_string_and_an_int32_t_ {\n  char *a_string;\n  int32_t an_int32;\n} a_string_and_an_int32_t;\n=end code\n\nHere's the structure. Notice how we've got a C<char *> there.\n\n=begin code :lang<C>\nvoid init_struct(a_string_and_an_int32_t *target, char *str, int32_t int32) {\n  target->an_int32 = int32;\n  target->a_string = strdup(str);\n\n  return;\n}\n=end code\n\nIn this function we initialize the C structure by assigning an integer\nby value, and passing the string by reference. The function allocates\nmemory that it points C<char *a_string> to within the structure as it\ncopies the string.  (Note you will also have to manage deallocation of\nthe memory as well to avoid memory leaks.)\n\n=begin code :preamble<class AStringAndAnInt {}>\n# A long time ago in a galaxy far, far away...\nmy $foo = AStringAndAnInt.new(a_string => \"str\", an_int => 123);\nsay \"foo is {$foo.a_string} and {$foo.an_int32}\";\n# OUTPUT: «foo is str and 123␤»\n=end code\n\n=head1 Typed pointers\n\nYou can type your C<Pointer> by passing the type as a parameter. It works with\nthe native type but also with C<CArray> and C<CStruct> defined types. NativeCall\nwill not implicitly allocate the memory for it even when calling C<new> on them.\nIt's mostly useful in the case of a C routine returning a pointer, or if it's a\npointer embedded in a C<CStruct>.\n\n=begin code\nuse NativeCall;\nsub strdup(Str $s --> Pointer[Str]) is native { * }\nmy Pointer[Str] $p = strdup(\"Success!\");\nsay $p.deref;\n=end code\n\nYou have to call X<C<.deref>|Language,deref> on C<Pointer>s to access the embedded type.\nIn the example above, declaring the type of the pointer avoids typecasting error\nwhen dereferenced. Please note that the original\nL<C<strdup>|https://en.cppreference.com/w/c/experimental/dynamic/strdup> returns\na pointer to C<char>; we are using C<Pointer[Str]>.\n\n=begin code :skip-test<external dependency>\nmy Pointer[int32] $p; #For a pointer on int32;\nmy Pointer[MyCstruct] $p2 = some_c_routine();\nmy MyCstruct $mc = $p2.deref;\nsay $mc.field1;\n=end code\n\nIt's quite common for a native function to return a pointer to an array of\nelements. Typed pointers can be dereferenced as an array to obtain individual\nelements.\n\n=begin code :skip-test<external dependency>\nmy $n = 5;\n# returns a pointer to an array of length $n\nmy Pointer[Point] $plot = some_other_c_routine($n);\n# display the 5 elements in the array\nfor 1 .. $n -> $i {\n    my $x = $plot[$i - 1].x;\n    my $y = $plot[$i - 1].y;\n    say \"$i: ($x, $y)\";\n}\n=end code\n\nPointers can also be updated to reference successive elements in the array:\n\n=begin code :skip-test<continued example>\nmy Pointer[Point] $elem = $plot;\n# show differences between successive points\nfor 1 ..^ $n {\n    my Point $lo = $elem.deref;\n    ++$elem; # equivalent to $elem = $elem.add(1);\n    my Point $hi = (++$elem).deref;\n    my $dx = $hi.x = $lo.x;\n    my $dy = $hi.y = $lo.y;\n    say \"$_: delta ($dx, $dy)\";\n}\n=end code\n\nVoid pointers can also be used by declaring them C<Pointer[void]>. Please\nconsult L<the native types documentation|/language/nativetypes#The_void_type>\nfor more information on the subject.\n\n=head1 Strings\n\n=head2 Explicit memory management\n\nLet's say there is some C code that caches strings passed, like so:\n\n=begin code :lang<C>\n#include <stdlib.h>\n\nstatic char *__VERSION;\n\nchar *\nget_version()\n{\n    return __VERSION;\n}\n\nchar *\nset_version(char *version)\n{\n    if (__VERSION != NULL) free(__VERSION);\n    __VERSION = version;\n    return __VERSION;\n}\n=end code\n\nIf you were to write bindings for C<get_version> and C<set_version>, they would\ninitially look like this, but will not work as intended:\n\n=begin code :skip-test<external dependency>\nsub get_version(--> Str)     is native('./version') { * }\nsub set_version(Str --> Str) is native('./version') { * }\n\nsay set_version('1.0.0'); # 1.0.0\nsay get_version;          # Differs on each run\nsay set_version('1.0.1'); # Double free; segfaults\n=end code\n\nThis code segfaults on the second C<set_version> call because it tries to free\nthe string passed on the first call after the garbage collector had already\ndone so. If the garbage collector shouldn't free a string passed to a native\nfunction, use C<explicitly-manage> with it:\n\n=begin code :skip-test<external dependency>\nsay set_version(explicitly-manage('1.0.0')); # 1.0.0\nsay get_version;                             # 1.0.0\nsay set_version(explicitly-manage('1.0.1')); # 1.0.1\nsay get_version;                             # 1.0.1\n=end code\n\nBear in mind all memory management for explicitly managed strings must be\nhandled by the C library itself or through the NativeCall API to prevent memory\nleaks.\n\n=head2 Buffers and blobs\n\nL<C<Blob>|/type/Blob>s and L<C<Buf>|/type/Buf>s are the Raku way of storing binary data. We can use them\nfor interchange of data with native functions and data structures, although not\ndirectly. We will have to use L<C<nativecast>|/routine/nativecast>.\n\n=for code :preamble<use NativeCall;>\nmy $blob = Blob.new(0x22, 0x33);\nmy $src = nativecast(Pointer, $blob);\n\nThis C<$src> can then be used as an argument for any native function that takes\na C<Pointer>. The opposite, putting values pointed to by a C<Pointer> into a L<C<Buf>|/type/Buf>\nor using it to initialize a L<C<Blob>|/type/Blob> is not directly supported. You might want to\nuse L<C<NativeHelpers::Blob>|https://github.com/salortiz/NativeHelpers-Blob> to\ndo this kind of operations.\n\n=for code :skip-test<incomplete code>\nmy $esponja = blob-from-pointer( $inter, :2elems, :type(Blob[int8]));\nsay $esponja;\n\n=head1 Function arguments\n\nNativeCall also supports native functions that take functions as arguments.  One\nexample of this is using function pointers as callbacks in an event-driven\nsystem.  When binding these functions via NativeCall, one needs only provide the\nequivalent signature as\nL<a constraint on the code parameter|/language/signatures#Constraining_signatures_of_Callables>.\nIn the case of NativeCall, however, as of Rakudo 2019.07, a space between the\nfunction argument and the signature, and the colon of a normal L<C<Signature>|/type/Signature>\nliteral is omitted, as in:\n\n    use NativeCall;\n    # void SetCallback(int (*callback)(const char *))\n    my sub SetCallback(&callback (Str --> int32)) is native('mylib') { * }\n\nNote: the native code is responsible for memory management of values passed to\nRaku callbacks this way. In other words, NativeCall will not free() strings\npassed to callbacks.\n\nIt is important that any code passed as a native callback handles its exceptions and,\nif applicable, returns an appropriate error value to the native code that invoked it.\nIt is not allowed to throw an exception out of a native callback, and doing so will\nlead to process termination.\n\n=head1 Variadic functions\n\nTo call a variadic function, specify the fixed arguments as usual but add a\nslurpy argument. When calling a variadic function, just provide as many\narguments as you like. The types of the variadic arguments are inferred by\nlooking at the passed values.\n\n=begin code :skip-test<needs variadic args support introduced in rakudo 2025.12>\nuse NativeCall;\n\n# Sums the passed int arguments. First arg is the count of the variadic args.\nsub sum_int_things(int32, **@varargs) returns int32 is native('mylib') { * }\nsay sum_things(3, 1, 2, 3);  # 6\n=end code\n\nSo one needs to cast the arguments to the intended type first.\n\n=begin code :skip-test<misses vararg support> :preamble<use NativeCall;\nsub sum_int_things(int32, **@varargs) returns int32 is native('mylib') { * }\n>\nmy $input = prompt(\"Give a number to add 5 to: \");\nsay sum_things(2, $input.Int, 5);\n=end code\n\nPassing pointers works via the C<Pointer.to()> method:\n\n=begin code :skip-test<needs variadic args support introduced in rakudo 2025.12>\nuse NativeCall;\n\n# Writes a 5 into all passed pointers.\nsub write_5_to_ints(int32, **@varargs) is native('mylib') { * }\nmy uint32 $number1;\nmy uint32 $number2;\nwrite_5_to_ints(2, Pointer.to($number1), Pointer.to($number2));\nsay \"One: $number1, Two: $number2\"; #One: 5, Two: 5\n=end code\n\n=head1 Library paths and names\n\nThe C<native> trait accepts the library name, the full path, or a subroutine\nreturning either of the two. When using the library name, the name is assumed\nto be prepended with C<lib> and appended with C<.so> (or just appended with\nC<.dll> on Windows), and will be searched for in the paths in the\nC<LD_LIBRARY_PATH> (C<PATH> on Windows) environment variable.\n\n=begin code\nuse NativeCall;\nconstant LIBMYSQL = 'mysqlclient';\nconstant LIBFOO = '/usr/lib/libfoo.so.1';\nsub LIBBAR {\n    my $path = qx/pkg-config --libs libbar/.chomp;\n    $path ~~ s/\\/[[\\w+]+ % \\/]/\\0\\/bar/;\n    $path\n}\n# and later\n\nsub mysql_affected_rows returns int32 is native(LIBMYSQL) { * };\nsub bar is native(LIBFOO) { * }\nsub baz is native(LIBBAR) { * }\n=end code\n\nYou can also put an incomplete path like './foo' and NativeCall will\nautomatically put the right extension according to the platform specification.\nIf you wish to suppress this expansion, simply pass the string as the body of a\nblock.\n\n=begin code :preamble<use NativeCall>\nsub bar is native({ './lib/Non Standard Naming Scheme' }) { * }\n=end code\n\nBE CAREFUL: the C<native> trait and C<constant> are evaluated at compile time.\nDon't write a constant that depends on a dynamic variable like:\n\n    # WRONG:\n    constant LIBMYSQL = %*ENV<P6LIB_MYSQLCLIENT> || 'mysqlclient';\n\nThis will keep the value given at compile time. A module will be precompiled and\nC<LIBMYSQL> will keep the value it acquires when the module gets precompiled.\n\n=head2 ABI/API version\n\nIf you write C<native('foo')> NativeCall will search C<libfoo.so> under Unix like\nsystem (C<libfoo.dynlib> on OS X, C<foo.dll> on win32). In most modern system it\nwill require you or the user of your module to install the development package\nbecause it's recommended to always provide an API/ABI version to a shared\nlibrary, so C<libfoo.so> ends often being a symbolic link provided only by a\ndevelopment package.\n\nTo avoid that, the C<native> trait allows you to specify the API/ABI version. It\ncan be a full version or just a part of it. (Try to stick to Major version, some\nBSD code does not care for Minor.)\n\n    use NativeCall;\n    sub foo1 is native('foo', v1) { * } # Will try to load libfoo.so.1\n    sub foo2 is native('foo', v1.2.3) { * } # Will try to load libfoo.so.1.2.3\n\n    my List $lib = ('foo', 'v1');\n    sub foo3 is native($lib) { * }\n\n\n=head2 Routine\n\nThe C<native> trait also accepts a L<C<Callable>|/type/Callable> as argument, allowing you to\nprovide your own way to handle the way it will find the library file to load.\n\n    use NativeCall;\n    sub foo is native(sub {'libfoo.so.42'}) { * }\n\nIt will only be called at the first invocation of the sub.\n\n=head2 Calling into the standard library\n\nIf you want to call a C function that's already loaded, either from the\nstandard library or from your own program, you can omit the value, so\nC<is native>.\n\nFor example on a UNIX-like operating system, you could use the following code\nto print the home directory of the current user:\n\n    use NativeCall;\n    my class PwStruct is repr('CStruct') {\n        has Str $.pw_name;\n        has Str $.pw_passwd;\n        has uint32 $.pw_uid;\n        has uint32 $.pw_gid;\n        has Str $.pw_gecos;\n        has Str $.pw_dir;\n        has Str $.pw_shell;\n    }\n    sub getuid()              returns uint32   is native { * };\n    sub getpwuid(uint32 $uid) returns PwStruct is native { * };\n\n    say getpwuid(getuid()).pw_dir;\n\nAlthough C<$*HOME> is a much easier way :-)!\n\n=head1 Exported variables\n\nVariables exported by a library – also named \"global\" or \"extern\"\nvariables – can be accessed using C<cglobal>.  For example:\n\n=for code :preamble<use NativeCall>\nmy $var := cglobal('libc.so.6', 'errno', int32)\n\nThis code binds to C<$var> a new L<C<Proxy>|/type/Proxy> object that\nredirects all its accesses to the integer variable named \"errno\" as\nexported by the C<libc.so.6> library.\n\n\n=head1 C++ support\n\nNativeCall offers support to use classes and methods from C++ as shown in\nL<https://github.com/rakudo/rakudo/blob/master/t/04-nativecall/13-cpp-mangling.t>\n(and its associated C++ file).\nNote that at the moment it's not as tested and developed as C support.\n\n=head1 Helper functions\n\nThe C<NativeCall> library exports several subroutines to help you work with\ndata from native libraries.\n\n=head2 sub nativecast\n\n    sub nativecast($target-type, $source) is export(:DEFAULT)\n\nThis will I<cast> the C<Pointer> C<$source> to an object of C<$target-type>.\nThe source pointer will typically have been obtained from a call to a native subroutine\nthat returns a pointer or as a member of a C<struct>, this may be specified as C<void *>\nin the C<C> library definition for instance, but you may also cast from a pointer to\na less specific type to a more specific one.\n\nAs a special case, if a L<C<Signature>|/type/Signature> is supplied as C<$target-type> then\na C<subroutine> will be returned which will call the native function pointed to by C<$source>\nin the same way as a subroutine declared with the C<native> trait. This is described in\nL<Function Pointers|/language/nativecall#Function_pointers>.\n\n=head2 sub cglobal\n\n    sub cglobal($libname, $symbol, $target-type) is export is rw\n\nThis returns a L<C<Proxy>|/type/Proxy> object that provides access to the C<extern>\nnamed C<$symbol> that is exposed by the specified library. The library can be\nspecified in the same ways that they can be to the C<native> trait.\n\n=head2 sub nativesizeof\n\n    sub nativesizeof($obj) is export(:DEFAULT)\n\nThis returns the size in bytes of the supplied object, it can be thought of as being\nequivalent to C<sizeof> in B<C>.  The object can be a builtin native type such as\nC<int64> or C<num64>, a C<CArray> or a class with the C<repr> C<CStruct>, C<CUnion>\nor C<CPointer>.\n\n=head2 sub explicitly-manage\n\n    sub explicitly-manage($str) is export(:DEFAULT)\n\nThis returns an object for the given L<C<Str>|/type/Str>. If the string returned is\npassed to a NativeCall subroutine, it will not be freed by the runtime's\ngarbage collector.\n\n=head1 Examples\n\nSome specific examples, and instructions to use examples above in particular\nplatforms.\n\n=head2 PostgreSQL\n\nThe PostgreSQL examples in\nL<DBIish|https://github.com/raku-community-modules/DBIish/blob/master/examples/pg.raku> make use of\nthe NativeCall library and C<is native> to use the native C<_putenv> function\ncall in Windows.\n\n=head2 MySQL\n\nB<NOTE:> Please bear in mind that, under the hood, Debian has substituted MySQL\nwith MariaDB since the Stretch version, so if you want to install MySQL, use\nL<MySQL APT repository|https://dev.mysql.com/downloads/repo/apt/> instead of the\ndefault repository.\n\nTo use the MySQL example in\nL<DBIish|https://github.com/raku-community-modules/DBIish/blob/master/examples/mysql.raku>, you'll\nneed to install MySQL server locally; on Debian-esque systems\nit can be installed with something like:\n\n=for code :lang<shell>\nwget https://dev.mysql.com/get/mysql-apt-config_0.8.10-1_all.deb\nsudo dpkg -i mysql-apt-config_0.8.10-1_all.deb # Don't forget to select 5.6.x\nsudo apt-get update\nsudo apt-get install mysql-community-server -y\nsudo apt-get install libmysqlclient18 -y\n\nPrepare your system along these lines before trying out the examples:\n\n=for code :lang<shell>\n$ mysql -u root -p\nSET PASSWORD = PASSWORD('sa');\nDROP DATABASE test;\nCREATE DATABASE test;\n\n=head2 Microsoft Windows API\n\nHere is an example of a Windows API call:\n\n=begin code :method<False>\nuse NativeCall;\n\nsub MessageBoxA(int32, Str, Str, int32)\n    returns int32\n    is native('user32')\n    { * }\n\nMessageBoxA(0, \"We have NativeCall\", \"ohai\", 64);\n=end code\n\n=head3 wchar_t\n\nPassing and receiving a C<wchar_t> string works by passing the L<C<Str>|/type/Str> encoding\nvia a trait:\n\n=begin code :method<False>\nuse NativeCall;\n\n# Using the wide character variant (notice the trailing \"W\" in the name)\nsub MessageBoxW(int32, Str is encoded('utf16'), Str is encoded('utf16'), int32\n    --> int32) is native('user32') { * }\n\nMessageBoxW(0, \"We have NativeCall\", \"ohai\", 64);\n=end code\n\nWhen passing a string as a pointer that the native function sets, one has to\nuse plain C<Pointer>s:\n\n=begin code :method<False>\nuse NativeCall;\n\nsub make-guid($val) {\n    my $buf = Buf[uint8].new;\n    for ^16 Z $val.subst('-', :g).comb(2) -> ($i, $byte-text) {\n        my $byte = $byte-text.parse-base(16).Int;\n        $buf.write-uint8: $i, $byte;\n    }\n    $buf\n}\nmy $local-appdata-guid = make-guid('F1B32785-6FBA-4FCF-9D55-7B8E7F157091');\n\nsub SHGetKnownFolderPath(\n  Buf[uint8]      $rfid,\n  uint32          $dwFlags,\n  Pointer         $hToken,\n  Pointer[uint16] $ppszPath is rw\n  --> int32) is native('Shell32') { * }\n\nmy Pointer[uint16] $path-pointer .= new;\nSHGetKnownFolderPath($local-appdata-guid, 0, 0, $path-pointer);\n\nmy $buf = Buf[uint8].new;\nmy $pos = 0;\nwhile $path-pointer.deref() != 0 {\n    $buf.write-uint16($pos, $path-pointer.deref());\n    $pos += 2;\n    $path-pointer++;\n}\n$buf.write-uint16($pos, 0);\nmy $path = $buf.decode('utf16');\n=end code\n\n=head2 Short tutorial on calling a C function\n\nThis is an example for calling a standard function and using the returned\ninformation in a Raku program.\n\nC<getaddrinfo> is a POSIX standard function for obtaining network information\nabout a network node, e.g., C<google.com>. It is an interesting function to look\nat because it illustrates a number of the elements of NativeCall.\n\nThe Linux manual provides the following information about the C callable function:\n\n=begin code :lang<C>\nint getaddrinfo(const char *node, const char *service,\n       const struct addrinfo *hints,\n       struct addrinfo **res);\n=end code\n\nThe function returns a response code 0 for success and 1 for error. The data are\nextracted from a linked list of C<addrinfo> elements, with the first element\npointed to by C<res>.\n\nFrom the table of NativeCall types we know that an C<int> is C<int32>.\nWe also know that a C<char *> is one of the forms C for a C Str, which maps\nsimply to L<C<Str>|/type/Str>. But C<addrinfo> is a structure, which means we\nwill need to write our own type class. However, the function declaration is\nstraightforward:\n\n=begin code :method :preamble<use NativeCall;\nclass SockAddr is repr('CStruct') {\n    has int32    $.sa_family;\n    has Str      $.sa_data;\n};\nclass Addrinfo is repr('CStruct') {\n    has int32     $.ai_flags;\n    has int32     $.ai_family;\n    has int32     $.ai_socktype;\n    has int32     $.ai_protocol;\n    has int32     $.ai_addrlen;\n    has SockAddr  $.ai_addr       is rw;\n    has Str       $.ai_cannonname is rw;\n    has Addrinfo  $.ai_next       is rw;\n\n};\n>\nsub getaddrinfo( Str $node, Str $service, Addrinfo $hints, Pointer $res is rw )\n    returns int32\n    is native\n    { * }\n=end code\n\nNote that C<$res> is to be written by the function, so it must be labeled with\nthe C<is rw> trait. Since the library is standard POSIX, the library name can be\nthe type definition or null.\n\nWe now have to handle structure C<Addrinfo>. The Linux Manual provides this\ninformation:\n\n=begin code :lang<C>\nstruct addrinfo {\n               int              ai_flags;\n               int              ai_family;\n               int              ai_socktype;\n               int              ai_protocol;\n               socklen_t        ai_addrlen;\n               struct sockaddr *ai_addr;\n               char            *ai_canonname;\n               struct addrinfo *ai_next;\n           };\n=end code\n\nThe C<int, char*> parts are straightforward. Some research indicates that\nC<socklen_t> can be architecture dependent, but is an unsigned integer of at\nleast 32 bits. So C<socklen_t> can be mapped to the C<uint32> type.\n\nThe complication is C<sockaddr> which differs depending on whether\nC<ai_socktype> is undefined, INET, or INET6 (a standard v4 IP address or a v6\naddress).\n\nSo we create a Raku C<class> to map to the C C<struct addrinfo>; while we're at\nit, we also create another class for C<SockAddr> which is needed for it.\n\n=begin code\nclass SockAddr is repr('CStruct') {\n    has int32    $.sa_family;\n    has Str      $.sa_data;\n}\n\nclass Addrinfo is repr('CStruct') {\n    has int32     $.ai_flags;\n    has int32     $.ai_family;\n    has int32     $.ai_socktype;\n    has int32     $.ai_protocol;\n    has int32     $.ai_addrlen;\n    has SockAddr  $.ai_addr       is rw;\n    has Str       $.ai_cannonname is rw;\n    has Addrinfo  $.ai_next       is rw;\n\n}\n=end code\n\nThe C<is rw> on the last three attributes reflects that these were defined in C\nto be pointers.\n\nThe important thing here for mapping to a C C<Struct> is the structure of the\nstate part of the class, that is the attributes. However, a class can have\nmethods and C<NativeCall> does not 'touch' them for mapping to C. This means\nthat we can add extra methods to the class to unpack the attributes in a more\nreadable manner, e.g.,\n\n=begin code :skip-test<should be compiled as part of Addrinfo defined above>\nmethod flags {\n    do for AddrInfo-Flags.enums { .key if $!ai_flags +& .value }\n}\n=end code\n\nBy defining an appropriate C<enum>, C<flags> will return a string of keys\nrather than a bit packed integer.\n\nThe most useful information in the C<sockaddr> structure is the address of\nnode, which depends on the family of the Socket.  So we can add method\nC<address> to the Raku class that interprets the address depending on the\nfamily.\n\nIn order to get a human readable IP address, there is the C function\nC<inet_ntop> which returns a C<char *> given a buffer with the C<addrinfo>.\n\nPutting all these together, leads to the following program:\n\n=begin code :solo\n#!/usr/bin/env raku\n\nuse v6;\nuse NativeCall;\n\nconstant \\INET_ADDRSTRLEN = 16;\nconstant \\INET6_ADDRSTRLEN = 46;\n\nenum AddrInfo-Family (\n    AF_UNSPEC                   => 0;\n    AF_INET                     => 2;\n    AF_INET6                    => 10;\n);\n\nenum AddrInfo-Socktype (\n    SOCK_STREAM                 => 1;\n    SOCK_DGRAM                  => 2;\n    SOCK_RAW                    => 3;\n    SOCK_RDM                    => 4;\n    SOCK_SEQPACKET              => 5;\n    SOCK_DCCP                   => 6;\n    SOCK_PACKET                 => 10;\n);\n\nenum AddrInfo-Flags (\n    AI_PASSIVE                  => 0x0001;\n    AI_CANONNAME                => 0x0002;\n    AI_NUMERICHOST              => 0x0004;\n    AI_V4MAPPED                 => 0x0008;\n    AI_ALL                      => 0x0010;\n    AI_ADDRCONFIG               => 0x0020;\n    AI_IDN                      => 0x0040;\n    AI_CANONIDN                 => 0x0080;\n    AI_IDN_ALLOW_UNASSIGNED     => 0x0100;\n    AI_IDN_USE_STD3_ASCII_RULES => 0x0200;\n    AI_NUMERICSERV              => 0x0400;\n);\n\nsub inet_ntop(int32, Pointer, Blob, int32 --> Str)\n    is native {}\n\nclass SockAddr is repr('CStruct') {\n    has uint16 $.sa_family;\n}\n\nclass SockAddr-in is repr('CStruct') {\n    has int16 $.sin_family;\n    has uint16 $.sin_port;\n    has uint32 $.sin_addr;\n\n    method address {\n        my $buf = buf8.allocate(INET_ADDRSTRLEN);\n        inet_ntop(AF_INET, Pointer.new(nativecast(Pointer,self)+4),\n            $buf, INET_ADDRSTRLEN)\n    }\n}\n\nclass SockAddr-in6 is repr('CStruct') {\n    has uint16 $.sin6_family;\n    has uint16 $.sin6_port;\n    has uint32 $.sin6_flowinfo;\n    has uint64 $.sin6_addr0;\n    has uint64 $.sin6_addr1;\n    has uint32 $.sin6_scope_id;\n\n    method address {\n        my $buf = buf8.allocate(INET6_ADDRSTRLEN);\n        inet_ntop(AF_INET6, Pointer.new(nativecast(Pointer,self)+8),\n            $buf, INET6_ADDRSTRLEN)\n    }\n}\n\nclass Addrinfo is repr('CStruct') {\n    has int32 $.ai_flags;\n    has int32 $.ai_family;\n    has int32 $.ai_socktype;\n    has int32 $.ai_protocol;\n    has uint32 $.ai_addrNativeCalllen;\n    has SockAddr $.ai_addr is rw;\n    has Str $.ai_cannonname is rw;\n    has Addrinfo $.ai_next is rw;\n\n    method flags {\n        do for AddrInfo-Flags.enums { .key if $!ai_flags +& .value }\n    }\n\n    method family {\n        AddrInfo-Family($!ai_family)\n    }\n\n    method socktype {\n        AddrInfo-Socktype($!ai_socktype)\n    }\n\n    method address {\n        given $.family {\n            when AF_INET {\n                nativecast(SockAddr-in, $!ai_addr).address\n            }\n            when AF_INET6 {\n                nativecast(SockAddr-in6, $!ai_addr).address\n            }\n        }\n    }\n}\n\nsub getaddrinfo(Str $node, Str $service, Addrinfo $hints,\n                Pointer $res is rw --> int32)\n    is native {};\n\nsub freeaddrinfo(Pointer)\n    is native {}\n\nsub MAIN() {\n    my Addrinfo $hint .= new(:ai_flags(AI_CANONNAME));\n    my Pointer $res .= new;\n    my $rv = getaddrinfo(\"google.com\", Str, $hint, $res);\n    say \"return val: $rv\";\n    if ( ! $rv ) {\n        my $addr = nativecast(Addrinfo, $res);\n        while $addr {\n            with $addr {\n                say \"Name: \", $_ with .ai_cannonname;\n                say .family, ' ', .socktype;\n                say .address;\n                $addr = .ai_next;\n            }\n        }\n    }\n    freeaddrinfo($res);\n}\n=end code\n\nThis produces the following output:\n\n=begin code :lang<text>\nreturn val: 0\nName: google.com\nAF_INET SOCK_STREAM\n216.58.219.206\nAF_INET SOCK_DGRAM\n216.58.219.206\nAF_INET SOCK_RAW\n216.58.219.206\nAF_INET6 SOCK_STREAM\n2607:f8b0:4006:800::200e\nAF_INET6 SOCK_DGRAM\n2607:f8b0:4006:800::200e\nAF_INET6 SOCK_RAW\n2607:f8b0:4006:800::200e\n=end code\n\n=head1 Platform Specific Notes\n\n=head2 MacOS - DYLD_LIBRARY_PATH is ignored\n\nOn MacOSX El Capitan and later the I<System Integrity Protection>, short SIP,\nprevents protected processes from passing through several environment\nvariables, among them C<DYLD_LIBRARY_PATH>. The C<env> program, often used in\nI<shebang> lines, is one of those programs. This means that whenever C<env> is\ninvolved in calling a program the C<DYLD_LIBRARY_PATH> variable will be\ncleared. To work around this effect one has to either make sure no protected\nprocess is involved (this can be difficult) or disable SIP.\n\nThis is usually not a problem when using popular installation methods such as\nI<Homebrew> or I<MacPorts>, tends to be more problematic when installing into\nnon standard locations such as ones home directory and most definitely\nproblematic when explicitly utilizing the C<DYLD_LIBRARY_PATH> variable.\n\nSee L<Apples documentation on SIP|https://developer.apple.com/library/archive/documentation/Security/Conceptual/System_Integrity_Protection_Guide/RuntimeProtections/RuntimeProtections.html>\nfor some more information.\nSee L<brian d foy's blog post on the topic|https://briandfoy.github.io/macos-s-system-integrity-protection-sanitizes-your-environment/>\nfor a more detailed explanation.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/nativetypes.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Raku native types\n\n=SUBTITLE Using the types the compiler and hardware make available to you\n\nRaku offers a set of I<native> types with a fixed, and known, representation\nin memory. This page shows which ones exist and how they can be used. Please\ncheck also the page on L<native numerics|/language/numerics#Native_numerics> for\nmore information on them.\n\nX<|Tutorial,int>X<|Tutorial,uint>X<|Tutorial,num>X<|Tutorial,str>\n=head1 Types with native representation\n\nSome simple types in Raku have a I<native> representation, indicating\nthat they will use the C language representation provided by the\ncompiler, operating system and machine. These are the four native types\navailable:\n\n=begin table\nint            Equivalent to Int (with limited range)\nuint           Equivalent to Int (with limited range) with the unsigned trait\nnum            Equivalent to Num\nstr            Equivalent to Str\n=end table\n\nHowever, these types do not necessarily have the size that is required by the\nL<NativeCall|/language/nativecall> interface (e.g., Raku's C<int> can be 8\nbytes but C's C<int> is only 4 bytes); the types below will have to be\nused instead of the types C<int> or C<num> listed above.\n\nIn general, these variables will behave in the same way as regular\nscalar variables, in a behavior that is called\nL<I<auto-boxing>|/language/numerics#Auto-boxing>; however, there are\nsome differences, since what you are actually declaring is how they will\nbe represented, not their actual type. The first one is that their type\nwill be actually their equivalent type, not their native type.\n\n    my int $intillo = 3;\n    say $intillo.^name; # OUTPUT: «Int␤»\n\nThis obviously means that they will smartmatch their equivalent (auto-boxed)\ntype, not their native type:\n\n    my str $strillo = \"tres\";\n    say $strillo ~~ str; # OUTPUT: «False␤»\n    say $strillo ~~ Str; # OUTPUT: «True␤»\n\nAnd also that they will always have a default value, unlike their non-native\ncounterparts:\n\n    say (my Str $); # OUTPUT: «(Str)␤»\n    say (my str $); # OUTPUT: «␤»\n    say (my num $); # OUTPUT: «0␤»\n\nB<Note>: In v6.c, the default value for C<num> would have been a NaN.\n\nThis is due to the fact that Natives don't know their types because\nthey're just values, without any metadata. In\nL<multi-dispatch|/language/glossary#Multi-dispatch>, you can have a\nnative candidate, but you cannot differentiate different sizes or\nsignedness of the same native type.  That is, you can have an\nL<C<Int>|/type/Int> and L<int|/native/int> candidates, but there would be an\nambiguity between, for instance L<int|/native/int>,\nL<uint|/language/nativetypes#index-entry-uint>,\nL<C<atomicint>|/type/atomicint> or\nL<int64|/language/nativetypes#index-entry-int64> candidates.\n\nThey cannot be bound either; trying to do C<my num $numillo := 3.5> will\nraise the exception C<Cannot bind to natively typed variable\n'$variable-name'; use assignment instead>.\n\nX<|Types,int @> X<|Types,num @> X<|Types,str @>\nNative types can also be composite.\n\n    my int @intillos = ^10_000_000;\n    say [+] @intillos; # OUTPUT: «49999995000000␤»\n\nX<|Language,native array>\nIn this case, I<native>ness extends to the composite type, which is called\nC<array>\n\n     my num @many-pi  = ^8 »*» π ; say @many-pi.^name;  # OUTPUT: «array[num]␤»\n\nNative C<array>s behave as L<C<Iterable>|/type/Iterable> and\nL<C<Positional>|/type/Positional>, but they are not a subclass of L<C<List>|/type/List>; thus,\nthey behave similarly to L<C<Array>|/type/Array>s; for instance, they can be\nshaped:\n\n=begin code\nmy str @letter-pairs[10] = 'a'..'j' Z~ 'A'..'J';\nsay @letter-pairs.raku;\n# OUTPUT: «array[str].new(:shape(10,), [\"aA\", \"bB\", \"cC\", \"dD\", \"eE\", \"fF\", \"gG\", \"hH\", \"iI\", \"jJ\"])␤»\n=end code\n\nNative arrays of C<str> can only be used from version 6.d.\n\nThese native types can also be used as attributes in classes, and as such they\ncan be used as bound targets, for instance in submethods like C<BUILD>:\n\n=for code\nclass Foo {\n    has num $.numillo;\n    submethod BUILD( :$!numillo = 3.5e0 ) {}\n};\nmy $foo = Foo.new;\nsay $foo.raku; # OUTPUT: «Foo.new(numillo => 3.5e0)␤»\n\n\nX<|Types,int8>X<|Types,int16>X<|Types,int32>X<|Types,int64>X<|Types,uint8>X<|Types,uint16>X<|Types,uint32>X<|Types,uint64>\nX<|Types,num32>X<|Types,num64>X<|Types,byte>\n=head1 Types with native representation and size\n\nWhat has been mentioned about types with native representation also applies\nhere; they will be auto-boxed to Raku types and you will not be able to bind\nto them. However, these types, which are listed in the table below, have the\ncharacteristic of being usable in\nL<NativeCall|/language/nativecall#Passing_and_returning_values> functions.\n\n=begin table\n    int8           (int8_t in C)\n    int16          (int16_t in C)\n    int32          (int32_t in C)\n    int64          (int64_t in C)\n    byte, uint8    (uint8_t in C)\n    uint16         (uint16_t in C)\n    uint32         (uint32_t in C)\n    uint64         (uint64_t in C)\n    num32          (float in C)\n    num64          (double in C)\n=end table\n\nThese types have a fixed size representation which is independent of the\nplatform, and thus can be used safely for those native calls. Nothing prevents\nus from using them in any other environment, if we so wish. In the same way as\nthe types above, this size will have to be taken into account when assigning\nvalues to variables of this type:\n\n    my byte $intillo = 257;\n    say $intillo; # OUTPUT: «1␤»\n\nSince C<byte> is able to hold only 8 bits, it will I<wrap over> and assign the\nresult of the original value modulo 256, which is what is shown.\n\nThe main difference between types with declared native size and those without is\nthe use of X<is nativesize|Traits,is nativesize> in their declaration. For instance, C<int8> is\ndeclared in this way:\n\n    my native int8 is repr('P6int') is Int is nativesize(8) { }\n\nIndicating that it will use, besides an integer representation (C<P6int>), a\nnative size of only 8 bits. This trait, however, is not intended to be used in\nyour programs since it is not part of the Raku specification.\n\nX<|Types,void type (NativeCall)>\n=head1 The C<void> type\n\nThe native C<void> type corresponds to the C namesake type; being a\nvalid type, you can use it in expressions:\n\n     use NativeCall;\n     my void $nothing;\n     say $nothing.raku; # OUTPUT: «NativeCall::Types::void␤»\n\nIn practice, it is an C<Uninstantiable> type that can rarely be used by itself,\nand in fact it is\nL<explicitly forbidden in C<return> types|/language/nativecall#Passing_and_returning_values>.\nHowever, it is\ngenerally found in typed pointers representing the equivalent to the C<void *>\npointer in C.\n\n=begin code :preamble<use NativeCall;>\nsub malloc( int32 $size --> Pointer[void] ) is native { * };\nmy Pointer[void] $for-malloc = malloc( 32 );\nsay $for-malloc.raku;\n=end code\n\nAs the example shows, it's represented by a parameterized\nL<C<Pointer> role|/language/nativecall#index-entry-Pointer>,\nusing as parameter whatever the original pointer is pointing to (in this\ncase, C<void>). This role represents native pointers, and can be used\nwherever they need to be represented in a Raku program.\n\nYou can also L<nativecast|/routine/nativecast> L<C<Blob>|/type/Blob>s to this kind\nof pointer in case you need to work with them in native functions that use the\ntype\n\n=begin code\nuse NativeCall;\nmy Pointer[void] $native = nativecast(Pointer[void], Blob.new(0x22, 0x33));\n=end code\n\nHowever, outside that, the functionality it offers is quite limited, since\npointers to void cannot be dereferenced:\n\n=begin code\nuse NativeCall;\nmy Pointer[void] $native = nativecast(Pointer[void], Buf.new(0x22, 0x33));\nsay $native.deref; # ERROR OUTPUT: «Internal error: unhandled target type␤»\n=end code\n\n\n=head1 I<Atomic> types\n\nIn this context, I<atomic> refers to safe operation under threading. Raku\nprovides a type, L<C<atomicint>|/type/atomicint>, and\nL<some operations|/type/atomicint#Routines> which, together, guarantee this.\nPlease check\nL<the atomic operations section on the Numerics page|/language/numerics#Atomic_operations>\nfor more information on this.\n\n=head1 Rakudo specific native types\n\nThe types described in this section are Rakudo specific, so they are not\nguaranteed to be in other implementations or remain the same in future versions.\n\n=begin table\nlong       (long in C)\nlonglong   (longlong in C)\nulong      (long and unsigned in C)\nulonglong  (longlong and unsigned in C)\nsize_t     (size_t and unsigned in C)\nssize_t    (size_t in C)\nbool       (bool in C)\n=end table\n\nYou can use them in the same way they would be used in native C:\n\n=begin code\nuse NativeCall;\n\nmy $just-an-array = CArray[int32].new( 1, 2, 3, 4, 5 );\n\nloop ( my size_t $i = 0; $i < $just-an-array.elems; $i++ ) {\n    say $just-an-array[$i];\n}\n=end code\n\nWhich would print the five elements of the array, as it should be expected.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/newline.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Newline handling in Raku\n\n=SUBTITLE How the different newline characters are handled, and how to change the behavior\n\nDifferent operating systems use different characters, or combinations of them,\nto represent the transition to a new line. Every language has its own set of\nrules to handle this. Raku has the following ones:\n\n=item C<\\n> in a string literal means Unicode codepoint 10.\n\n=item The default L<nl-out|/routine/nl-out> that is appended to a string by say\nis also C<\\n>.\n\n=item On output, when on Windows, the encoder will by default transform a C<\\n>\ninto a C<\\r\\n> when it's going to a file, process, or terminal (it won't do this\non a socket, however).\n\n=item On input, on any platform, the decoder will by default normalize C<\\r\\n>\ninto C<\\n> for input from a file, process, or terminal (again, not socket).\n\n=item These above two points together mean that you can - socket programming\naside - expect to never see a C<\\r\\n> inside of your program (this is how things\nwork in numerous other languages too).\n\nX<|Reference,:$translate-nl>\n=item The L<C<:$translate-nl>|/type/Encoding#method_decoder> named parameter\nexists in various places to control this transformation, for instance, in\nL<C<Proc::Async.new>|/type/Proc::Async#method_new> and\nL<C<Proc::Async.Supply>|/type/Proc::Async#method_Supply>.\n\n=item A C<\\n> in the L<regex|/language/regexes> language is logical, and will\nmatch a C<\\r\\n>.\n\nX<|Reference,:nl-out>\nYou can change the default behavior for a particular handle by setting the\nC<:nl-out> attribute when you create that handle.\n\n    my $crlf-out = open(IO::Special.new('<STDOUT>'), :nl-out(\"\\\\\\n\\r\"));\n    $*OUT.say: 1;     # OUTPUT: «1␤»\n    $crlf-out.say: 1; # OUTPUT: «1\\␤␍»\n\nIn this example, where we are replicating standard output to a new handle by\nusing L<C<IO::Special>|/type/IO::Special>, we are appending a C<\\> to the end of\nthe string, followed by a newline C<␤> and a carriage return C<␍>; everything\nwe print to that handle will get those characters at the end of the line,\nas shown.\n\nIn regular expressions,\nL<C<\\n>|/language/regexes#\\n_and_\\N> is defined in\nterms of the L<Unicode definition of logical newline|https://unicode.org/reports/tr18/#Line_Boundaries>. It will match C<.>\nand also C<\\v>, as well as any class that includes whitespace.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/numerics.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Numerics\n\n=SUBTITLE Numeric types available in Raku\n\n=head1 L<C<Int>|/type/Int>\n\nThe L<C<Int>|/type/Int> type offers arbitrary-size integer numbers. They can get as big\nas your computer memory allows, although some implementations choose to\nthrow a numeric overflow error when asked to produce integers of truly\nstaggering size:\n\n=begin code\nsay 10**600**600\n# OUTPUT: «Numeric overflow␤»\n=end code\n\nUnlike some languages, division performed using\nL<C«/» operator|/routine/$SOLIDUS> when both operands are of L<C<Int>|/type/Int>\ntype, would produce a fractional number, without any rounding performed.\n\n=begin code\nsay 4/5; # OUTPUT: «0.8␤»\n=end code\n\nThe type produced by this division is either a L<C<Rat>|/type/Rat> or a\nL<C<Num>|/type/Num> type. The L<C<Rat>|/type/Rat> is produced if, after reduction, the\nfraction's denominator is smaller than 64 bits, otherwise a L<C<Num>|/type/Num>\ntype is produced.\n\nThe L<div|/routine/div> and L<narrow|/routine/narrow> routines can be helpful if\nyou wish to end up with an L<C<Int>|/type/Int> result, whenever possible. The\nL<div|/routine/div> operator performs integer division, discarding the\nremainder, while L<narrow|/routine/narrow> fits the number into the narrowest\ntype it'll fit:\n\n=begin code\nsay 5 div 2; # OUTPUT: «2␤»\n\n# Result `2` is narrow enough to be an Int:\nsay (4/2).narrow; # OUTPUT: «2␤»\nsay (4/2).narrow.^name; # OUTPUT: «Int␤»\n\n# But 2.5 has fractional part, so it ends up being a Rat type:\nsay (5/2).narrow.^name; # OUTPUT: «Rat␤»\nsay (5/2).narrow;       # OUTPUT: «2.5␤»\n\n# Denominator is too big for a Rat, so a Num is produced:\nsay 1 / 10⁹⁹; # OUTPUT: «1e-99␤»\n=end code\n\nRaku has a L<C<FatRat>|/type/FatRat> type that offers arbitrary precision fractions. How come\na limited-precision L<C<Num>|/type/Num> is produced instead of a L<C<FatRat>|/type/FatRat> type in the\nlast example above? The reason is: performance. Most operations are fine\nwith a little bit of precision lost and so do not require the use of a more\nexpensive L<C<FatRat>|/type/FatRat> type. You'll need to instantiate one yourself if you wish\nto have the extra precision.\n\n=head1 L<C<Num>|/type/Num>\n\nThe L<C<Num>|/type/Num> type offers\nL<double-precision floating-point|https://en.wikipedia.org/wiki/Double-precision_floating-point_format> decimal numbers, sometimes called \"doubles\" in other languages.\n\nA L<C<Num>|/type/Num> literal is written with the exponent separated using the letter C<e>. Keep\nin mind that the letter C<e> B<is required> even if the exponent is zero, as\notherwise you'll get a L<C<Rat>|/type/Rat> rational literal instead:\n\n=begin code\nsay 42e0.^name; # OUTPUT: «Num␤»\nsay 42.0.^name; # OUTPUT: «Rat␤»\n=end code\n\nCase-sensitive words L<Inf|/type/Num#Inf> and L<NaN|/type/Num#NaN> represent the special values infinity and\nnot-a-number respectively. The U+221E INFINITY (C<∞>) character can be used\ninstead of L<Inf|/type/Num#Inf>:\n\nRaku follows the\nL<IEEE 754-2008 Standard for Floating-Point Arithmetic|https://en.wikipedia.org/wiki/IEEE_754> as much as possible, with\nmore conformance planned to be implemented in later language versions. The\nlanguage guarantees the closest representable number is chosen for any given\nL<C<Num>|/type/Num> literal and does offer support for negative zero and\nL<denormals|https://en.wikipedia.org/wiki/Denormal_number> (also known as\n\"subnormals\").\n\nKeep in mind that output routines like L<say|/routine/say> or L<put|/routine/put> do not try very hard to\ndistinguish between how L<C<Numeric>|/type/Numeric> types are output and may choose to display\na L<C<Num>|/type/Num> as an L<C<Int>|/type/Int> or a L<C<Rat>|/type/Rat> number. For a more definitive string to\noutput, use the L<raku|/routine/raku> method:\n\n=begin code\nsay  1e0;      # OUTPUT: «1␤»\nsay .5e0;      # OUTPUT: «0.5␤»\nsay  1e0.raku; # OUTPUT: «1e0␤»\nsay .5e0.raku; # OUTPUT: «0.5e0␤»\n=end code\n\n=head1 L<C<Complex>|/type/Complex>\n\nThe L<C<Complex>|/type/Complex> type numerics of the\nL<complex plane|https://en.wikipedia.org/wiki/Complex_plane>. The L<C<Complex>|/type/Complex>\nobjects consist of two L<C<Num>|/type/Num> objects representing the\nL<real|/routine/re> and L<imaginary|/routine/im> portions of the complex number.\n\nTo create a L<C<Complex>|/type/Complex>, you can use the L«postfix C<i> operator|/routine/i»\non any other non-complex number, optionally setting the real part with\naddition. To use the C<i> operator on C<NaN> or C<Inf> literals, separate it\nfrom them with a backslash.\n\n=begin code\nsay 42i;      # OUTPUT: «0+42i␤»\nsay 73+42i;   # OUTPUT: «73+42i␤»\nsay 73+Inf\\i; # OUTPUT: «73+Inf\\i␤»\n=end code\n\nKeep in mind the above syntax is just an addition expression and precedence\nrules apply. It also cannot be used in places that forbid expressions, such\nas literals in routine parameters.\n\n=begin code\n# Precedence of `*` is higher than that of `+`\nsay 2 * 73+10i; # OUTPUT: «146+10i␤»\n=end code\n\nTo avoid these issues, you can choose to use the L<C<Complex>|/type/Complex> literal syntax\ninstead, which involves surrounding the real and imaginary parts with angle\nbrackets, I<without any spaces>:\n\n=begin code\nsay 2 * <73+10i>; # OUTPUT: «146+20i␤»\n\nmulti how-is-it (<2+4i>) { say \"that's my favorite number!\" }\nmulti how-is-it (|)      { say \"meh\"                        }\nhow-is-it 2+4i;  # OUTPUT: «that's my favorite number!␤»\nhow-is-it 3+2i;  # OUTPUT: «meh␤»\n=end code\n\n=head1 L<C<Rational>|/type/Rational>\n\nThe types that do the L<C<Rational>|/type/Rational> role offer high-precision and\narbitrary-precision decimal numbers. Since the higher the precision the\nlarger the performance penalty, the L<C<Rational>|/type/Rational> types come in two flavors:\nL<C<Rat>|/type/Rat> and L<C<FatRat>|/type/FatRat>. The L<C<Rat>|/type/Rat> is the most often-used variant\nthat degrades into a L<C<Num>|/type/Num> in most cases, when it can no longer hold all of\nthe requested precision. The L<C<FatRat>|/type/FatRat> is the arbitrary-precision variant that\nkeeps growing to provide all of the requested precision.\n\n=head2 L<C<Rat>|/type/Rat>\n\nThe most common of L<C<Rational>|/type/Rational> types. It supports rationals with denominators\nas large as 64 bits (after reduction of the fraction to the lowest denominator).\nL<C<Rat>|/type/Rat> objects with larger denominators can be created directly, however, when\nL<C<Rat>|/type/Rat>s with such denominators are the result of mathematical operations, they\ndegrade to a L<C<Num>|/type/Num> object.\n\nThe L<C<Rat>|/type/Rat> literals use syntax similar to L<C<Num>|/type/Num> literals in many other\nlanguages, using the dot to indicate the number is a decimal:\n\n=begin code\nsay .1 + .2 == .3; # OUTPUT: «True␤»\n=end code\n\nIf you try to execute a statement similar to the above in many common\nlanguages, you'll get C<False> as the answer, due to imprecision of\nfloating point math. To get the same result in Raku, you'd have to use\nL<C<Num>|/type/Num> literals instead:\n\n=begin code\nsay .1e0 + .2e0 == .3e0; # OUTPUT: «False␤»\n=end code\n\nYou can also use L«C</> division operator|/routine/$SOLIDUS» with L<C<Int>|/type/Int> or\nL<C<Rat>|/type/Rat> objects to produce a L<C<Rat>|/type/Rat>:\n\n=begin code\nsay 3/4;     # OUTPUT: «0.75␤»\nsay 3/4.2;   # OUTPUT: «0.714286␤»\nsay 1.1/4.2; # OUTPUT: «0.261905␤»\n=end code\n\nKeep in mind the above syntax is just a division expression and precedence\nrules apply. It also cannot be used in places that forbid expressions, such\nas literals in routine parameters.\n\n=begin code\n# Precedence of power operators is higher than division\nsay 3/2²; # OUTPUT: «0.75␤»\n=end code\n\nTo avoid these issues, you can choose to use the L<C<Rational>|/type/Rational> literal syntax\ninstead, which involves surrounding the numerator and denominator with angle\nbrackets, I<without any spaces>:\n\n=begin code\nsay <3/2>²; # OUTPUT: «2.25␤»\n\nmulti how-is-it (<3/2>) { say \"that's my favorite number!\" }\nmulti how-is-it (|)     { say \"meh\"                        }\nhow-is-it 3/2;  # OUTPUT: «that's my favorite number!␤»\nhow-is-it 1/3;  # OUTPUT: «meh␤»\n=end code\n\nLastly, any Unicode character with property C<No> that represents a fractional\nnumber can be used as a L<C<Rat>|/type/Rat> literal:\n\n=begin code\nsay ½ + ⅓ + ⅝ + ⅙; # OUTPUT: «1.625␤»\n=end code\n\n=head3 Degradation to L<C<Num>|/type/Num>\n\nIf a I<mathematical operation> that produces a L<C<Rat>|/type/Rat> answer would produce\na L<C<Rat>|/type/Rat> with denominator larger than 64 bits, that operation would instead\nreturn a L<C<Num>|/type/Num> object. When I<constructing> a L<C<Rat>|/type/Rat> (i.e. when it is not\na result of some mathematical expression), however, a larger denominator can be used:\n\n    my $a = 1 / (2⁶⁴ - 1);\n    say $a;                   # OUTPUT: «0.000000000000000000054␤»\n    say $a.^name;             # OUTPUT: «Rat␤»\n    say $a.nude;              # OUTPUT: «(1 18446744073709551615)␤»\n\n    my $b = 1 / 2⁶⁴;\n    say $b;                   # OUTPUT: «5.421010862427522e-20␤»\n    say $b.^name;             # OUTPUT: «Num␤»\n\n    my $c = Rat.new(1, 2⁶⁴);\n    say $c;                   # OUTPUT: «0.000000000000000000054␤»\n    say $c.^name;             # OUTPUT: «Rat␤»\n    say $c.nude;              # OUTPUT: «(1 18446744073709551616)␤»\n    say $c.Num;               # OUTPUT: «5.421010862427522e-20␤»\n\n=head2 L<C<FatRat>|/type/FatRat>\n\nThe last L<C<Rational>|/type/Rational> type—L<C<FatRat>|/type/FatRat>—keeps all of the precision you ask of\nit, storing the numerator and denominator as two L<C<Int>|/type/Int> objects. A L<C<FatRat>|/type/FatRat>\nis more infectious than a L<C<Rat>|/type/Rat>, so many math operations with a L<C<FatRat>|/type/FatRat> will\nproduce another L<C<FatRat>|/type/FatRat>, preserving all of the available precision. Where\na L<C<Rat>|/type/Rat> degrades to a L<C<Num>|/type/Num>, math with a L<C<FatRat>|/type/FatRat> keeps chugging along:\n\n=begin code\nsay ((42 + Rat.new(1,2))/999999999999999999).^name;         # OUTPUT: «Rat␤»\nsay ((42 + Rat.new(1,2))/9999999999999999999).^name;        # OUTPUT: «Num␤»\nsay ((42 + FatRat.new(1,2))/999999999999999999).^name;      # OUTPUT: «FatRat␤»\nsay ((42 + FatRat.new(1,2))/99999999999999999999999).^name; # OUTPUT: «FatRat␤»\n=end code\n\nThere's no special operator or syntax available for construction of L<C<FatRat>|/type/FatRat>\nobjects. Simply use the C<FatRat.new> method,\ngiving numerator as first positional argument and denominator as the second.\n\nIf your program requires a significant amount of L<C<FatRat>|/type/FatRat> creation, you could\ncreate your own custom operator:\n\n=begin code\nsub infix:<🙼> { FatRat.new: $^a, $^b }\nsay (1🙼3).raku; # OUTPUT: «FatRat.new(1, 3)␤»\n=end code\n\n=head2 Printing rationals\n\nKeep in mind that output routines like L<say|/routine/say> or L<put|/routine/put> do not try very hard to\ndistinguish between how L<C<Numeric>|/type/Numeric> types are output and may choose to display\na L<C<Num>|/type/Num> as an L<C<Int>|/type/Int> or a L<C<Rat>|/type/Rat> number. For a more definitive string to\noutput, use the L<raku|/routine/raku> method:\n\n=begin code\nsay 1.0;        # OUTPUT: «1␤»\nsay ⅓;          # OUTPUT: «0.333333␤»\nsay 1.0.raku;   # OUTPUT: «1.0␤»\nsay ⅓.raku;     # OUTPUT: «<1/3>␤»\n=end code\n\nThe L<nude|/routine/nude> method returns a L<C<List>|/type/List> with the reduced B<nu>merator and B<de>nominator\nof the L<C<Rational>|/type/Rational>.\n\n=begin code\nsay <300/12>.nude; # OUTPUT: «(25 1)␤»\n=end code\n\n=head1 Division by zero\n\nIn many languages division by zero is an immediate exception. In Raku, what\nhappens depends on what you're dividing and how you use the result.\n\nRaku follows L<IEEE 754-2008 Standard for Floating-Point Arithmetic|https://en.wikipedia.org/wiki/IEEE_754>, but for historical reasons\n6.c and 6.d language versions do not comply fully. L<C<Num>|/type/Num> division by zero\nproduces a L<C<Failure>|/type/Failure>, while L<C<Complex>|/type/Complex> division by zero produces C<NaN>\ncomponents, regardless of what the numerator is.\n\nAs of 6.e language, both L<C<Num>|/type/Num> and L<C<Complex>|/type/Complex> division by zero will produce an\nL<C<-Inf>|/type/Num#Inf>, C<+Inf>, or L<NaN|/type/Num#NaN> depending on whether the numerator was\nnegative, positive, or zero, respectively (for L<C<Complex>|/type/Complex> the real and imaginary\ncomponents are L<C<Num>|/type/Num> and are considered separately).\n\nDivision of L<C<Int>|/type/Int> numerics produces a L<C<Rat>|/type/Rat> object (or a L<C<Num>|/type/Num>, if\nafter reduction the denominator is larger than 64-bits, which isn't the case\nwhen you're dividing by zero). This means such division never produces\nan L<C<Exception>|/type/Exception> or a L<C<Failure>|/type/Failure>. The result is a Zero-Denominator Rational,\nwhich can be explosive.\n\n=head2 Zero-denominator rationals\n\nA Zero-Denominator Rational is a numeric that does role L<C<Rational>|/type/Rational>, which\namong core numerics would be L<C<Rat>|/type/Rat> and L<C<FatRat>|/type/FatRat> objects, which\nhas denominator of zero. The numerator of such Rationals is normalized\nto C<-1>, C<0>, or C<1> depending on whether the original numerator\nis negative, zero or positive, respectively.\n\nOperations that can be performed without requiring actual division to occur are\nnon-explosive. For example, you can separately examine L<numerator|/routine/numerator> and\nL<denominator|/routine/denominator> in the L<nude|/routine/nude> or perform mathematical operations without any\nexceptions or failures popping up.\n\nConverting zero-denominator rationals to L<C<Num>|/type/Num> follows the\nL<IEEE|https://en.wikipedia.org/wiki/IEEE_754> conventions, and the result is an\nC<-Inf>, C<Inf>, or C<NaN>, depending on whether the numerator is negative,\npositive, or zero, respectively. The same is true going the other way:\nconverting C<±Inf>/C<NaN> to one of the L<C<Rational>|/type/Rational> types will produce a\nzero-denominator rational with an appropriate numerator:\n\n=begin code\nsay  <1/0>.Num;   # OUTPUT: «Inf␤»\nsay <-1/0>.Num;   # OUTPUT: «-Inf␤»\nsay  <0/0>.Num;   # OUTPUT: «NaN␤»\nsay Inf.Rat.nude; # OUTPUT: «(1 0)␤»\n=end code\n\nAll other operations that require\nnon-L<IEEE|https://en.wikipedia.org/wiki/IEEE_754> division of the numerator and\ndenominator to occur will result in L<C<X::Numeric::DivideByZero>|/type/X::Numeric::DivideByZero> exception to be\nthrown. The most common of such operations would likely be trying to print or\nstringify a zero-denominator rational:\n\n=begin code\nsay 0/0;\n# OUTPUT:\n# Attempt to divide by zero using div\n#  in block <unit> at -e line 1\n=end code\n\n=head1 Allomorphs\n\nL<Allomorphs|/language/glossary#Allomorph> are subclasses of two\ntypes that can behave as either of them. For example, the allomorph L<C<IntStr>|/type/IntStr> is\nthe subclass of L<C<Int>|/type/Int> and L<C<Str>|/type/Str> types and will be accepted by any type\nconstraint that requires an L<C<Int>|/type/Int> or L<C<Str>|/type/Str> object.\n\nAllomorphs can be created using L«angle brackets|/language/quoting#Word_quoting:_<_>», either used\nstandalone or as part of a hash key lookup; directly\nusing method C<.new> and are also provided by some constructs such as\nparameters of L«C<sub MAIN>|/language/functions#sub_MAIN».\n\n=begin code\nsay <42>.^name;                 # OUTPUT: «IntStr␤»\nsay <42e0>.^name;               # OUTPUT: «NumStr␤»\nsay < 42+42i>.^name;            # OUTPUT: «ComplexStr␤»\nsay < 1/2>.^name;               # OUTPUT: «RatStr␤»\nsay <0.5>.^name;                # OUTPUT: «RatStr␤»\n\n@*ARGS = \"42\";\nsub MAIN($x) { say $x.^name }   # OUTPUT: «IntStr␤»\n\nsay IntStr.new(42, \"42\").^name; # OUTPUT: «IntStr␤»\n=end code\n\nA couple of constructs above have a space after the opening angle bracket. That\nspace isn't accidental. Numerics that are often written using an operator, such\nas C<1/2> (L<C<Rat>|/type/Rat>, division operator) and C<1+2i> (L<C<Complex>|/type/Complex>, addition) can be\nwritten as a literal that doesn't involve the use of an operator: angle brackets\nI<without> any spaces between the angle brackets and the characters inside. By adding\nspaces within the angle brackets, we tell the compiler that not only we want a L<C<Rat>|/type/Rat>\nor L<C<Complex>|/type/Complex> literal, but we also want it to be an allomorph: the L<C<RatStr>|/type/RatStr> or\nL<C<ComplexStr>|/type/ComplexStr>, in this case.\n\nIf the numeric literal doesn't use any operators, then writing it inside the\nangle brackets, even without including any spaces within, would produce the\nallomorph. (Logic: if you didn't want the allomorph, you wouldn't use the angle\nbrackets. The same isn't true for operator-using numbers as some constructs,\nsuch as signature literals, do not let you use operators, so you can't just omit\nangle brackets for such numeric literals).\n\n=head2 Available allomorphs\n\nThe core language offers the following allomorphs:\n\n=begin table\n\n    Type       | Allomorph of         | Example\n    ===========+======================+=================\n    IntStr     | Int and Str          | <42>\n    NumStr     | Num and Str          | <42e0>\n    ComplexStr | Complex and Str      | < 1+2i>\n    RatStr     | Rat and Str          | <1.5>\n\n=end table\n\nNote: there is no C<FatRatStr> type.\n\n=head2 Coercion of allomorphs\n\nKeep in mind that allomorphs are simply subclasses of the types they\nrepresent. Just as a variable or parameter type-constrained to C<Foo>\ncan accept any subclass of C<Foo>, so will a variable or parameter\ntype-constrained to L<C<Int>|/type/Int> will accept an\nL<C<IntStr>|/type/IntStr> allomorph:\n\n=begin code\nsub foo(Int $x) { say $x.^name }\nfoo <42>;                          # OUTPUT: «IntStr␤»\nmy Num $y = <42e0>;\nsay $y.^name;                      # OUTPUT: «NumStr␤»\n=end code\n\nThis also applies to parameter\nL<coercers|/language/signatures#Coercion_type>:\n\n=begin code\nsub foo(Int(Cool) $x) { say $x.^name }\nfoo <42>;  # OUTPUT: «IntStr␤»\n=end code\n\nThe given allomorph is I<already> an object of type L<C<Int>|/type/Int>, so\nit does not get converted to a \"plain\" L<C<Int>|/type/Int> in this case.\n\nThe power of allomorphs would be severely diminished if there\nwere no way to \"collapse\" them to one of their components. Thus, if you\nexplicitly call a method with the name of the type to coerce to, you'll\nget just that component. The same applies to any proxy methods, such as\ncalling method L«C<.Numeric>|/routine/Numeric» instead of\nL«C<.Int>|/routine/Int» or using the L«C«prefix:<~>»\noperator|/routine/~» instead of L«C<.Str>|/routine/Str» method call.\n\n=begin code\nmy $al := IntStr.new: 42, \"forty two\";\nsay $al.Str;  # OUTPUT: «forty two␤»\nsay +$al;     # OUTPUT: «42␤»\n\nsay <1/99999999999999999999>.Rat.^name;    # OUTPUT: «Rat␤»\nsay <1/99999999999999999999>.FatRat.^name; # OUTPUT: «FatRat␤»\n=end code\n\nA handy way to coerce a whole list of allomorphs is by\napplying the L<hyper operator|/language/operators#Hyper_operators> to the appropriate prefix:\n\n=begin code\nsay map *.^name,   <42 50e0 100>;  # OUTPUT: «(IntStr NumStr IntStr)␤»\nsay map *.^name, +«<42 50e0 100>;  # OUTPUT: «(Int Num Int)␤»\nsay map *.^name, ~«<42 50e0 100>;  # OUTPUT: «(Str Str Str)␤»\n=end code\n\n=head2 Object identity\n\nThe above discussion on coercing allomorphs becomes more important when we consider object\nidentity. Some constructs utilize it to ascertain whether two objects are \"the same\". And while\nto humans an allomorphic C<42> and regular C<42> might appear \"the same\", to those constructs,\nthey're entirely different objects:\n\n=begin code\n# \"42\" shows up twice in the result: 42 and <42> are different objects:\nsay unique 1, 1, 1, 42, <42>; # OUTPUT: «(1 42 42)␤»\n# Use a different operator to `unique` with:\nsay unique :with(&[==]), 1, 1, 1, 42, <42>; # OUTPUT: «(1 42)␤»\n# Or coerce the input instead (faster than using a different `unique` operator):\nsay unique :as(*.Int), 1, 1, 1, 42, <42>; # OUTPUT: «(1 42)␤»\nsay unique +«(1, 1, 1, 42, <42>);         # OUTPUT: «(1 42)␤»\n\n# Parameterized Hash with `Any` keys does not stringify them; our key is of type `Int`:\nmy %h{Any} = 42 => \"foo\";\n# But we use the allomorphic key of type `IntStr`, which is not in the Hash:\nsay %h<42>:exists;           # OUTPUT: «False␤»\n# Must use curly braces to avoid the allomorph:\nsay %h{42}:exists;           # OUTPUT: «True␤»\n\n# We are using a set operator to look up an `Int` object in a list of `IntStr` objects:\nsay 42 ∈ <42 100 200>; # OUTPUT: «False␤»\n# Convert it to an allomorph:\nsay <42> ∈ <42 100 200>; # OUTPUT: «True␤»\n# Or convert the items in the list to plain `Int` objects:\nsay 42 ∈ +«<42 100 200>; # OUTPUT: «True␤»\n=end code\n\nBe mindful of these object identity differences and coerce your allomorphs as needed.\n\n=head2 Transforming non-Allomorphs\n\nWhen we create variables explicitly as L«C<Str>|/type/Str» or L«C<Numeric>|/type/Numeric» types, they are not L«C<Allomorph>|/type/Allomorph»s:\n\n=begin code\nmy $a = \"010\"; say $a.^name; # OUTPUT: «Str␤»\nmy $b = 42;    say $b.^name; # OUTPUT: «Int␤»\n=end code\n\nWe can then explicitly transform them to their L«C<Allomorph>|/type/Allomorph» counterparts:\n\n=begin code :preamble<my ($a,$b)>\n$a .= Numeric; # OUTPUT: «10␤»\nsay $a.^name;  # OUTPUT: «Int␤»\n$b .= Str;   ; # OUTPUT: «42␤»\nsay $b.^name;  # OUTPUT: «Str␤»\n=end code\n\nOr we can coerce them into their other forms naturally:\n\n=begin code :preamble<my ($a,$b)>\nmy $a = \"010\"; say $a.^name; # OUTPUT: «Str␤»\nmy $b = $a + 1;              # OUTPUT: «11␤»\nsay $b.^name;                # OUTPUT: «Int␤»\n=end code\n\n=head1 Native numerics\n\nAs the name suggests, native numerics offer access to native numerics—i.e. those offered directly\nby your hardware. This in turn offers two features: overflow/underflow and better performance.\n\nB<NOTE:> at the time of this writing (2018.05), certain implementations (such as Rakudo) offer\nsomewhat spotty details on native types, such as whether C<int64> is available and is of 64-bit\nsize on 32-bit machines, and how to detect when your program is running on such hardware.\n\n=head2 Available native numerics\n\n=begin table\n\n    Native type | Base numeric     | Size\n    ============+==================+===============\n    int         | integer          | 64-bits\n\n    int8        | integer          | 8-bits\n\n    int16       | integer          | 16-bits\n\n    int32       | integer          | 32-bits\n\n    int64       | integer          | 64-bits\n    ------------+------------------+---------------\n    uint        | unsigned integer | 64-bits\n\n    uint8       | unsigned integer | 8-bits\n\n    uint16      | unsigned integer | 16-bits\n\n    uint32      | unsigned integer | 32-bits\n\n    uint64      | unsigned integer | 64-bits\n    ------------+------------------+---------------\n    num         | floating point   | 64-bits\n\n    num32       | floating point   | 32-bits\n\n    num64       | floating point   | 64-bits\n    ------------+------------------+---------------\n    atomicint   | integer          | sized to offer CPU-provided atomic operations. (typically 64 bits on 64-bit platforms and 32 bits on 32-bit ones)\n\n=end table\n\n=head2 Creating native numerics\n\nTo create a natively-typed variable or parameter, simply use the name of one of the available\nnumerics as the type constraint:\n\n=begin code\nmy int32 $x = 42;\nsub foo(num $y) {}\nclass { has int8 $.z }\n=end code\n\nAt times, you may wish to coerce some value to a native type without creating any usable variables.\nThere are no C<.int> or similar coercion methods (method calls are latebound, so they're not\nwell-suited for this purpose). Instead, simply use an anonymous variable:\n\n=begin code :preamble<my $y=1; my $z=1; sub some-native-taking-sub(\\a,\\b){}>\nsome-native-taking-sub( (my int $ = $y), (my int32 $ = $z) )\n=end code\n\n=head2 Overflow/Underflow\n\nTrying to B<assign> a value that does not fit into a particular native type, produces an exception.\nThis includes attempting to give too large an argument to a native parameter:\n\n=begin code :solo\nmy int $x = 2¹⁰⁰;\n# OUTPUT:\n# Cannot unbox 101 bit wide bigint into native integer\n#  in block <unit> at -e line 1\n\nsub f(int $x) { $x }; say f 2⁶⁴\n# OUTPUT:\n# Cannot unbox 65 bit wide bigint into native integer\n#   in sub f at -e line 1\n#   in block <unit> at -e line 1\n=end code\n\nHowever, modifying an already-existing value in such a way that it becomes too big/small, produces\noverflow/underflow behavior:\n\n=begin code\nmy int $x = 2⁶³-1;\nsay $x;             # OUTPUT: «9223372036854775807␤»\nsay ++$x;           # OUTPUT: «-9223372036854775808␤»\n\nmy uint8 $x;\nsay $x;             # OUTPUT: «0␤»\nsay $x -= 100;      # OUTPUT: «156␤»\n=end code\n\nCreating objects that utilize native types does not involve direct assignment by\nthe programmer; that is why these constructs offer overflow/underflow behavior\ninstead of throwing exceptions.\n\n=begin code\nsay Buf.new(1000, 2000, 3000).List; # OUTPUT: «(232 208 184)␤»\nsay my uint8 @a = 1000, 2000, 3000; # OUTPUT: «232 208 184␤»\n=end code\n\n=head2 Auto-boxing\n\nWhile they can be referred to as \"native I<types>\", native numerics are not\nactually classes that have any sort of methods available. However, you I<can>\ncall any of the methods available on non-native versions of these numerics.\nWhat's going on?\n\n=begin code\nmy int8 $x = -42;\nsay $x.abs; # OUTPUT: «42␤»\n=end code\n\nThis behavior is known as \"auto-boxing\". The compiler automatically \"boxes\" the\nnative type into a full-featured higher-level type with all the methods. In\nother words, the C<int8> above was automatically converted to an\nL<C<Int>|/type/Int> and it's the L<C<Int>|/type/Int> class that then provided the\nL<abs|/routine/abs> method that was called.\n\nThis detail is significant when you're using native types for performance gains.\nIf the code you're using results in a lot of auto-boxing being performed you\nmight get I<worse> performance with native types than you would with\nnon-natives:\n\n=begin code\nmy $a = -42;\nmy int $a-native = -42;\n{ for ^1000_000 { $a.abs        }; say now - ENTER now } # OUTPUT: «0.38180862␤»\n{ for ^1000_000 { $a-native.abs }; say now - ENTER now } # OUTPUT: «0.938720␤»\n=end code\n\nAs you can see above, the native variant is more than twice slower. The reason\nis the method call requires the native type to be boxed, while no such thing is\nneeded in the non-native variant, hence the performance loss.\n\nIn this particular case, we can simply switch to a subroutine form of\nL<abs|/routine/abs>, which can work with native types without boxing them. In\nother cases, you may need to seek out other solutions to avoid excessive\nautoboxing, including switching to non-native types for a portion of the code.\n\n=begin code\nmy $a = -42;\nmy int $a-native = -42;\n{ for ^1000_000 { abs $a        }; say now - ENTER now } # OUTPUT: «0.38229177␤»\n{ for ^1000_000 { abs $a-native }; say now - ENTER now } # OUTPUT: «0.3088305␤»\n=end code\n\n=head2 Default values\n\nSince there are no classes behind native types, there are no type objects you'd\nnormally get with variables that haven't been initialized. Thus, native types\nare automatically initialized to zero. In 6.c language, native floating point\ntypes (C<num>, C<num32>, and C<num64>) were initialized to value C<NaN>; in 6.d\nlanguage the default is C<0e0>.\n\n=head2 Native dispatch\n\nIt is possible to have native candidates alongside non-native candidates to, for\nexample, offer faster algorithms with native candidates when sizes are\npredictable, but to fallback to slower non-native alternatives otherwise. The\nfollowing are the rules concerning multi-dispatch involving native candidates.\n\nFirst, the size of the native type does not play a role in dispatch and an\nC<int8> is considered to be the same as C<int16> or C<int>:\n\n=begin code\nmulti foo(int   $x) { say \"int\" }\nmulti foo(int32 $x) { say \"int32\" }\nfoo my int $x = 42;\n# OUTPUT:\n# Ambiguous call to 'foo(Int)'; these signatures all match:\n# :(int $x)\n# :(int32 $x)\n=end code\n\nSecond, if a routine is an C<only>—i.e. it is not a\nL«C<multi>|/language/functions#Multi-dispatch»—that takes a non-native type but\na native one was given during the call, or vice-versa, then the argument will be\nauto-boxed or auto-unboxed to make the call possible. If the given argument is\ntoo large to fit into the native parameter, an exception will be thrown:\n\n=begin code\n-> int {}( 42 );            # OK; auto-unboxing\n-> int {}( 2¹⁰⁰ );          # Too large; exception\n-> Int {}( 2¹⁰⁰ );          # OK; non-native parameter\n-> Int {}( my int $ = 42 ); # OK; auto-boxing\n=end code\n\nWhen it comes to L«C<multi>|/language/functions#Multi-dispatch» routines, native\narguments will always be auto-boxed if no native candidates are available to\ntake them:\n\n=begin code\nmulti foo (Int $x) { $x }\nsay foo my int $ = 42; # OUTPUT: «42␤»\n=end code\n\nThe same luxury is not afforded when going the other way. If only a native\ncandidate is available, a non-native argument will I<not> be auto-unboxed and\ninstead an exception indicating no candidates matched will be thrown (the reason\nfor this asymmetry is a native type can always be boxed, but a non-native may be\ntoo large to fit into a native):\n\n=begin code\nmulti f(int $x) { $x }\nmy $x = 2;\nsay f $x;\n# OUTPUT:\n# Cannot resolve caller f(Int); none of these signatures match:\n#     (int $x)\n#   in block <unit> at -e line 1\n=end code\n\nHowever, this rule is waived if a call is being made where one of the arguments\nis a native type and another one is a\nL<numeric literal|/language/syntax#Number_literals>:\n\n=begin code\nmulti f(int, int) {}\nf 42, my int $x; # Successful call\n=end code\n\nThis way you do not have to constantly write, for example, C«$n +> 2» as C«$n +>\n(my int $ = 2)». The compiler knows the literal is small enough to fit to a\nnative type and converts it to a native.\n\n=head2 Atomic operations\n\nThe language offers L<some operations|/type/atomicint>\nthat are guaranteed to be performed atomically, i.e. safe to be executed\nby multiple threads without the need for locking with no risk of data races.\n\nFor such operations, the L<C<atomicint>|/type/atomicint> native type is required.\nThis type is similar to a plain native L<C<int>|/native/int>, except it is sized such\nthat CPU-provided atomic operations can be performed upon it. On a 32-bit CPU it\nwill typically be 32 bits in size, and on an a 64-bit CPU it will typically be\n64 bits in size.\n\n=begin code\n# !!WRONG!! Might be non-atomic on some systems\nmy int $x;\nawait ^100 .map: { start $x⚛++ };\nsay $x; # OUTPUT: «98␤»\n\n# RIGHT! The use of `atomicint` type guarantees operation is atomic\nmy atomicint $x;\nawait ^100 .map: { start $x⚛++ };\nsay $x; # OUTPUT: «100␤»\n=end code\n\nThe similarity to C<int> is present in multi dispatch as well: an\nL<C<atomicint>|/type/atomicint>, plain C<int>, and the sized C<int> variants are all considered\nto be the same by the dispatcher and cannot be differentiated through\nmulti-dispatch.\n\n=head1 Numeric infectiousness\n\nNumeric \"infectiousness\" dictates the resultant type when two numerics of\ndifferent types are involved in some mathematical operations. A type is said to\nbe more infectious than the other type if the result is of that type rather than\nthe type of the other operand. For example, L<C<Num>|/type/Num> type is more infectious than\nan L<C<Int>|/type/Int>, thus we can expect C<42e0 + 42> to produce a L<C<Num>|/type/Num> as the result.\n\nThe infectiousness is as follows, with the most infectious type listed first:\n\n=item Complex\n\n=item Num\n\n=item FatRat\n\n=item Rat\n\n=item Int\n\n=begin code\nsay (2 + 2e0).^name; # Int + Num => OUTPUT: «Num␤»\nsay (½ + ½).^name; # Rat + Rat => OUTPUT: «Rat␤»\nsay (FatRat.new(1,2) + ½).^name; # FatRat + Rat => OUTPUT: «FatRat␤»\n=end code\n\nThe allomorphs have the same infectiousness as their numeric component. Native\ntypes get autoboxed and have the same infectiousness as their boxed variant.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/objects.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Object orientation\n\n=SUBTITLE Object orientation in Raku\n\nRaku provides strong support for L<Object Oriented Programming (OOP)|https://en.wikipedia.org/wiki/Object-oriented_programming>.\nAlthough Raku allows programmers to program in multiple paradigms,\nObject Oriented Programming is at the heart of the language.\n\nRaku comes with a wealth of predefined types, which can be classified\nin two categories: regular and L<I<native> types|/language/nativetypes>.\nEverything that you can store in a variable is either a I<native value>\nor an I<object>. That includes literals, types (type objects), code and\ncontainers.\n\nNative types are used for low-level types (like C<uint64>). Even if I<native>\ntypes do not have the same capabilities as objects, if you call methods on them,\nthey are automatically I<boxed> into normal objects.\n\nEverything that is not a I<native> value is an I<object>.\nObjects do allow for both\nL<inheritance|https://en.wikipedia.org/wiki/Object-oriented_programming#Inheritance_and_behavioral_subtyping> and\nL<encapsulation|https://en.wikipedia.org/wiki/Object-oriented_programming#Encapsulation>.\n\n\n=head1 Using objects\n\nTo call a method on an object, add a dot, followed by the method name:\n\n=for code\nsay \"abc\".uc;\n# OUTPUT: «ABC␤»\n\nThis calls the C<uc> method on C<\"abc\">, which is an object of type\nL<C<Str>|/type/Str>. To supply arguments to the method, add arguments inside parentheses\nafter the method.\n\n=for code\nmy $formatted-text = \"Fourscore and seven years ago...\".indent(8);\nsay $formatted-text;\n# OUTPUT: «        Fourscore and seven years ago...␤»\n\nC<$formatted-text> now contains the above text, but indented 8 spaces.\n\nMultiple arguments are separated by commas:\n\n=for code :preamble<my $formatted-text;>\nmy @words = \"Abe\", \"Lincoln\";\n@words.push(\"said\", $formatted-text.comb(/\\w+/));\nsay @words;\n# OUTPUT: «[Abe Lincoln said (Fourscore and seven years ago)]␤»\n\nSimilarly, multiple arguments can be specified by placing a colon after\nthe method and separating the argument list with a comma:\n\n=for code :preamble<my @words;>\nsay @words.join('--').subst: 'years', 'DAYS';\n# OUTPUT: «Abe--Lincoln--said--Fourscore and seven DAYS ago␤»\n\nSince you have to put a C<:> after the method if you want to pass\narguments without parentheses, a method call without a colon or\nparentheses is unambiguously a method call without an argument list:\n\n    say 4.log:   ; # OUTPUT: «1.38629436111989␤» ( natural logarithm of 4 )\n    say 4.log: +2; # OUTPUT: «2␤» ( base-2 logarithm of 4 )\n    say 4.log  +2; # OUTPUT: «3.38629436111989␤» ( natural logarithm of 4, plus 2 )\n\nMany operations that don't look like method calls (for example,\nsmartmatching or interpolating an object into a string) might result in\nmethod calls under the hood.\n\nMethods can return mutable containers, in which case you can assign to the\nreturn value of a method call. This is how read-writable attributes to\nobjects are used:\n\n=for code\n$*IN.nl-in = \"\\r\\n\";\n\nHere, we call method C<nl-in> on the C<$*IN> object, without arguments,\nand assign to the container it returned with the L<C<=>|/routine/= (item assignment)> operator.\n\nAll objects support methods from class L<C<Mu>|/type/Mu>, which is the type\nhierarchy root. All objects derive from L<C<Mu>|/type/Mu>.\n\nObject equality needs a specific operator:\nL<C<eqv>|/language/operators#infix_eqv>, the structural comparison\noperator:\n\n=for code\nclass Foo {\n    has $.bar;\n    has $.baz\n};\nmy $bar = \"42\";\nmy $baz = 24;\nmy $zipi = Foo.new( :$baz, :$bar);\nmy $zape = Foo.new( :$bar, :$baz);\nsay $zipi eqv $zape; # OUTPUT: «True␤»\n\nObject identity, on the other hand, uses C<===>. Using it above will return\nC<False>, for instance.\n\n\n=head2 X<Type objects|Language,Type objects>\n\nTypes themselves are objects and you can get the I<type object> by\nwriting its name:\n\n=for code\nmy $int-type-obj = Int;\n\nYou can request the type object of anything by calling the C<WHAT>\nmethod, which is actually a macro in method form:\n\n=for code :ok-test<WHAT>\nmy $int-type-obj = 1.WHAT;\n\nType objects (other than L<C<Mu>|/type/Mu>) can be compared for equality with the\nL<C<===>|/routine/===> identity operator:\n\n=for code :ok-test<WHAT>\nsub f(Int $x) {\n    if $x.WHAT === Int {\n        say 'you passed an Int';\n    }\n    else {\n        say 'you passed a subtype of Int';\n    }\n}\n\nAlthough, in most cases, the L<C<.isa>|/routine/isa> method will suffice:\n\n=for code\nsub f($x) {\n    if $x.isa(Int) {\n        ...\n    }\n    ...\n}\n\nSubtype checking is done by L<smartmatching|/language/operators#infix_~~>:\n\n=for code :preamble<my $type;>\nif $type ~~ Real {\n    say '$type contains Real or a subtype thereof';\n}\n\n=head1 X<Classes|Syntax,class>\n\nClasses are declared using the C<class> keyword, typically followed by a\nname.\n\n=for code\nclass Journey { }\n\nThis declaration results in a type object being created and installed in the\ncurrent package and current lexical scope under the name C<Journey>. You\ncan also declare classes lexically:\n\n=for code\nmy class Journey { }\n\nThis restricts their visibility to the current lexical scope, which can be\nuseful if the class is an implementation detail nested inside a module or\nanother class.\n\n=head2 X<Attributes|Language,Attribute>\n\nX<|Other languages,Property>\nX<|Other languages,Member>\nX<|Other languages,Slot>\nAttributes are variables that exist per instance of a class; when instantiated\nto a value, the association between the variable and its value is called a\nX<property|Language,Property>. They are where the state of an object is stored. In Raku, all\nattributes are I<private>, which means they can be accessed directly only by\nthe class instance itself. They are typically declared using the C<has>\ndeclarator and the C<!> twigil.\n\n=begin code\nclass Journey {\n    has $!origin;\n    has $!destination;\n    has @!travelers;\n    has $!notes;\n}\n=end code\n\nAlternatively, you can omit the twigil, which will still create the private\nattribute (with a C<!> twigil), and will also create an alias that binds\nthe name (without the twigil) to that attribute.  Thus, you can declare the\nsame class above with\n\n=begin code\nclass Journey {\n    has $origin;\n    has $destination;\n    has @travelers;\n    has $notes;\n}\n=end code\n\nIf you declare the class like this, you can subsequently access the attributes\neither with or without the twigil – e.g., C<$!origin> and C<$origin> refer to\nsame attribute.\n\nWhile there is no such thing as a public (or even protected) attribute,\nthere is a way to have accessor methods generated automatically: replace the\nC<!> twigil with the C<.> twigil (the C<.> should remind you of a method\ncall).\n\n=begin code\nclass Journey {\n    has $.origin;\n    has $.destination;\n    has @!travelers;\n    has $.notes;\n}\n=end code\n\nThis defaults to providing a read-only accessor. In order to allow changes\nto the attribute, add the L<is rw|/routine/is%20rw> trait:\n\n=begin code\nclass Journey {\n    has $.origin;\n    has $.destination;\n    has @!travelers;\n    has $.notes is rw;\n}\n=end code\n\nNow, after a C<Journey> object is created, its C<.origin>, C<.destination>,\nand C<.notes> will all be accessible from outside the class, but only\nC<.notes> can be modified.\n\nIf an object is instantiated without certain attributes, such as origin or\ndestination, we may not get the desired result. To prevent this, provide\ndefault values or make sure that an attribute is set on object creation\nby marking an attribute with an L<is required|/routine/is%20required> trait.\n\n=begin code\nclass Journey {\n    # error if origin is not provided\n    has $.origin is required;\n    # set the destination to Orlando as default (unless that is the origin!)\n    has $.destination = self.origin eq 'Orlando' ?? 'Kampala' !! 'Orlando';\n    has @!travelers;\n    has $.notes is rw;\n}\n=end code\n\nSince classes inherit a default constructor from L<C<Mu>|/type/Mu> and we have requested\nthat some accessor methods are generated for us, our class is already\nsomewhat functional.\n\n=begin code :preamble<class Journey {};>\n# Create a new instance of the class.\nmy $vacation = Journey.new(\n    origin      => 'Sweden',\n    destination => 'Switzerland',\n    notes       => 'Pack hiking gear!'\n);\n\n# Use an accessor; this outputs Sweden.\nsay $vacation.origin;\n\n# Use a rw accessor to change the value.\n$vacation.notes = 'Pack hiking gear and sunglasses!';\n=end code\n\nNote that, although the default constructor can initialize read-only\nattributes, it will only set attributes that have an accessor method.\nThat is, even if you pass C«travelers => [\"Alex\", \"Betty\"]» to the\ndefault constructor, the attribute C<@!travelers> is not initialized.\n\n=head2 Traits\n\nSeveral traits are provided to modify the behavior of attributes.\nAttribute traits are introduced by the C<is> keyword after the attribute name.\nThe following traits (and some others) are documented L<here|/type/Attribute#Traits>.\n\n=begin code\nclass Journey {\n    # error if origin is not provided\n    has $.origin is required;\n    # reset to this default value if Nil is assigned\n    has $.destination is default('Orlando') is rw;\n    # private attribute\n    has @!travelers;\n    # is read/write\n    has $.notes is rw;\n    # is readonly\n    has $.agent is readonly = 'Acme Travel Inc.';\n    # private attribute can (only) be set via .new\n    has $!status is built;\n}\n=end code\n\nHere's how to construct and use this new version of Journey:\n\n=begin code :preamble<class Journey {}>\n# Create a new instance of the class.\nmy $vacation = Journey.new(\n    origin      => 'Sweden',\n    status      => 'Requested'\n);\n\n# Use a setter accessor on a read/write attribute, then a getter to read it,\n# then assign Nil to reset the default.\n$vacation.destination = 'San Francisco';\nsay $vacation.destination;    # OUTPUT: «San Francisco␤»\n$vacation.destination = Nil;\nsay $vacation.destination;    # OUTPUT: «Orlando␤»\n\n# Try to change a built private attribute later.\ntry { $vacation.status = 'Booked'; }  #ERROR\n=end code\n\nNote that C<is readonly> is the default for attributes that are not marked C<is rw>,\nso in this example it has no effect. An entire class can be marked C<is rw>, in which\ncase the C<is readonly> is useful to opt out specific attributes.\n\n=head2 Methods\n\nMethods are declared with the C<method> keyword inside a class body.\n\n=begin code\nclass Journey {\n    has $.origin;\n    has $.destination;\n    has @!travelers;\n    has $.notes is rw;\n\n    method add-traveler($name) {\n        if $name ne any(@!travelers) {\n            push @!travelers, $name;\n        }\n        else {\n            warn \"$name is already going on the journey!\";\n        }\n    }\n\n    method describe() {\n        \"From $!origin to $!destination\"\n    }\n}\n=end code\n\nA method can have a signature, just like a subroutine. Attributes can be\nused in methods and can always be used with the C<!> twigil, even if they\nare declared with the C<.> twigil. This is because the C<.> twigil\ndeclares an attribute and generates an accessor method for it.\n\nLooking at the code above, there is a subtle but important difference between\nusing C<$!origin> and C<$.origin> in the method C<describe>. C<$!origin>\nis an inexpensive and obvious lookup of the attribute. C<$.origin> is a\nmethod call and thus may be overridden in a subclass. Only use C<$.origin> if\nyou want to allow overriding.\n\nUnlike subroutines, additional named arguments will not produce compile time or\nruntime errors. That allows chaining of methods via\nL<Re-dispatching|/language/functions#Re-dispatching>.\n\nYou may write your own accessors to override any or all of the autogenerated\nones.\n\n=begin code\nmy $ⲧ = \" \" xx 4; # A tab-like thing\nclass Journey {\n    has $.origin;\n    has $.destination;\n    has @.travelers;\n    has Str $.notes is rw;\n\n    multi method notes() { \"$!notes\\n\" };\n    multi method notes( Str $note ) { $!notes ~= \"$note\\n$ⲧ\" };\n\n    method Str { \"⤷ $!origin\\n$ⲧ\" ~ self.notes() ~ \"$!destination ⤶\\n\" };\n}\n\nmy $trip = Journey.new( :origin<Here>, :destination<There>,\n                        travelers => <þor Freya> );\n\n$trip.notes(\"First steps\");\nnotes $trip: \"Almost there\";\nprint $trip;\n\n# OUTPUT:\n#⤷ Here\n#       First steps\n#       Almost there\n#\n#There ⤶\n=end code\n\nThe declared multi method C<notes> overrides the auto-generated\nmethods implicit in the declaration of C<$.notes>, using a different\nsignature for reading and writing.\n\nPlease note that in C<notes $trip: \"Almost there\"> we are using X<indirect\ninvocant syntax|Language,indirect invocant syntax>, which puts first the method name, then the object, and then,\nseparated by a colon, the arguments: C<method invocant: arguments>. We can use\nthis syntax whenever it feels more natural than the classical\nperiod-and-parentheses one. It works exactly in the same way.\n\nNote how the call to the C<notes> method in the L<C<Str>|/routine/Str> method is made on\nC<self>. Writing method calls this way will leave the return value of\nthe method as is with regards to containers. To containerize return\nvalues, you can make method calls on a sigil instead of C<self>. This\ncalls various methods on the return value of the method depending on the\nsigil used to containerize it:\n\n=begin table\nSigil | Method\n==============\n $    | item\n @    | list\n %    | hash\n &    | item\n=end table\n\nFor example, the L<C<Str>|/routine/Str> method of C<Journey> can be rewritten not to use\nthe C<~> operator by embedding a sigiled method call in the string it\nreturns:\n\n=begin code :skip-test<need wrapper class>\nmethod Str { \"⤷ $!origin\\n$ⲧ$.notes()$!destination ⤶\\n\" }\n=end code\n\nThe syntax used to update C<$.notes> changed in this section with respect\nto the previous L<Attributes|#Attributes> section. Instead of an assignment:\n\n=for code :preamble<my $vacation>\n$vacation.notes = 'Pack hiking gear and sunglasses!';\n\nwe now do a method call:\n\n=for code :preamble<my $trip>\n$trip.notes(\"First steps\");\n\nX<Classes|Methods,overriding default accessors>\nOverriding the default auto-generated accessor means it is no longer\navailable to provide a mutable container on return for an assignment.\nA method call is the preferred approach to adding computation and\nlogic to the update of an attribute (see 'programmatic use' of such calls\nin the following section). Many modern languages can update\nan attribute by overloading assignment with a “setter” method. While\nRaku can overload the assignment operator for this purpose with a\nL<C<Proxy>|/type/Proxy>\nobject, overloading assignment to set attributes with complex logic is\ncurrently discouraged as\nL<weaker object oriented design|https://raku.github.io/CCR/Remaster/Jonathan%20Worthington/Raku-is-biased-towards-mutators-being-really-simple-Thats-a-good-thing.html>.\n\n=head2 Class and instance methods\n\nX<|Methods,programmatic use>\nMethod names can be resolved at runtime with the L<C<.\"\"> operator|/language/operators#methodop_.\"\"> which\nenables programmatic use of such names. For example, since an\nattribute name is also a method, we can show attribute C<a>'s value by\ncalling the C<a> method:\n\n=begin code\nclass A { has $.a = 9 }\nmy $method = 'a';\nA.new.\"$method\"().say;\n# OUTPUT: «9␤»\n=end code\n\nA method with arguments may be called in a similar manner:\n\n=begin code\nclass B {\n    has $.b = 9;\n    method mul($n) {\n        $!b * $n\n    }\n}\nmy $method = 'mul';\nB.new.\"$method\"(6).say;\n# OUTPUT: «54␤»\n=end code\n\nX<|Methods,signatures>\nA method's signature can have an I<explicit invocant> as its first parameter\nfollowed by a colon, which allows for the method to refer to the object\nit was called on.\n\n=begin code\nclass Foo {\n    method greet($me: $person) {\n        say \"Hi, I am $me.^name(), nice to meet you, $person\";\n    }\n}\nFoo.new.greet(\"Bob\");    # OUTPUT: «Hi, I am Foo, nice to meet you, Bob␤»\n=end code\n\nProviding an invocant in the method signature also allows for defining\nthe method as either as a class method, or as an object method, through\nthe use of L<type constraints|/language/signatures#Type_constraints>. The\nC<::?CLASS> variable can be used to provide the class name at compile\ntime, combined with either C<:U> (for class methods AKA static in other languages) or C<:D> (for\ninstance methods).\n\n=begin code\nclass Pizza {\n    has $!radius = 42;\n    has @.ingredients;\n\n    # class method: construct from a list of ingredients\n    method from-ingredients(::?CLASS:U $pizza: @ingredients) {\n        $pizza.new( ingredients => @ingredients );\n    }\n\n    # instance method\n    method get-radius(::?CLASS:D:) { $!radius }\n}\nmy $p = Pizza.from-ingredients: <cheese pepperoni vegetables>;\nsay $p.ingredients;     # OUTPUT: «[cheese pepperoni vegetables]␤»\nsay $p.get-radius;      # OUTPUT: «42␤»\nsay Pizza.get-radius;   # This will fail.\nCATCH { default { put .^name ~ \":\\n\" ~ .Str } };\n# OUTPUT: «X::Parameter::InvalidConcreteness:␤\n#          Invocant of method 'get-radius' must be\n#          an object instance of type 'Pizza',\n#          not a type object of type 'Pizza'.\n#          Did you forget a '.new'?»\n=end code\n\nA method can be both a class and object method by using the\nL<multi|/syntax/multi> declarator:\n\n=begin code\nclass C {\n    multi method f(::?CLASS:U:) { say \"class method\"  }\n    multi method f(::?CLASS:D:) { say \"object method\" }\n}\nC.f;       # OUTPUT: «class method␤»\nC.new.f;   # OUTPUT: «object method␤»\n=end code\n\n=head2 X<C<self>|Syntax,self>\n\nInside a method, the term C<self> is available and bound to the invocant\nobject. C<self> can be used to call further methods on the invocant,\nincluding constructors:\n\n=begin code\nclass Box {\n  has $.data;\n\n  method make-new-box-from() {\n      self.new: data => $!data;\n  }\n}\n=end code\n\nC<self> can be used in class or instance methods as well, though beware\nof trying to invoke one type of method from the other:\n\n=begin code\nclass C {\n    method g()            { 42     }\n    method f(::?CLASS:U:) { self.g }\n    method d(::?CLASS:D:) { self.f }\n}\nC.f;        # OUTPUT: «42␤»\nC.new.d;    # This will fail.\nCATCH { default { put .^name ~ \":\\n\" ~ .Str } };\n# OUTPUT: «X::Parameter::InvalidConcreteness:␤\n#          Invocant of method 'f' must be a type object of type 'C',\n#          not an object instance of type 'C'.  Did you forget a 'multi'?»\n=end code\n\nC<self> can also be used with attributes, as long as they have an accessor.\nC<self.a> will call the accessor for an attribute declared as C<has $.a>.\nHowever, there is a difference between C<self.a> and C<$.a>, since the latter\nwill itemize; C<$.a> will be equivalent to C<self.a.item> or C<$(self.a)>.\n\n=begin code\nclass A {\n    has Int @.numbers;\n    has $.x = (1, 2, 3);\n\n    method show-diff() { .say for self.x; .say for $.x }\n\n    method twice  { self.times: 2 }\n    method thrice { $.times: 3    }\n\n    method times($val = 1) { @!numbers.map(* * $val).list }\n};\n\nmy $obj = A.new(numbers => [1, 2, 3]);\n$obj.show-diff;   # OUTPUT: «1␤2␤3␤(1 2 3)␤»\nsay $obj.twice;   # OUTPUT: «(2 4 6)␤»\nsay $obj.thrice;  # OUTPUT: «(3 6 9)␤»\n=end code\n\n\nThe colon-syntax for method arguments is supported for method calls\nusing either C<self> or the shortcut, as illustrated with the methods\nC<twice> and C<thrice> in the example above.\n\nNote that if the relevant methods C<bless>, C<CREATE> of L<C<Mu>|/type/Mu>\nare not overloaded, C<self> will point to the type object in those methods.\n\nOn the other hand, the submethods C<BUILD> and C<TWEAK> are called on instances,\nin different stages of initialization. Submethods of the same name from\nsubclasses have not yet run, so you should not rely on potentially virtual\nmethod calls inside these methods.\n\n=head2 X<Private methods|Language,Private methods>\n\nMethods with an exclamation mark C<!> before the method name are not callable\nfrom anywhere outside the defining class; such methods are private in the sense\nthat they are not visible from outside the class that declares them. Private\nmethods are invoked with an exclamation mark instead of a dot:\n\n=begin code\nclass FunMath {\n    has $.value is required;\n    method !do-subtraction( $num ) {\n        if $num ~~ Str {\n            return $!value + (-1 * $num.chars);\n        }\n        return $!value + (-1 * $num);\n    }\n    method minus( $minuend: $subtrahend ) {\n        # invoking the private method on the explicit invocant\n        $minuend!do-subtraction($subtrahend);\n    }\n}\nmy $five = FunMath.new(value => 5);\nsay $five.minus(6);         # OUTPUT: «-1␤»\n\nsay $five.do-subtraction(6);\nCATCH { default { put .^name ~ \":\\n\" ~ .Str } }\n# OUTPUT: «X::Method::NotFound:\n# No such method 'do-subtraction' for invocant of type\n# 'FunMath'. Did you mean '!do-subtraction'?␤»\n=end code\n\nPrivate methods have their own namespace. They're not virtual, i.e.,\nprivate methods cannot be overridden within the inheriting class to provide any\npolymorphic behavior, thus missing ones are detected at compile time. Unlike\nin some languages where C<private> is\nan L<accessibility modifier|https://en.wikipedia.org/wiki/Access_modifiers> on a\nmethod, in Raku \"private methods\" and \"methods\" are quite different things -\nthat is to say, it's better to read \"private method\" as a compound noun rather\nthan an adjective describing a noun.\n\nPrivate methods are not inherited by subclasses.\n\n=head2 X<Submethods|Language,Submethods>\n\nSubmethods are public methods that will not be inherited by subclasses. The\nname stems from the fact that they are semantically similar to subroutines.\n\nSubmethods are useful for object construction and destruction tasks, as well\nas for tasks that are so specific to a certain type that subtypes would\ncertainly have to override them.\n\nFor example, the L<default method new|/type/Mu#method_new> calls submethod\nC<BUILD> on each class in an L<inheritance|#Inheritance> chain:\n\n=begin code\nclass Point2D {\n    has $.x;\n    has $.y;\n\n    submethod BUILD(:$!x, :$!y) {\n        say \"Initializing Point2D\";\n    }\n}\n\nclass InvertiblePoint2D is Point2D {\n    submethod BUILD() {\n        say \"Initializing InvertiblePoint2D\";\n    }\n    method invert {\n        self.new(x => - $.x, y => - $.y);\n    }\n}\n\nsay InvertiblePoint2D.new(x => 1, y => 2);\n# OUTPUT: «Initializing Point2D␤»\n# OUTPUT: «Initializing InvertiblePoint2D␤»\n# OUTPUT: «InvertiblePoint2D.new(x => 1, y => 2)␤»\n=end code\n\nSee also: L<Object construction|#Object_construction>.\n\n=head2 Inheritance\n\nClasses can have I<parent classes>.\n\n=for code :preamble<class Parent1 {}; class Parent2 {};>\nclass Child is Parent1 is Parent2 { }\n\nX<|Language,MRO>\nIf a method is called on the child class, and the child class does not\nprovide that method, the method of that name in one of the parent classes is\ninvoked instead, if it exists. The order in which parent classes are\nconsulted is called the I<method resolution order> (MRO). Raku uses the\nL<C3 method resolution order|https://en.wikipedia.org/wiki/Multiple_inheritance>.\nYou can ask a type for its MRO through a call to its metaclass:\n\n=for code\nsay List.^mro;      # OUTPUT: «((List) (Cool) (Any) (Mu))␤»\n\nIf a class does not specify a parent class, L<C<Any>|/type/Any> is assumed\nby default. All classes directly or indirectly derive from L<C<Mu>|/type/Mu>,\nthe root of the type hierarchy.\n\nAll calls to public methods are \"virtual\" in the C++ sense, which means that\nthe actual type of an object determines which method to call, not the\ndeclared type:\n\n=begin code\nclass Parent {\n    method frob {\n        say \"the parent class frobs\"\n    }\n}\n\nclass Child is Parent {\n    method frob {\n        say \"the child's somewhat more fancy frob is called\"\n    }\n}\n\nmy Parent $test;\n$test = Child.new;\n$test.frob;          # calls the frob method of Child rather than Parent\n# OUTPUT: «the child's somewhat more fancy frob is called␤»\n=end code\n\nIf you want to explicitly call the parent method on a child object,\nrefer to its full name in the parent namespace:\n\n=begin code :preamble<my $test>\n$test.Parent::frob;  # calls the frob method of Parent\n# OUTPUT: «the parent class frobs␤»\n=end code\n\n=head2 X<Delegation|Language,delegation (trait handles)>\n\nDelegation is a technique whereby an object, the I«delegator», accepts a\nmethod call but has designated another object, the I«delegatee», to process the\ncall in its place.  In other words, the I«delegator» publishes one or more\nof the I«delegatee»'s methods as its own.\n\nIn Raku, delegation is specified by applying the L«handles|/language/typesystem#trait_handles»\ntrait to an attribute. The arguments provided to the trait specify the methods\nthe object and the I«delegatee» attribute will have in common. Instead of a\nlist of method names, you can provide a L<C<Pair>|/type/Pair> (to rename; the key becomes the\nnew name), a L<C<Regex>|/type/Regex> (to handle every method with a matching name), a L<C<Whatever>|/type/Whatever>\n(to delegate all methods that the attribute L<can|/type/Metamodel::ClassHOW#method_can>\ncall), or a L<C<HyperWhatever>|/type/HyperWhatever> (to delegate all method calls, even ones that will lead to\nthe attribute's L<FALLBACK|/routine/FALLBACK> method).  You can also provide a L<C<List>|/type/List> providing\nany of those items to delegate multiple methods.  Note that the L<C<Regex>|/type/Regex>, L<C<Whatever>|/type/Whatever>, and\nL<C<HyperWhatever>|/type/HyperWhatever> forms do not delegate any methods that the class has inherited (for example,\nfrom L<C<Any>|/type/Any> or L<C<Mu>|/type/Mu>) but that explicitly naming the method does delegate it.\n\n=begin code\nclass Book {\n    has Str  $.title;\n    has Str  $.author;\n    has Str  $.language;\n    has Cool $.publication;\n}\n\nclass Product {\n    has Book $.book handles('title', 'author', 'language', year => 'publication');\n}\n\nmy $book = Book.new:\n    :title<Dune>,\n    :author('Frank Herbert'),\n    :language<English>,\n    :publication<1965>\n;\n\ngiven Product.new(:$book) {\n    say .title;    # OUTPUT: «Dune␤»\n    say .author;   # OUTPUT: «Frank Herbert␤»\n    say .language; # OUTPUT: «English␤»\n    say .year;     # OUTPUT: «1965␤»\n}\n=end code\n\nIn the example above, the class C«Product» defines the attribute C«$.book»\nand mark it with the C«handles» trait to specify the methods that will be\nforwarded to the class C«Book» whenever they're invoked on an instance\nobject of the C«Product» class. There are a few things to notice here:\n\n=item We didn't write any methods inside the C«Product» class that we invoked\nin its instance object. Instead, we instructed the class to delegate a call to\nany those methods to the C«Book» class.\n\n=item We've specified the method names C«title», C«author», and C«language»\nas they appear in the C«Book» class. On the other hand, we've renamed\nthe C«publication» method to C«year» by providing the appropriate L<C<Pair>|/type/Pair>.\n\nDelegation can be used as an alternative to inheritance by delegating\nto the parent class and not inheriting all of its methods. For example, the\nfollowing C«Queue» class delegates several methods proper of queues\nto the L«C<Array>|/type/Array» class while also providing a preferred interface for\na few of those methods (e.g., C«enqueue» for C«push»):\n\n=begin code\nclass Queue {\n    has @!q handles(\n        enqueue => 'push', dequeue => 'shift',\n        'push', 'shift', 'head', 'tail', 'elems', 'splice'\n    );\n\n    method gist {\n        '[' ~ @!q.join(', ') ~ ']'\n    }\n}\n\nmy Queue $q .= new;\n$q.enqueue($_) for 1..5;\n$q.push(6);\nsay $q.shift;                  # OUTPUT: «1␤»\nsay $q.dequeue while $q.elems; # OUTPUT: «2␤3␤4␤5␤6␤»\n\n$q.enqueue($_) for <Perl Python Raku Ruby>;\nsay $q.head;                   # OUTPUT: «Perl␤»\nsay $q.tail;                   # OUTPUT: «Ruby␤»\nsay $q;                        # OUTPUT: «[Perl, Python, Raku, Ruby]␤»\n$q.dequeue while $q.elems;\nsay $q;                        # OUTPUT: «[]␤»\n=end code\n\n\n=head2 X<Object construction|Language,new (method)>\n\nObjects are generally created through method calls, either on the type\nobject or on another object of the same type.\n\nClass L<C<Mu>|/type/Mu> provides a constructor method called\nL<new|/routine/new>, which takes named\nL<arguments|/language/functions#Arguments> and uses them to initialize public\nattributes.\n\n=begin code\nclass Point {\n    has $.x;\n    has $.y;\n}\nmy $p = Point.new( x => 5, y => 2);\n#             ^^^ inherited from class Mu\nsay \"x: \", $p.x;\nsay \"y: \", $p.y;\n# OUTPUT: «x: 5␤»\n# OUTPUT: «y: 2␤»\n=end code\n\nC<Mu.new> calls method L<bless|/routine/bless> on its invocant, passing all\nthe named L<arguments|/language/functions#Arguments>. C<bless> creates the new\nobject, and then walks all subclasses in reverse method resolution order\n(i.e. from L<C<Mu>|/type/Mu> to most derived classes). In each class C<bless>\nexecutes the following steps in the order given here:\n\n=item It checks for the existence of a method named C<BUILD>. If the method\nexists, the method is called with all the named arguments it received (from the\nC<new> method).\n\n=item If no C<BUILD> method was found, the public attributes from this class\nare initialized from named arguments of the same name.\n\n=begin item\nAll attributes that have not been touched in any of the previous steps have\ntheir default values applied:\n\nC<has $.attribute = 'default value';>\n=end item\n\n=begin item\nX<|Methods,TWEAK>\nC<TWEAK> is called should it exist. It will receive the same arguments\nC<BUILD> receives.\n=end item\n\nThis object construction scheme has several implications:\n\n=begin item\nNamed arguments to the default C<new> constructor (inherited from L<C<Mu>|/type/Mu>) can\ncorrespond directly to public attributes of any of the classes in the method\nresolution order, or to any named parameter of any C<BUILD> or C<TWEAK>\nsubmethod.\n=end item\n\n=begin item\nCustom C<BUILD> methods should always be submethods, otherwise they are\ninherited to subclasses and prevent default attribute initialization (item two\nin the above list) should the subclass not have its own C<BUILD> method.\n=end item\n\n=begin item\nC<BUILD> may set an attribute, but it does not have access to the contents of\nthe attribute declared as its default as they are only applied later.\nC<TWEAK> on the other hand is called after default values have been\napplied and will thus find the attributes initialized. So it can be used to\ncheck things or modify attributes after object construction:\n\n=begin code\nclass RectangleWithCachedArea {\n    has ($.x1, $.x2, $.y1, $.y2);\n    has $.area;\n    submethod TWEAK() {\n        $!area = abs( ($!x2 - $!x1) * ( $!y2 - $!y1) );\n    }\n}\n\nsay RectangleWithCachedArea.new( x2 => 5, x1 => 1, y2 => 1, y1 => 0).area;\n# OUTPUT: «4␤»\n=end code\n=end item\n\n=begin item\nSince passing arguments to a routine binds the arguments to the parameters,\none can simplify BUILD methods by using the attribute as a parameter.\n\nA class using ordinary binding in the C<BUILD> method:\n=begin code\nclass Point {\n    has $.x;\n    has $.y;\n\n    submethod BUILD(:$x, :$y) {\n        $!x := $x;\n        $!y := $y;\n    }\n}\nmy $p1 = Point.new( x => 10, y => 5 );\n=end code\n\nThe following C<BUILD> method is equivalent to the above:\n=begin code :preamble<has $.x; has $.y>\nsubmethod BUILD(:$!x, :$!y) {\n    # Nothing to do here anymore, the signature binding\n    # does all the work for us.\n}\n=end code\n=end item\n\n=begin item\nIn order to use default values together with a `BUILD()` method one can't use\nparameter binding of attributes, as that will always touch the attribute and\nthus prevent the automatic assignment of default values (step three in the\nabove list). Instead one would need to conditionally assign the value:\n\n=begin code\nclass A {\n    has $.attr = 'default';\n    submethod BUILD(:$attr) {\n        $!attr = $attr if defined $attr;\n    }\n}\nsay A.new(attr => 'passed').raku;\nsay A.new().raku;\n# OUTPUT: «A.new(attr => \"passed\")␤»\n# OUTPUT: «A.new(attr => \"default\")␤»\n=end code\n\nIt's simpler to set a default value of the `BUILD` parameter instead though:\n\n=begin code\nclass A {\n    has $.attr;\n    submethod BUILD(:$!attr = 'default') {}\n}\n=end code\n=end item\n\n=begin item\nBe careful when using parameter binding of attributes when the attribute has a\nspecial type requirement such as an L<C<Int>|/type/Int> type. If C<new> is called without\nthis parameter, then a default of L<C<Any>|/type/Any> will be assigned, which will cause a\ntype error. The easy fix is to add a default value to the C<BUILD> parameter.\n\n=begin code\nclass A {\n    has Int $.attr;\n    submethod BUILD(:$!attr = 0) {}\n}\nsay A.new(attr => 1).raku;\nsay A.new().raku;\n# OUTPUT: «A.new(attr => 1)␤»\n# OUTPUT: «A.new(attr => 0)␤»\n=end code\n=end item\n\n=begin item\nC<BUILD> allows to create aliases for attribute initialization:\n\n=begin code\nclass EncodedBuffer {\n    has $.enc;\n    has $.data;\n\n    submethod BUILD(:encoding(:$!enc), :$!data) { }\n}\nmy $b1 = EncodedBuffer.new( encoding => 'UTF-8', data => [64, 65] );\nmy $b2 = EncodedBuffer.new( enc      => 'UTF-8', data => [64, 65] );\n#  both enc and encoding are allowed now\n=end code\n=end item\n\n=begin item\nNote that the name C<new> is not special in Raku. It is merely a common\nconvention, one that is followed quite thoroughly in\nL<most Raku classes|/routine/new>. You can call C<bless> from any method, or\nuse C<CREATE> to fiddle around with low-level workings.\n=end item\n\n=begin item\nIf you want a constructor that accepts positional arguments, you must write\nyour own C<new> method:\n\n=begin code\nclass Point {\n    has $.x;\n    has $.y;\n    method new($x, $y) {\n        self.bless(:$x, :$y);\n    }\n}\n=end code\n\nDo note, however, that C<new> is a normal method and not involved in any of the\nconstruction process of C<bless>. So any logic placed in the C<new> method will\nnot be called when using a different C<new> method or a C<new> of a subclass.\n\n=begin code\nclass Vector {\n    has $.x;\n    has $.y;\n    has $.length;\n    method new($x, $y) {\n        self.bless(:$x, :$y, length => sqrt($x**2 * $y**2));\n    }\n}\n\nclass NamedVector is Vector {\n    has $.name;\n    method new($name, $x, $y) {\n        self.bless(:$name, :$x, :$y);\n    }\n}\n\nmy $v = Vector.new: 3, 4;\nsay $v.length; # OUTPUT: «5␤»\n\nmy $f = NamedVector.new: 'Francis', 5, 12;\nsay $f.length; # OUTPUT: «(Any)␤»\n=end code\n\n=end item\n\nHere is an example where we I<enrich> the L<C<Str>|/type/Str> class with an\nauto-incrementing ID:\n\n=begin code\nclass Str-with-ID is Str {\n    my $counter = 0;\n    has Int $.ID  is rw = 0;\n\n    multi method new( $str ) {\n        self.bless( value => $str );\n    }\n    submethod BUILD( :$!ID = $counter++ ) {}\n}\n\nsay Str-with-ID.new(\"1.1,2e2\").ID;                  # OUTPUT: «0␤»\nmy $enriched-str = Str-with-ID.new(\"3,4\");\nsay \"$enriched-str, {$enriched-str.^name}, {$enriched-str.ID}\";\n# OUTPUT: «3,4, Str-with-ID, 1␤»\n=end code\n\nWe create a custom C<new> since we want to be able to be able to initialize\nour new class with a bare string. C<bless> will call C<Str.BUILD> which will\nI<capture> the value it's looking for, the pair C«value => $str» and\ninitialize itself. But we have to also initialize the properties of the\nsubclass, which is why within C<BUILD> we initialize C<$.ID>. As seen in the\noutput, the objects will be correctly initialized with an ID and can be used\njust like a normal L<C<Str>|/type/Str>.\n\n=head2 Object cloning\n\nThe cloning is done using the L<clone|/routine/clone> method available on all\nobjects, which shallow-clones both public and private attributes. New values for\nI<public> attributes can be supplied as named arguments.\n\n=begin code\nclass Foo {\n    has $.foo = 42;\n    has $.bar = 100;\n}\n\nmy $o1 = Foo.new;\nmy $o2 = $o1.clone: :bar(5000);\nsay $o1; # OUTPUT: «Foo.new(foo => 42, bar => 100)␤»\nsay $o2; # OUTPUT: «Foo.new(foo => 42, bar => 5000)␤»\n=end code\n\nSee document for L<clone|/routine/clone> for details on how non-scalar\nattributes get cloned, as well as examples of implementing your own custom clone\nmethods.\n\n=head1 X<Roles|Syntax,role>\n\nRoles are a collection of attributes and methods; however, unlike classes, roles\nare meant for describing only parts of an object's behavior; this is why, in\ngeneral, roles are intended to be I<mixed in> classes and objects. In general,\nclasses are meant for managing objects and roles are meant for managing behavior\nand code reuse within objects.\n\nX<|Syntax,does>\nRoles use the keyword X<C<role>|Syntax,role declaration> preceding the name of the role that is\ndeclared. Roles are mixed in using the C<does> keyword preceding the name of\nthe role that is mixed in.\n\nRoles can also be mixed into a class using C<is>. However, the semantics of\nC<is> with a role are quite different from those offered by C<does>. With C<is>,\na class is punned from the role, and then inherited from. Thus, there is no\nflattening composition, and none of the safeties which C<does> provides.\n\n=begin code\nconstant ⲧ = \" \" xx 4; #Just a ⲧab\nrole Notable {\n    has Str $.notes is rw;\n\n    multi method notes() { \"$!notes\\n\" };\n    multi method notes( Str $note ) { $!notes ~= \"$note\\n\" ~ ⲧ };\n\n}\n\nclass Journey does Notable {\n    has $.origin;\n    has $.destination;\n    has @.travelers;\n\n    method Str { \"⤷ $!origin\\n\" ~ ⲧ ~ self.notes() ~ \"$!destination ⤶\\n\" };\n}\n\nmy $trip = Journey.new( :origin<Here>, :destination<There>,\n                        travelers => <þor Freya> );\n\n$trip.notes(\"First steps\");\nnotes $trip: \"Almost there\";\nprint $trip;\n# OUTPUT:\n#⤷ Here\n#       First steps\n#       Almost there\n#\n#There ⤶\n=end code\n\nRoles are immutable as soon as the compiler parses the closing curly brace\nof the role declaration.\n\n=head2 Applying roles\n\nRole application differs significantly from class inheritance. When a role\nis applied to a class, the methods of that role are copied into the class.\nIf multiple roles are applied to the same class, conflicts (e.g.\nattributes or non-multi methods of the same name) cause a compile-time error,\nwhich can be solved by providing a method of the same name in the class.\n\nThis is much safer than multiple inheritance, where conflicts are never\ndetected by the compiler, but are instead resolved to the superclass\nthat appears earlier in the method resolution order, which might not\nbe what the programmer wanted.\n\nFor example, if you've discovered an efficient method to ride cows, and are\ntrying to market it as a new form of popular transportation, you might have\na class C<Bull>, for all the bulls you keep around the house, and a class\nC<Automobile>, for things that you can drive.\n\n=begin code\nclass Bull {\n    has Bool $.castrated = False;\n    method steer {\n        # Turn your bull into a steer\n        $!castrated = True;\n        return self;\n    }\n}\nclass Automobile {\n    has $.direction;\n    method steer($!direction) { }\n}\nclass Taurus is Bull is Automobile { }\n\nmy $t = Taurus.new;\nsay $t.steer;\n# OUTPUT: «Taurus.new(castrated => Bool::True, direction => Any)␤»\n=end code\n\nWith this setup, your poor customers will find themselves unable to turn\ntheir Taurus and you won't be able to make more of your product! In this\ncase, it may have been better to use roles:\n\n=begin code :skip-test<illustrates error>\nrole Bull-Like {\n    has Bool $.castrated = False;\n    method steer {\n        # Turn your bull into a steer\n        $!castrated = True;\n        return self;\n    }\n}\nrole Steerable {\n    has Real $.direction;\n    method steer(Real $d = 0) {\n        $!direction += $d;\n    }\n}\nclass Taurus does Bull-Like does Steerable { }\n=end code\n\nThis code will die with something like:\n\n=begin code :lang<text>\n===SORRY!===\nMethod 'steer' must be resolved by class Taurus because it exists in\nmultiple roles (Steerable, Bull-Like)\n=end code\n\nThis check will save you a lot of headaches:\n\n=begin code :preamble<role Bull-Like{}; role Steerable{};>\nclass Taurus does Bull-Like does Steerable {\n    method steer($direction?) {\n        self.Steerable::steer($direction)\n    }\n}\n=end code\n\nWhen a role is applied to a second role, the actual application is delayed\nuntil the second role is applied to a class, at which point both roles are\napplied to the class. Thus\n\n=begin code\nrole R1 {\n    # methods here\n}\nrole R2 does R1 {\n    # methods here\n}\nclass C does R2 { }\n=end code\n\nproduces the same class C<C> as\n\n=begin code\nrole R1 {\n    # methods here\n}\nrole R2 {\n    # methods here\n}\nclass C does R1 does R2 { }\n=end code\n\n=head2 Stubs\n\nWhen a role contains a stubbed method, that is, a method whose code is limited\nto C<...>, a non-stubbed version of a method of the same name must be supplied\nat the time the role is applied to a class. This allows you to create roles that\nact as abstract interfaces.\n\n=begin code :skip-test<illustrates error>\nrole AbstractSerializable {\n    method serialize() { ... }        # literal ... here marks the\n                                      # method as a stub\n}\n\n# the following is a compile time error, for example\n#        Method 'serialize' must be implemented by Point because\n#        it's required by a role\n\nclass APoint does AbstractSerializable {\n    has $.x;\n    has $.y;\n}\n\n# this works:\nclass SPoint does AbstractSerializable {\n    has $.x;\n    has $.y;\n    method serialize() { \"p($.x, $.y)\" }\n}\n=end code\n\nThe implementation of the stubbed method may also be provided by another\nrole.\n\n=head2 Inheritance\n\nRoles cannot inherit from classes, but they may I<carry> classes, causing\nany class which does that role to inherit from the carried classes.\nSo if you write:\n\n=begin code\nrole A is Exception { }\nclass X::Ouch does A { }\nX::Ouch.^parents.say # OUTPUT: «((Exception))␤»\n=end code\n\nthen C<X::Ouch> will inherit directly from Exception, as we can see above\nby listing its parents.\n\nAs they do not use what can properly be called inheritance, roles are not part\nof the class hierarchy. Roles are listed with the C<.^roles> metamethod\ninstead, which uses C<transitive> as flag for including all levels or just the\nfirst one. Despite this, a class or instance may still be tested with\nsmartmatches or type constraints to see if it does a role.\n\n=begin code\nrole F { }\nclass G does F { }\nG.^roles.say;                    # OUTPUT: «((F))␤»\nrole Ur {}\nrole Ar does Ur {}\nclass Whim does Ar {}; Whim.^roles(:!transitive).say;   # OUTPUT: «((Ar))␤»\nsay G ~~ F;                      # OUTPUT: «True␤»\nmulti a (F $a) { \"F\".say }\nmulti a ($a)   { \"not F\".say }\na(G);                            # OUTPUT: «F␤»\n=end code\n\n=head2 Pecking order\n\nA method defined directly in a class will always override definitions from\napplied roles or from inherited classes. If no such definition exists, methods\nfrom roles override methods inherited from classes. This happens both when\nsaid class was brought in by a role, and also when said class was inherited\ndirectly.\n\n=begin code\nrole M {\n  method f { say \"I am in role M\" }\n}\n\nclass A {\n  method f { say \"I am in class A\" }\n}\n\nclass B is A does M {\n  method f { say \"I am in class B\" }\n}\n\nclass C is A does M { }\n\nB.new.f; # OUTPUT: «I am in class B␤»\nC.new.f; # OUTPUT: «I am in role M␤»\n=end code\n\nNote that each candidate for a multi-method is its own method. In this case,\nthe above only applies if two such candidates have the same signature.\nOtherwise, there is no conflict, and the candidate is just added to the\nmulti-method.\n\n=head2 Automatic role punning\n\nAny attempt to directly instantiate a role or use it as a type object\nwill automatically create a class with the same name as the role,\nmaking it possible to transparently use a role as if it were a class.\n\n=begin code\nrole Point {\n    has $.x;\n    has $.y;\n    method abs { sqrt($.x * $.x + $.y * $.y) }\n    method dimensions { 2 }\n}\nsay Point.new(x => 6, y => 8).abs; # OUTPUT: «10␤»\nsay Point.dimensions;              # OUTPUT: «2␤»\n=end code\n\nWe call this automatic creation of classes I<punning>, and the generated class\na I<pun>.\n\nPunning is not caused by most L<metaprogramming|/language/mop> constructs,\nhowever, as those are sometimes used to work directly with roles.\n\n=head2 X<Parameterized roles|Language,Parameterized Roles>\n\nRoles can be parameterized, by giving them a signature in square brackets:\n\n=begin code\nrole BinaryTree[::Type] {\n    has BinaryTree[Type] $.left;\n    has BinaryTree[Type] $.right;\n    has Type $.node;\n\n    method visit-preorder(&cb) {\n        cb $.node;\n        for $.left, $.right -> $branch {\n            $branch.visit-preorder(&cb) if defined $branch;\n        }\n    }\n    method visit-postorder(&cb) {\n        for $.left, $.right -> $branch {\n            $branch.visit-postorder(&cb) if defined $branch;\n        }\n        cb $.node;\n    }\n    method new-from-list(::?CLASS:U: *@el) {\n        my $middle-index = @el.elems div 2;\n        my @left         = @el[0 .. $middle-index - 1];\n        my $middle       = @el[$middle-index];\n        my @right        = @el[$middle-index + 1 .. *];\n        self.new(\n            node    => $middle,\n            left    => @left  ?? self.new-from-list(@left)  !! self,\n            right   => @right ?? self.new-from-list(@right) !! self,\n        );\n    }\n}\n\nmy $t = BinaryTree[Int].new-from-list(4, 5, 6);\n$t.visit-preorder(&say);    # OUTPUT: «5␤4␤6␤»\n$t.visit-postorder(&say);   # OUTPUT: «4␤6␤5␤»\n=end code\n\nHere the signature consists only of a type capture, but any signature will do:\n\n=begin code\nenum Severity <debug info warn error critical>;\n\nrole Logging[$filehandle = $*ERR] {\n    method log(Severity $sev, $message) {\n        $filehandle.print(\"[{uc $sev}] $message\\n\");\n    }\n}\n\nLogging[$*OUT].log(debug, 'here we go'); # OUTPUT: «[DEBUG] here we go␤»\n=end code\n\nYou can have multiple roles of the same name, but with different signatures;\nthe normal rules of multi dispatch apply for choosing multi candidates.\n\nX<|Syntax,but>\n=head2 X<Mixins|Language,Mixins> of roles\n\nRoles can be mixed into objects. A role's given attributes and methods will be\nadded to the methods and attributes the object already has. Multiple mixins and\nanonymous roles are supported.\n\n=begin code\nrole R { method Str() {'hidden!'} };\nmy $i = 2 but R;\nsub f(\\bound){ put bound };\nf($i); # OUTPUT: «hidden!␤»\nmy @positional := <a b> but R;\nsay @positional.^name; # OUTPUT: «List+{R}␤»\n=end code\n\nNote that the object got the role mixed in, not the object's class or the\ncontainer. Thus, @-sigiled containers will require binding to make the role\nstick as is shown in the example with C<@positional>. Some operators will return\na new value, which effectively strips the mixin from the result. That is why it\nmight be more clear to mix in the role in the declaration of the variable using\nC<does>:\n\n=begin code\nrole R {};\nmy @positional does R = <a b>;\nsay @positional.^name; # OUTPUT: «Array+{R}␤»\n=end code\n\nThe operator C<infix:<but>> is narrower than the list constructor. When\nproviding a list of roles to mix in, always use parentheses.\n\n=for code\nrole R1 { method m {} }\nrole R2 { method n {} }\nmy $a = 1 but R1,R2; # R2 is in sink context, issues a WARNING\nsay $a.^name;\n# OUTPUT: «Int+{R1}␤»\nmy $all-roles = 1 but (R1,R2);\nsay $all-roles.^name; # OUTPUT: «Int+{R1,R2}␤»\n\nIf the role supplies exactly one attribute, an initializer can be passed in\nparentheses:\n\n=begin code\nrole Named {\n    has $.name;\n}\nmy $hero = 1.Rat but Named('Remy');\nsay $hero.name;     # OUTPUT: «Remy␤»\n=end code\n\nMixins can be used at any point in your object's life.\n\n=begin code\n# A counter for Table of Contents\nrole TOC-Counter {\n    has Int @!counters is default(0);\n    method Str() { @!counters.join: '.' }\n    method inc($level) {\n        @!counters[$level - 1]++;\n        @!counters.splice($level);\n        self\n    }\n}\n\nmy Num $toc-counter = NaN;     # don't do math with Not A Number\nsay $toc-counter;              # OUTPUT: «NaN␤»\n$toc-counter does TOC-Counter; # now we mix the role in\n$toc-counter.inc(1).inc(2).inc(2).inc(1).inc(2).inc(2).inc(3).inc(3);\nput $toc-counter / 1;          # OUTPUT: «NaN␤» (because that's numerical context)\nput $toc-counter;              # OUTPUT: «2.2.2␤» (put will call TOC-Counter::Str)\n=end code\n\nRoles can be anonymous.\n\n=begin code\nmy %seen of Int is default(0 but role :: { method Str() {'NULL'} });\nsay %seen<not-there>;          # OUTPUT: «NULL␤»\nsay %seen<not-there>.defined;  # OUTPUT: «True␤» (0 may be False but is well defined)\nsay Int.new(%seen<not-there>); # OUTPUT: «0␤»\n=end code\n\n=head1 Metaobject programming and introspection\n\nRaku has a metaobject system, which means that the behavior of objects,\nclasses, roles, grammars, enums, etc. are themselves controlled by other\nobjects; those objects are called I<metaobjects>. Metaobjects are, like\nordinary objects, instances of classes, in this case we call them I<metaclasses>.\n\nFor each object or class you can get the metaobject by calling C<.HOW> on it.\nNote that although this looks like a method call, it works more like a macro.\n\nSo, what can you do with the metaobject? For one you can check if two\nobjects have the same metaclass by comparing them for equality:\n\n=begin code\nsay 1.HOW ===   2.HOW;      # OUTPUT: «True␤»\nsay 1.HOW === Int.HOW;      # OUTPUT: «True␤»\nsay 1.HOW === Num.HOW;      # OUTPUT: «False␤»\n=end code\n\nRaku uses the word I<HOW> (Higher Order Workings) to refer to the metaobject\nsystem. Thus it should be no surprise that in Rakudo, the class name of the\nmetaclass that controls class behavior is called C<Perl6::Metamodel::ClassHOW>.\nFor each class there is one instance of C<Perl6::Metamodel::ClassHOW>.\n\nBut the metamodel does much more for you. For example, it allows\nyou to introspect objects and classes. The calling convention for methods on\nmetaobjects is to call the method on the metaobject and pass in the object\nof interest as first argument to the object. So to get the name of the class\nof an object, you could write:\n\n=begin code\nmy $object = 1;\nmy $metaobject = 1.HOW;\nsay $metaobject.name($object);      # OUTPUT: «Int␤»\n\n# or shorter:\nsay 1.HOW.name(1);                  # OUTPUT: «Int␤»\n=end code\n\n(The motivation is that Raku also wants to allow a more prototype-based\nobject system, where it's not necessary to create a new metaobject for\nevery type).\n\nThere's a shortcut to keep from using the same object twice:\n\n=begin code\nsay 1.^name;                        # OUTPUT: «Int␤»\n# same as\nsay 1.HOW.name(1);                  # OUTPUT: «Int␤»\n=end code\n\nSee L<C<Metamodel::ClassHOW>|/type/Metamodel::ClassHOW> for documentation on the\nmetaclass of C<class> and also the L<general documentation on the metaobject\nprotocol|/language/mop>.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/operators.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Operators\n\n=SUBTITLE Common Raku infixes, prefixes, postfixes, and more!\n\nSee L<creating operators|/language/optut> on how to define new operators.\n\n=head1 Operator precedence\n\nThe precedence and associativity of Raku operators determine how an expression\nis going to be parsed, more specifically, what operands will be passed to which\noperand during the evaluation of the expression. (Parentheses can also be used\nto indicate if a subexpression should be treated as a single operand.)\n\nWhen an operand appears in a position where it could belong to two operators,\ne.g. C<2> in C<1 + 2 * 3>, the operand belongs to the operator with higher\nprecedence - in this case, the C<*> operator. This means that the operands of\nC<+> are C<1> and C<2 * 3> so C<1 + 2 * 3> is equivalent to C<1 + (2 * 3)>, and\nthe sum will evaluate to C<7>. On the other hand, C<1 ** 2 * 3> will be equivalent\nto C<(1 ** 2) * 3> and evaluate to C<3> because the L<power operator C<**>|#infix_**>\nhas higher precedence than C<*>.\n\nInstead of \"precedence\" one can also speak of \"binding\": operators with a higher\nprecedence are then said to have a tighter binding to the operand(s) in\nquestion, while operators with a lower precedence are said to have a looser\nbinding. In practice one may also encounter blends of terminology, such as\nstatements that an operator has a tighter or looser precedence.\n\nThe following table summarizes the precedence levels offered by Raku, listing\nthem in order from high to low precedence. For each precedence level the table\nalso indicates the associativity (discussed more below) of the operators\nassigned to that level and lists some example operators at that precedence\nlevel.\n\n=begin table\n\n    Precedence Level | Associativity | Examples\n    =================+===============+==========\n    Term¹            | non           | 42 3.14 \"eek\" qq[\"foo\"] $x :!verbose @$array rand time now ∅\n    Method call      | left          | .meth .\\+ .? .* .() .[] .{} .<> .«» .:: .= .^ .: i\n    Autoincrement    | non           | \\+\\+ --\n    Exponentiation   | right         | **\n    Symbolic unary   | left          | ! \\+ - ~ ? \\| \\|\\| \\+^ ~^ ?^ ^ //\n    Dotty infix¹     | left          | .= .\n    Multiplicative   | left          | * × / ÷ % %% \\+& \\+< \\+> ~& ~< ~> ?& div mod gcd lcm\n    Additive         | left          | \\+ - − \\+\\| \\+^ ~\\| ~^ ?\\| ?^\n    Replication      | left          | x xx\n    Concatenation    | list          | ~ o ∘\n    Junctive and     | list          | & (&) (.) ∩ ⊍\n    Junctive or      | list          | \\| ^ (\\|) (^) (\\+) (-) ∪ ⊖ ⊎ ∖\n    Named unary¹     | left          | temp let\n    Structural       | non           | but does <=> leg unicmp cmp coll .. ..^ ^.. ^..^\n    Chaining         | chain         | != ≠ == ⩵ < <= ≤ > >= ≥ eq ne lt le gt ge ~~ === ⩶ eqv !eqv =~= ≅ (elem) (cont) (<) (>) (<=) (>=) (<\\+) (>\\+) (==) ∈ ∊ ∉ ∋ ∍ ∌ ≡ ≢ ⊂ ⊄ ⊃ ⊅ ⊆ ⊈ ⊇ ⊉ ≼ ≽\n    Tight and        | list          | &&\n    Tight or         | list          | \\|\\| ^^ // min max\n    Conditional¹     | right         | ?? !! ff ff^ ^ff ^ff^ fff fff^ ^fff ^fff^\n    Item assignment  | right         | =² => \\+= -= **= xx=\n    Loose unary      | left          | so not\n    Comma            | list          | , :\n    List infix       | list          | Z minmax X X~ X* Xeqv ... … ...^ …^ ^... ^… ^...^ ^…^\n    List prefix      | right         | =³ ??? !!! ... [\\+] [*] Z=\n    Loose and        | list          | and andthen notandthen\n    Loose or         | list          | or xor orelse\n    Sequencer¹       | list          | <== ==> <<== ==>>\n    Terminator¹      | non           | ; {...} unless extra ) ] }\n\n=end table\n\nNotes:\n=item1 for the precedence levels marked with C<¹>, there are no operator\nsubroutines with that precedence level (usually because the operators at that\nprecedence level are special-cased by the compiler).  This means that you cannot\naccess that precedence level when setting the L<precedence of custom\noperators|/language/functions#Precedence>.\n=item1 C<=²> denotes L<item\nassignment|#infix_=_(item_assignment)> while C<=³> denotes L<list assignment\noperator|#infix_=_(list_assignment)>.\n\n=head1 Operator associativity\n\nAssociativity can be seen as a tiebreaker: where two operators with the same\nprecedence level act on an operand, the associativity of the operators determines\nwhich operator the given operand belongs to. For instance, in the expression\nC<100 / 2 * 10>, the binary division operator C</> and the binary multiplication\noperator C<*> have equal precedence, so their associativity decides which operator\nC<2> belongs to. As the two operators are I<left associative>, operations are\ngrouped from the left like this: C<(100 / 2) * 10>. The expression thus\nevaluates to C<500>. Conversely, if C</> and C<*> had both been I<right\nassociative>, the expression would have been grouped as C<100 / (2 * 10)> and\nwould have evaluated to C<5>.\n\nThe following table shows how each associativity affects the interpretation of\nan expression involving three such operators of equal precedence and the same\nassociativity (using a fictitious infix C<§> operator):\n\n=begin table\n\n     Associativity | Meaning of $a § $b § $c § $d\n    ===============+========================\n     left          |  (($a § $b) § $c) § $d\n     right         |  $a § ($b § ($c § $d))\n     non           |  ILLEGAL\n     chain         |  ($a § $b) and ($b § $c) and ($c § $d)\n     list          |  infix:<§>($a, $b, $c, $d)\n\n=end table\n\nAlthough this table only depicts infix operators, associativity also determines\nthe structure of expressions when other types of operators are used. (Note: currently\nonly the associativity of infix operators can be I<set>.)\nFor example, if you created an infix C<§> operator with the precedence\nC<equiv(&prefix:<~>)>, then in the expression C<~$a § $b>, C<$a>\ncould be the left operand of C<§> or the (only) operand of C<~>, depending on the\nassociativity you assigned to C<§>.  If C<§> is left associative, then C<$a> will be\nthe operand of C<~> and C<~$a> will be the left operand of C<§>, making the expression\nequivalent to C<(~$a) § $b>. If C<§> is right associative, then C<$a> will be the\nleft operand of C<§> and the expression will be equivalent to C<~($a § $b)>.\n\nWhen two operators have the same precedence but I<different> associativity,\ndetermining the grouping of operands is more complicated.  However, for\noperators built in to Raku, all operators with the same precedence level also\nhave the same associativity.\n\n=begin comment\n   Associativity for unary ops is NYI, see https://github.com/rakudo/rakudo/issues/4779\n   I'm leaving this text in a comment so that it can more easily be added back in\n   when the that support is added.\n\n   Associativity works slightly differently for unary operators (that is, operators\n   that take only one operand such as prefix and postfix operators).  The following\n   table shows the grouping for a fictitious C<¶> operator given left,\n   right, or non associativity.\n\n   =begin table\n\n      Associativity   |  Meaning of ¶$a¶\n      ================+==========================\n       left           |  (¶$a)¶\n       right          |  ¶($a¶)\n       non            |  ILLEGAL\n\n   =end table\n=end comment\n\nSetting the associativity of non-infix operators is not yet implemented.\n\nIn the operator descriptions below, a default associativity of I<left>\nis assumed.\n\n=head1 Operator classification\n\nX<|Language,prefix operator>\nX<|Language,infix operator>\nX<|Language,postfix operator>\nX<|Language,circumfix operator>\nX<|Language,postcircumfix operator>\nX<|Language,method operators>\n\nOperators can occur in several positions relative to a term:\n\n=begin table\n\n    \\+term          | prefix\n    term1 \\+ term2  | infix\n    term\\+\\+        | postfix\n    (term)          | circumfix\n    term1[term2]    | postcircumfix\n    .+(term)        | method\n=end table\n\nEach operator (except method operators) is also available as a subroutine. The\nname of the routine is formed from the operator category, followed by a colon,\nthen a list quote construct with the symbol(s) that make up the operator:\n\n    infix:<+>(1, 2);                # same as 1 + 2\n    circumfix:«[ ]»(<a b c>);       # same as [<a b c>]\n\nAs a special case, a I<listop> (list operator) can stand either as a\nterm or as a prefix. Subroutine calls are the most common listops. Other\ncases include metareduced infix operators (C<[+] 1, 2, 3>) and the\nL<listop ...|#listop_...> etc. stub operators.\n\nDefining custom operators is covered in\nL<Defining operators functions|/language/functions#Defining_operators>.\n\n=head1 Substitution operators\n\nEach substitution operator comes into two main forms: a lowercase one (e.g.,\nC<s///>) that performs I<in-place> (i.e., I<destructive> behavior; and an\nuppercase form (e.g., C<S///>) that provides a I<non-destructive> behavior.\n\nX<|Operators,s/// in-place substitution>\n=head2 C<s///> in-place substitution\n\n    my $str = 'old string';\n    $str ~~ s/o .+ d/new/;\n    say $str; # OUTPUT: «new string␤»\n\nC<s///> operates on the C<$_> topical variable, changing it in\nplace. It uses the given\nL«C<Regex>|/type/Regex» to find portions to replace and changes them to the\nprovided replacement string. Sets C<$/> to the L«C<Match>|/type/Match» object\nor, if multiple matches were made, a L«C<List>|/type/List» of L<C<Match>|/type/Match> objects.\nReturns C<$/>.\n\nIt's common to use this operator with the C<~~> smartmatch operator, as it\naliases left-hand side to C<$_>, which C<s///> uses.\n\nRegex captures can be referenced in the replacement part; it takes the same\nadverbs as the L«C<.subst> method|/routine/subst», which go between the C<s>\nand the opening C</>, separated with optional whitespace:\n\n    my $str = 'foo muCKed into the lEn';\n\n    # replace second 'o' with 'x'\n    $str ~~ s:2nd/o/x/;\n\n    # replace 'M' or 'L' followed by non-whitespace stuff with 'd'\n    # and lowercased version of that stuff:\n    $str ~~ s :g :i/<[ML]> (\\S+)/d{lc $0}/;\n\n    say $str; # OUTPUT: «fox ducked into the den␤»\n\nYou can also use a different delimiter:\n\n    my $str = 'foober';\n    $str ~~ s!foo!fox!;\n    $str ~~ s{b(.)r} = \" d$0n\";\n    say $str; # OUTPUT: «fox den␤»\n\nNon-paired characters can simply replace the original slashes. Paired\ncharacters, like curly braces, are used only on the match portion, with the\nsubstitution given by assignment (of anything: a string, a routine call, etc.).\n\nX<|Operators,S/// non-destructive substitution>\n=head2 C<S///> non-destructive substitution\n\n    say S/o .+ d/new/ with 'old string';      # OUTPUT: «new string␤»\n    S:g/« (.)/$0.uc()/.say for <foo bar ber>; # OUTPUT: «Foo␤Bar␤Ber␤»\n\nC<S///> uses the same semantics as the C<s///> operator, except\nit leaves the original string intact\nand I<returns the resultant string> instead of C<$/> (C<$/> still being set\nto the same values as with C<s///>).\n\nB<Note:> since the result is obtained as a return value, using this\noperator with the C<~~> smartmatch operator is a mistake and will issue a\nwarning. To execute the substitution on a variable that isn't the C<$_> this\noperator uses, alias it to C<$_> with C<given>, C<with>, or any other way.\nAlternatively, use the L«C<.subst> method|/routine/subst».\n\nX<|Operators,tr/// in-place transliteration>\n=head2 C<tr///> in-place transliteration\n\n    my $str = 'old string';\n    $str ~~ tr/dol/wne/;\n    say $str; # OUTPUT: «new string␤»\n\nC<tr///> operates on the C<$_> topical variable and changes it in place.\nIt behaves similar to\nL«C<Str.trans>|/routine/trans» called with a single L<C<Pair>|/type/Pair> argument, where\nkey is the matching part (characters C<dol> in the example above) and value is\nthe replacement part (characters C<wne> in the example above). Accepts the\nsame adverbs as L«C<Str.trans>|/routine/trans». Returns the L<C<StrDistance>|/type/StrDistance> object\nthat measures the distance between original value and the resultant string.\n\n    my $str = 'old string';\n    $str ~~ tr:c:d/dol st//;\n    say $str; # OUTPUT: «old st␤»\n\nX<|Operators,TR/// non-destructive transliteration>\n=head2 C<TR///> non-destructive transliteration\n\n    with 'old string' {\n        say TR/dol/wne/; # OUTPUT: «new string␤»\n    }\n\nC<TR///> behaves the same as the C<tr///> operator,\nexcept that it leaves the C<$_>\nvalue untouched and instead returns the resultant string.\n\n    say TR:d/dol // with 'old string'; # OUTPUT: «string␤»\n\n=head1 Assignment operators\n\nRaku has a variety of assignment operators, which can be roughly classified as\nsimple assignment operators and compound assignment operators.\n\nThe simple assignment operator symbol is C<=>. It is 'overloaded' in the sense\nthat it can mean either L<item\nassignment|#infix_=_(item_assignment)> or L<list\nassignment|#infix_=_(list_assignment)> depending on the\ncontext in which it is used:\n\n    my $x = 1;        # item assignment; $x = 1\n    my @x = 1,2,3;    # list assignment; @x = [1,2,3]\n\nSee the section on L<item and list\nassignment|/language/variables#Item_and_list_assignment> for a more elaborate\nand comparative discussion of these two types of assignment.\n\nThe compound assignment operators are\nL<metaoperators|#Metaoperators>: they combine the simple\nassignment operator C<=> with an infix operator to form a new operator that\nperforms the operation specified by the infix operator before assigning the\nresult to the left operand. Some examples of built-in compound assignment\noperators are C<+=>, C<-=>, C<*=>, C</=>, C<min=>, and C<~=>. Here is how they\nwork:\n\n    my $a = 32;\n    $a += 10;         # $a = 42\n    $a -= 2;          # $a = 40\n\n    $a = 3;\n    $a min= 5;        # $a = 3\n    $a min= 2;        # $a = 2\n\n    my $s = 'a';\n    $s ~= 'b';        # $s = 'ab'\n\n    # And an example of a custom operator:\n    sub infix:<space-concat> ($a, $b) { $a ~ \" \" ~ $b };\n    $a = 'word1';\n    $a space-concat= 'word2';                 # OUTPUT: «'word1 word2'␤»\n\nOne thing the simple and compound assignment operators have in common is that\nthey form so-called I<assignment expressions> that return or evaluate to the\nassigned value:\n\n    my sub fac (Int $n) { [*] 1..$n };        # sub for calculating factorial\n    my @x = ( my $y = fac(100), $y*101 );     # @x = [100!, 101!]\n\n    my $i = 0;\n    repeat { say $i } while ($i += 1) < 10;   # OUTPUT: «0,1,2,...9␤»\n\nIn the first example, the assignment expression C<my $y = fac(100)> declares\nC<$y>, assigns the value C<fac(100)> to it, and finally returns the assigned\nvalue C<fac(100)>. The returned value is then taken into account for\nconstructing the List. In the second example the compound-assignment expression\nC<$i += 1> assigns the value C<$i + 1> to C<$i>, and subsequently evaluates to\nthe assigned value C<$i+1>, thus allowing the returned value to be used for\njudging the while loop condition.\n\nIn dealing with simple and compound assignment operators, it is tempting to\nthink that for instance the following two statements are (always) equivalent:\n\n    =begin code :lang<pseudo>\n    expression1 += expression2;                     # compound assignment\n    expression1  = expression1 + expression2;       # simple assignment\n    =end code\n\nThey are not, however, for two reasons. Firstly, C<expression1> in the compound\nassignment statement is evaluated only once, whereas C<expression1> in the\nsimple assignment statement is evaluated twice. Secondly, the compound\nassignment statement may, depending on the infix operator in question,\nimplicitly initialize C<expression1> if it is a variable with an undefined\nvalue. Such initialization will not occur for C<expression1> in the simple\nassignment statement.\n\nThe aforementioned two differences between the simple and compound assignment\nstatements are briefly elucidated below.\n\nThe first difference is common amongst programming languages and mostly\nself-explanatory. In the compound assignment, there is only one C<expression1>\nthat is explicitly specified to serve both as a term of the addition to be\nperformed and as the location where the result of the addition, the sum, is to\nbe stored. There is thus no need to evaluate it twice. The simple assignment, in\ncontrast, is more generic in the sense that the value of the C<expression1> that\nserves as a term of the addition need not necessarily be the same as the value\nof the C<expression1> that defines the location where the sum must be stored.\nThe two expressions are therefore evaluated separately. The distinction is\nparticularly relevant in cases where the evaluation of C<expression1> has side\neffects in the form of changes to one or more variables:\n\n    my @arr = [10, 20, 30];\n    my $i = 0;\n\n    if rand < 1/2 {\n        @arr[++$i] += 1;                # @arr = [10,21,30]\n    } else {\n        @arr[++$i] = @arr[++$i] + 1;    # @arr = [10,31,30] (or [10,20,21]?)\n    }                                   # the result may be implementation-specific\n    say @arr;\n\nThe second difference pointed out above is related to the widespread practice of\nusing compound assignment operators in I<accumulator patterns>. Such patterns\ninvolve a so-called I<accumulator>: a variable that calculates the sum or a\nproduct of a series of values in a loop. To obviate the need for explicit\naccumulator initialization, Raku's compound assignment operators silently take\ncare of the initialization where this is sensibly possible:\n\n    my @str = \"Cleanliness is next to godliness\".comb;\n    my ($len, $str);\n    for @str -> $c {\n      $len += 1;\n      $str ~= $c;\n    }\n    say \"The string '$str' has $len characters.\";\n\nIn this example the accumulators C<$len> and C<$str> are implicitly initialized\nto C<0> and C<\"\">, respectively, which illustrates that the initialization value\nis operator-specific. In this regard it is also noted that not all compound\nassignment operators can sensibly initialize an undefined left-hand side\nvariable. The C</=> operator, for instance, will not arbitrarily select a value\nfor the dividend; instead, it will throw an exception.\n\nAlthough not strictly operators, methods can be used in the same fashion as\ncompound assignment operators:\n\n    my $a = 3.14;\n    $a .= round;      # $a = $a.round; OUTPUT: «3»\n\n=head1 Metaoperators\n\nMetaoperators can be parameterized with other operators or subroutines\nin the same way as functions can take other functions as parameters. To use a\nsubroutine as a parameter, prefix its name with an C<&>. Raku will\ngenerate the actual combined operator in the background, allowing the\nmechanism to be applied to user defined operators. To disambiguate\nchained metaoperators, enclose the inner operator in square brackets.\nThere are quite a few metaoperators with different semantics as\nexplained, next.\n\n=head2 X<Negated relational operators|Metaoperators,! (negation metaoperator)>\n\nThe result of a relational operator returning L<C<Bool>|/type/Bool> can be negated by\nprefixing with C<!>. To avoid visual confusion with the C<!!> operator,\nyou may not modify any operator already beginning with C<!>.\n\nThere are shortcuts for C<!==> and C<!eq>, namely C<!=> and C<ne>.\n\n    my $a = True;\n    say so $a != True;    # OUTPUT: «False␤»\n\n    my $release = Date.new(:2015year, :12month, :24day);\n    my $today = Date.today;\n    say so $release !before $today;     # OUTPUT: «False␤»\n\n=head2 X<Reversed operators|Metaoperators,R>\n\nX<|Metaoperators,reverse metaoperator>\nAny infix operator may be called with its two arguments reversed by\nprefixing with C<R>. Associativity of operands is reversed as well.\n\n    say 4 R/ 12;               # OUTPUT: «3␤»\n    say [R/] 2, 4, 16;         # OUTPUT: «2␤»\n    say [RZ~] <1 2 3>,<4 5 6>  # OUTPUT: «(41 52 63)␤»\n\n=head2 X«Hyper operators|Operators,<<»\n\nX«|Operators,>>»\nX<|Operators,«>\nX<|Operators,»>\nX<|Operators,»=«>\nX<|Operators,«=»>\nHyper operators include C<«> and C<»>, with their ASCII variants C«<<» and\nC«>>». They apply a given operator enclosed (or preceded or followed, in the\ncase of unary operators) by C<«> and/or C<»> to one or two lists, returning the\nresulting list, with the pointy part of C<«> or C<»> aimed at the shorter list.\nSingle elements are turned to a list, so they can be used too. If one of the\nlists is shorter than the other, the operator will cycle over the shorter list\nuntil all elements of the longer list are processed.\n\n    say (1, 2, 3) »*» 2;          # OUTPUT: «(2 4 6)␤»\n    say (1, 2, 3, 4) »~» <a b>;   # OUTPUT: «(1a 2b 3a 4b)␤»\n    say (1, 2, 3) »+« (4, 5, 6);  # OUTPUT: «(5 7 9)␤»\n    say (&sin, &cos, &sqrt)».(0.5);\n    # OUTPUT: «(0.479425538604203 0.877582561890373 0.707106781186548)␤»\n\nThe last example illustrates how postcircumfix operators (in this case .()) can\nalso be hypered.\n\n    my @a = <1 2 3>;\n    my @b = <4 5 6>;\n    say (@a,@b)»[1]; # OUTPUT: «(2 5)␤»\n\nIn this case, it's the L<postcircumfix[]|#circumfix_[_]> which is being hypered.\n\nAssignment metaoperators can be I<hyped>.\n\n    my @a = 1, 2, 3;\n    say @a »+=» 1;    # OUTPUT: «[2 3 4]␤»\n    my ($a, $b, $c);\n    (($a, $b), $c) «=» ((1, 2), 3);\n    say \"$a, $c\";       #  OUTPUT: «1, 3␤»\n\nHyper forms of unary operators have the pointy bit aimed at the operator and\nthe blunt end at the list to be operated on.\n\n    my @wisdom = True, False, True;\n    say !« @wisdom;     # OUTPUT: «[False True False]␤»\n\n    my @a = 1, 2, 3;\n    @a»++;\n    say @a;             # OUTPUT: «[2 3 4]␤»\n\nHyper operators are defined recursively on nested arrays.\n\n    say -« [[1, 2], 3]; # OUTPUT: «[[-1 -2] -3]␤»\n\nAlso, methods can be called in an out of order, concurrent fashion. The\nresulting list will be in order. Note that all hyper operators are candidates\nfor parallelism and will cause tears if the methods have side effects. The\noptimizer has full reign over hyper operators, which is the reason that they\ncannot be defined by the user.\n\n    class CarefulClass { method take-care {} }\n    my CarefulClass @objs;\n    my @results = @objs».take-care();\n\n    my @slops;        # May Contain Nuts\n    @slops».?this-method-may-not-exist();\n\nHyper operators can work with hashes. The pointy direction indicates if missing\nkeys are to be ignored in the resulting hash. The enclosed operator operates on\nall values that have keys in both hashes.\n\n=begin table\n%foo «+» %bar;       | intersection of keys\n\n%foo »+« %bar;       | union of keys\n\n%outer »+» %inner;   | only keys of %inner that exist in %outer will occur in the result\n=end table\n\n    my %outer = 1, 2, 3 Z=> <a b c>;\n    my %inner = 1, 2 Z=> <x z>;\n    say %outer «~» %inner;          # OUTPUT: «{\"1\" => \"ax\", \"2\" => \"bz\"}␤»\n\nHyper operators can take user-defined operators as their operator argument.\n\n    sub pretty-file-size (Int $size --> Str) {\n        # rounding version of infix:</>(Int, Int)\n        sub infix:<r/>(Int \\i1, Int \\i2) {\n            round(i1 / i2, 0.1)\n        }\n\n        # we build a vector of fractions of $size and zip that with the fitting prefix\n        for $size «[r/]« (2**60, 2**50, 2**40, 2**30, 2**20, 2**10)\n                  Z      <EB     PB     TB     GB     MB     KB> -> [\\v,\\suffix] {\n            # starting with the biggest suffix,\n            # we take the first that is 0.5 of that suffix or bigger\n            return v ~ ' ' ~ suffix if v > 0.4\n        }\n        # this be smaller or equal then 0.4 KB\n        return $size.Str;\n    }\n\n    for 60, 50, 40, 30, 20, 10 -> $test {\n        my &a = { (2 ** $test) * (1/4, 1/2, 1, 10, 100).pick * (1..10).pick };\n        print pretty-file-size(a.Int) xx 2, ' ';\n    }\n\n    # 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␤»\n\nWhether hyperoperators descend into child lists depends on the\nL<nodality|/language/typesystem#trait_is_nodal> of the inner operator of a\nchain. For the hyper method call operator (».), the nodality of the target\nmethod is significant.\n\n    say (<a b>, <c d e>)».elems;        # OUTPUT: «(2 3)␤»\n    say (<a b>, <c d e>)».&{ .elems };  # OUTPUT: «((1 1) (1 1 1))␤»\n\nYou can chain hyper operators to destructure a List of Lists.\n\n    my $neighbors = ((-1, 0), (0, -1), (0, 1), (1, 0));\n    my $p = (2, 3);\n    say $neighbors »>>+<<» ($p, *);   # OUTPUT: «((1 3) (2 2) (2 4) (3 3))␤»\n\nX<|Metaoperators,[] (reduction metaoperators)>X<|Metaoperators,[+] (reduction metaoperators)>\n=head2 Reduction metaoperators\n\nThe reduction metaoperator, C<[ ]>, reduces a list with the given infix\noperator. It gives the same result as the L<reduce|/routine/reduce> routine -\nsee there for details.\n\n    # These two are equivalent:\n    say [+] 1, 2, 3;                # OUTPUT: «6␤»\n    say reduce &infix:<+>, 1, 2, 3; # OUTPUT: «6␤»\n\nNo whitespace is allowed between the square brackets and the operator. To wrap a\nfunction instead of an operator, provide an additional layer of square brackets:\n\n    sub plus { $^a + $^b };\n    say [[&plus]] 1, 2, 3;          # OUTPUT: «6␤»\n\nThe argument list is iterated without flattening. This means that you can pass\na nested list to the reducing form of a list infix operator:\n\n    say [X~] (1, 2), <a b>;         # OUTPUT: «(1a 1b 2a 2b)␤»\n\nwhich is equivalent to C«1, 2 X~ <a b>».\n\nX<|Metaoperators,[\\] (triangular reduction metaoperators)>\nBy default, only the final result of the reduction is returned. Prefix the\nwrapped operator with a C<\\>, to return a lazy list of all intermediate values\ninstead. This is called a \"triangular reduce\". If the I<non-meta> part\ncontains a\nC<\\> already, quote it with C<[]> (e.g. C<[\\[\\x]]>).\n\n    my @n = [\\~] 1..*;\n    say @n[^5];         # OUTPUT: «(1 12 123 1234 12345)␤»\n\n=head2 X<Cross metaoperators|Metaoperators,X (cross metaoperator)>\n\nThe cross metaoperator, C<X>, will apply a given infix operator in order of\ncross product to all lists, such that the rightmost operand varies most\nquickly.\n\n    1..3 X~ <a b> # OUTPUT: «<1a, 1b, 2a, 2b, 3a, 3b>␤»\n\n=head2 X<Zip metaoperator|Metaoperators,Z (zip metaoperator)>\n\nThe zip metaoperator (not to be confused with L<infix:<Z>|#infix_Z>) will\napply a given infix operator to pairs taken one left, one right, from its\narguments. The resulting list is returned.\n\n    my @l = <a b c> Z~ 1, 2, 3;     # OUTPUT: «[a1 b2 c3]␤»\n\nIf one of the operands runs out of elements prematurely, the zip operator will\nstop. An infinite list can be used to repeat elements. A list with a final\nelement of C<*> will repeat its 2nd last element indefinitely.\n\n    my @l = <a b c d> Z~ ':' xx *;  # OUTPUT: «<a: b: c: d:>»\n       @l = <a b c d> Z~ 1, 2, *;   # OUTPUT: «<a1 b2 c2 d2>»\n\nIf an infix operator is not given, the C<,> (comma operator) will be used by\ndefault:\n\n    my @l = 1 Z 2;  # OUTPUT: «[(1 2)]»\n\nSee L<infix:<Z>|#infix_Z> for more about this usage.\n\n=head2 X<Sequential operators|Metaoperators,S>\n\nX<|Metaoperators,sequential metaoperator>\nThe sequential metaoperator, C<S>, will suppress any concurrency or reordering\ndone by the optimizer. Most simple infix operators are supported.\n\n    say so 1 S& 2 S& 3;  # OUTPUT: «True␤»\n\n=head2 Nesting of metaoperators\n\nTo avoid ambiguity when chaining metaoperators, use square brackets to help the\ncompiler understand you.\n\n    my @a = 1, 2, 3;\n    my @b = 5, 6, 7;\n    @a X[+=] @b;\n    say @a;         # OUTPUT: «[19 20 21]␤»\n\n=head1 Z<>Term precedence\n\n=head2 term C«< >»\n\nX<|Terms,quote-words>\nThe X<quote-words|Terms,qw> construct breaks up the contents on whitespace\nand returns a L<C<List>|/type/List> of the words. If a word looks like a number\nliteral or a L<C<Pair>|/type/Pair> literal, it's converted to the appropriate number.\n\n    say <a b c>[1];   # OUTPUT: «b␤»\n\n=head2 term C«( )»\n\nThe X<grouping operator|Terms,grouping operator>.\n\nAn empty group C<()> creates an L<empty list|/type/List#index-entry-()_(empty_list)>.\nParentheses around non-empty expressions simply structure the expression, but do\nnot have additional semantics.\n\nIn an argument list, putting parenthesis around an argument prevents it from\nbeing interpreted as a named argument.\n\n    multi p(:$a!) { say 'named'      }\n    multi p($a)   { say 'positional' }\n    p a => 1;           # OUTPUT: «named␤»\n    p (a => 1);         # OUTPUT: «positional␤»\n\n=head2 term C«{ }»\n\nX<|Terms,block constructor>\nX<|Terms,hash constructor>\nL<C<Block>|/type/Block> or L<C<Hash>|/type/Hash> constructor.\n\nIf the content is empty, or contains a single list that starts with a L<C<Pair>|/type/Pair>\nliteral or C<%>-sigiled variable, and the L«C<$_> variable|/syntax/$_» or\nplaceholder parameters are not used, the constructor returns a L<C<Hash>|/type/Hash>.\nOtherwise it constructs a L<C<Block>|/type/Block>.\n\nTo force construction of a L<C<Block>|/type/Block>, follow the opening brace with a semicolon.\nTo always ensure you end up with a L<C<Hash>|/type/Hash>, you can use C<%( )> coercer or\nL<hash|/routine/hash> routine instead:\n\n    {}.^name.say;        # OUTPUT: «Hash␤»\n    {;}.^name.say;       # OUTPUT: «Block␤»\n\n    {:$_}.^name.say;     # OUTPUT: «Block␤»\n    %(:$_).^name.say;    # OUTPUT: «Hash␤»\n    hash(:$_).^name.say; # OUTPUT: «Hash␤»\n\n=head2 circumfix C«[ ]»\n\nThe X<Array constructor|Circumfix operators,Array constructor> returns an itemized L<C<Array>|/type/Array> that does not flatten\nin list context. Check this:\n\n    say .raku for [3,2,[1,0]]; # OUTPUT: «3␤2␤$[1, 0]␤»\n\nThis array is itemized, in the sense that every element constitutes an item, as\nshown by the C<$> preceding the last element of the array, the\nL<(list) item contextualizer|/type/Any#index-entry-%24_%28item_contextualizer%29>.\n\n=head1 Terms\n\nTerms have their L<own extended documentation|/language/terms>.\n\n=head1 Method postfix precedence\n\n=head2 postcircumfix C«[ ]»\n\n    sub postcircumfix:<[ ]>(@container, **@index,\n                            :$k, :$v, :$kv, :$p, :$exists, :$delete)\n\nUniversal interface for positional access to zero or more elements of\n@container, a.k.a. \"X<array indexing operator|Postcircumfix operators,array indexing operator>\".\nX<|Postcircumfix operators,array subscript operator>\n\n    my @alphabet = 'a' .. 'z';\n    say @alphabet[0];                   # OUTPUT: «a␤»\n    say @alphabet[1];                   # OUTPUT: «b␤»\n    say @alphabet[*-1];                 # OUTPUT: «z␤»\n    say @alphabet[100]:exists;          # OUTPUT: «False␤»\n    say @alphabet[17, 0, 10, 20].join;  # OUTPUT: «raku␤»\n    say @alphabet[23 .. *].raku;        # OUTPUT: «(\"x\", \"y\", \"z\")␤»\n\n    @alphabet[1, 2] = \"B\", \"C\";\n    say @alphabet[0..3].raku;           # OUTPUT: «(\"a\", \"B\", \"C\", \"d\")␤»\n\nSee L<Subscripts|/language/subscripts>, for a more detailed explanation of this\noperator's behavior and for how to implement support for it in custom types.\n\n=head2 postcircumfix C«{ }»\n\n    sub postcircumfix:<{ }>(%container, **@key,\n                            :$k, :$v, :$kv, :$p, :$exists, :$delete)\n\nUniversal interface for associative access to zero or more elements of a\n%container, a.k.a. \"X<hash indexing operator|Postcircumfix operators,hash indexing operator>\".\nX<|Postcircumfix operators,hash subscript operator>\n\n    my %color = kiwi => \"green\", banana => \"yellow\", cherry => \"red\";\n    say %color{\"banana\"};                 # OUTPUT: «yellow␤»\n    say %color{\"cherry\", \"kiwi\"}.raku;    # OUTPUT: «(\"red\", \"green\")␤»\n    say %color{\"strawberry\"}:exists;      # OUTPUT: «False␤»\n\n    %color{\"banana\", \"lime\"} = \"yellowish\", \"green\";\n    %color{\"cherry\"}:delete; # note that value is always returned but removal only happens when delete is true.\n    say %color;             # OUTPUT: «banana => yellowish, kiwi => green, lime => green␤»\n\nSee L«C«postcircumfix < >»|/language/operators#postcircumfix_<_>» and\nL<C<postcircumfix « »>|/routine/« »#(Operators)_postcircumfix_«_»> for convenient\nshortcuts, and L<Subscripts|/language/subscripts> for a more detailed\nexplanation of this operator's behavior and how to implement support for it\nin custom types.\n\n=head2 postcircumfix C«<>»\n\nDecontainerization operator, which extracts the value from a container and makes\nit independent of the container type.\n\n=begin code :skip-test<need to mock JSON::Tiny>\nuse JSON::Tiny;\n\nmy $config = from-json('{ \"files\": 3, \"path\": \"/home/some-user/raku.rakudoc\" }');\nsay $config.raku;      # OUTPUT: «${:files(3), :path(\"/home/some-user/raku.rakudoc\")}␤»\nmy %config-hash = $config<>;\nsay %config-hash.raku; # OUTPUT: «{:files(3), :path(\"/home/some-user/raku.rakudoc\")}␤»\n=end code\n\nIt's a L<C<Hash>|/type/Hash> in both cases, and it can be used like that; however, in the\nfirst case it was in item context, and in the second case it has been extracted\nto its proper context.\n\n=head2 postcircumfix C«< >»\n\nShortcut for L<C<postcircumfix { }>|/routine/{ }#(Operators)_postcircumfix_{_}>\nthat quotes its argument using the same rules as the L«quote-words operator|#term_<_>»\nof the same name.\n\n    my %color = kiwi => \"green\", banana => \"yellow\", cherry => \"red\";\n    say %color<banana>;               # OUTPUT: «yellow␤»\n    say %color<cherry kiwi>.raku;     # OUTPUT: «(\"red\", \"green\")␤»\n    say %color<strawberry>:exists;    # OUTPUT: «False␤»\n\nTechnically, not a real operator; it's syntactic sugar that's turned into the\nC<{ }> postcircumfix operator at compile-time.\n\n=head2 postcircumfix C<« »>\n\nShortcut for L<C<postcircumfix { }>|/routine/{ }#(Operators)_postcircumfix_{_}>\nthat quotes its argument using the same rules as the\nL<interpolating quote-words operator|/language/quoting#Word_quoting_with_interpolation_and_quote_protection:_«_»>\nof the same name.\n\n    my %color = kiwi => \"green\", banana => \"yellow\", cherry => \"red\";\n    my $fruit = \"kiwi\";\n    say %color«cherry \"$fruit\"».raku;   # OUTPUT: «(\"red\", \"green\")␤»\n\nTechnically, not a real operator; it's syntactic sugar that's turned into the\nC<{ }> postcircumfix operator at compile-time.\n\n=head2 postcircumfix C«( )»\n\nThe X<call operator|Operators,call operator> treats the invocant as a L<C<Callable>|/type/Callable> and invokes it,\nusing the expression between the parentheses as arguments.\n\nNote that an identifier followed by a pair of parentheses is always parsed as a\nsubroutine call.\n\nIf you want your objects to respond to the call operator,\nimplement a L«C<method CALL-ME>|/routine/CALL-ME».\n\n=head2 methodop C«.»\n\nThe operator for calling one method, C<$invocant.method>.X<|Syntax,method call>\n\nTechnically, not a real operator; it's syntax special-cased in the compiler.\n\nX«|Syntax,methodop .&»\n=head2 methodop C«.&»\n\nThe operator to call a L<C<Callable>|/type/Callable>, such as a\nL<C<Block>|/type/Block>, a L<C<Method>|/type/Method>, or a L<C<Sub>|/type/Sub>\nwith method syntax. The invocant will be bound to the first positional\nargument (and thus dispatch will fail if the L<C<Callable>|/type/Callable> does not accept\nat least one positional argument).\n\nTechnically, not a real operator; it's syntax special-cased in the compiler.\n\n    my sub f($invocant){ \"The arg has a value of $invocant\" }\n    42.&f;\n    # OUTPUT: «The arg has a value of 42␤»\n\n    42.&(-> $invocant { \"The arg has a value of $invocant\" });\n    # OUTPUT: «The arg has a value of 42␤»\n\n=head2 methodop C«.=»\n\nA X<mutating method call|Syntax,mutating method call>. C<$invocant.=method> desugars to\nC<$invocant = $invocant.method>, similar to L<= (item assignment)|/routine/= (item assignment)> .\n\nTechnically, not a real operator; it's syntax special-cased in the compiler.\n\nX«|Syntax,methodop .^»\n=head2 methodop C«.^»\n\nA X<metamethod call|Language,metamethod call>. C<$invocant.^method> calls C<method> on C<$invocant>'s\nmetaclass. It desugars to C<$invocant.HOW.method($invocant, ...)>. See\nL<the metaobject protocol documentation|/language/mop> for more information.\n\nTechnically, not a real operator; it's syntax special-cased in the compiler.\nIt can be also applied, within classes, to access metamethods on self:\n\n=for code\nclass Foo {\n    method bar {\n        return self.^name\n    }\n};\nsay Foo.new.bar; # OUTPUT: «Foo␤»\n\n\nX«|Syntax,methodop .?»\n=head2 methodop C«.?»\n\nX<Safe call operator|Operators,Safe call operator>. C<$invocant.?method> calls method C<method> on\nC<$invocant> if it has a method of such name. Otherwise it returns\nL<C<Nil>|/type/Nil>.\n\nTechnically, not a real operator; it's syntax special-cased in the compiler.\n\nX«|Syntax,methodop .\"\"»\n=head2 methodop C«.\"\"»\n\nL<Runtime method resolution operator|/language/objects#index-entry-programmatic_use>. Uses\nL<double quotes|/language/quoting#Interpolation:_qq> for interpolation; the resulting string will\nbe used as a method name. Requires parentheses or C<\\> for the method call.\n\nTechnically, not a real operator; it's syntax special-cased in the compiler.\n\n=begin code\nclass Player {\n    method eat {\n        say 'Take the pineapple off the pizza!';\n    }\n\n    method drink {\n        say 'Pop the soda!';\n    }\n\n};\n\nmy $action = 'eat';\nPlayer.new.\"$action\"(); # OUTPUT: «Take the pineapple off the pizza!␤»\n=end code\n\nX«|Syntax,methodop .+»\n=head2 methodop C«.+»\n\nC<$foo.+meth> walks the L<MRO|/language/objects#index-entry-MRO> and calls all the methods called C<meth> and\nsubmethods called C<meth> if the type is the same as type of C<$foo>. Those\nmethods might be multis, in which case the matching candidate would be called.\n\nAfter that, a L<C<List>|/type/List> of the results are returned. If no such method\nwas found, it throws an L<C<X::Method::NotFound>|/type/X::Method::NotFound> exception.\n\n    class A {\n      method foo { say \"from A\"; }\n    }\n    class B is A {\n      multi method foo { say \"from B\"; }\n      multi method foo(Str) { say \"from B (Str)\"; }\n    }\n    class C is B is A {\n      multi method foo { say \"from C\"; }\n      multi method foo(Str) { say \"from C (Str)\"; }\n    }\n\n    say C.+foo; # OUTPUT: «from C␤from B␤from A␤(True True True)␤»\n\nX«|Syntax,methodop .*»\n=head2 methodop C«.*»\n\nC<$foo.*meth> walks the L<MRO|/language/objects#index-entry-MRO> and calls all the methods called C<meth> and\nsubmethods called C<meth> if the type is the same as type of C<$foo>. Those\nmethods might be multis, in which case the matching candidate would be called.\n\nAfter that, a L<C<List>|/type/List> of the results are returned. If no such method\nwas found, an empty L<C<List>|/type/List> is returned.\n\nTechnically, postfix C<.+> calls C<.*> at first. Read postfix C<.+> section to\nsee examples.\n\nX<|Syntax,methodop ».>X«|Syntax,methodop >>.»\n=head2 methodop C<».> / methodop C«>>.»\n\nThis is the X<hyper method call operator|Language,hyper method call operator>. Will call a method on all elements of\na L<C<List>|/type/List> out of order and return the list of return values in order.\n\n=for code\nmy @a = <a b c>;\nmy @b = @a».ord;                  # OUTPUT: «[97, 98, 99]␤»\n# The first parameter of a method is the invocant.\nsub foo(Str:D $c){ $c.ord * 2 };\n# So we can pretend to have a method call with a sub that got a good\n# first positional argument.\nsay @a».&foo;\n# Blocks have an implicit positional arguments that lands in $_. The latter can\n# be omitted for method calls.\nsay @a».&{ .ord};\n\nHyper method calls may appear to be the same as doing a L<map|/routine/map>\ncall, however along with being a hint to the compiler that it can parallelize\nthe call, the behavior is also affected by L<nodality of the\nmethod|/routine/is%20nodal> being invoked, depending on which either\nL<nodemap|/routine/nodemap> or L<deepmap|/routine/deepmap> semantics are used to\nperform the call.\n\nThe nodality is checked by looking up whether the L<C<Callable>|/type/Callable>\nprovides C<nodal> method. If the hyper is applied to a method, that\nL<C<Callable>|/type/Callable> is that method name, looked up on L<C<List>|/type/List>\ntype; if the hyper is applied to a routine (e.g. C<».&foo>), that routine\nfunctions as that L<C<Callable>|/type/Callable>. If the L<C<Callable>|/type/Callable>\nis determined to provide C<nodal> method, L<nodemap|/routine/nodemap> semantics\nare used to perform the hyper call, otherwise L<duckmap|/routine/duckmap>\nsemantics are used.\n\nTake care to avoid a\nL<common mistake|/language/traps#Using_»_and_map_interchangeably> of expecting\nside-effects to occur in order. The following C<say> is B<not>\nguaranteed to produce the output in order:\n\n    =begin code :preamble<my @a>\n    @a».say;  # WRONG! Could produce a␤b␤c␤ or c␤b␤a␤ or any other order\n    =end code\n\nX<|Syntax,.( )>X<|Syntax,.[ ]>X<|Syntax,.{ }>\n=head2 methodop C<.postfix> / C<.postcircumfix>\n\nIn most cases, a dot may be placed before a postfix or postcircumfix:\n\n    my @a;\n    @a[1, 2, 3];\n    @a.[1, 2, 3]; # Same\n\nThis can be useful for visual clarity or brevity. For example, if an object's\nattribute is a function, putting a pair of parentheses after the attribute name\nwill become part of the method call. So, either two pairs of parentheses must be\nused or a dot has to come before the parentheses to separate it from the method\ncall.\n\n    class Operation {\n        has $.symbol;\n        has &.function;\n    }\n    my $addition = Operation.new(:symbol<+>, :function{ $^a + $^b });\n    say $addition.function()(1, 2);   # OUTPUT: «3␤»\n    # OR\n    say $addition.function.(1, 2);    # OUTPUT: «3␤»\n\nIf the postfix is an identifier, however, it will be interpreted as a normal\nmethod call.\n\n=begin code\n1.i # No such method 'i' for invocant of type 'Int'\n=end code\n\nTechnically, not a real operator; it's syntax special-cased in the compiler.\n\nX<|Language,postfix operator call>\n=head2 methodop C«.:<prefix operator>»\n\nAn operator in prefix form can still be called like a method, that is, using the\nC<.> methodop notation, by preceding it by a colon. For example:\n\n    my $a = 1;\n    say ++$a;       # OUTPUT: «2␤»\n    say $a.:<++>;   # OUTPUT: «3␤»\n\nTechnically, not a real operator; it's syntax special-cased in the compiler,\nthat is why it's classified as a I<methodop>.\n\n=head2 methodop C«.::»\n\nA X<class-qualified method call|Language,class-qualified method call>, used to call a method as defined in a parent\nclass or role, even after it has been redefined in the child class.\n\n    class Bar {\n        method baz { 42 }\n    }\n    class Foo is Bar {\n        method baz { \"nope\" }\n    }\n    say Foo.Bar::baz;       # OUTPUT: «42␤»\n\n=head2 postfix C<,=>\n\nCreates an object that concatenates, in a class-dependent way, the contents of\nthe variable on the left-hand side and the expression on the right-hand side:\n\n    my %a = :11a, :22b;\n    %a ,= :33x;\n    say %a # OUTPUT: «{a => 11, b => 22, x => 33}␤»\n\n=head1 Autoincrement precedence\n\nX<|Operators,prefix increment operator>\n=head2 prefix X<C«++»|Prefix operators,prefix ++>\n\n    multi prefix:<++>($x is rw) is assoc<non>\n\nIncrements its argument by one and returns the updated value.\n\n    my $x = 3;\n    say ++$x;   # OUTPUT: «4␤»\n    say $x;     # OUTPUT: «4␤»\n\nIt works by calling the L<succ|/routine/succ> method (for I<successor>) on its\nargument, which gives custom types the freedom to implement their own increment\nsemantics.\n\nX<|Operators,prefix decrement operator>\n=head2 prefix X<C«--»|Prefix operators,prefix -->\n\n    multi prefix:<-->($x is rw) is assoc<non>\n\nDecrements its argument by one and returns the updated value.\n\n    my $x = 3;\n    say --$x;   # OUTPUT: «2␤»\n    say $x;     # OUTPUT: «2␤»\n\nIt works by calling the L<pred|/routine/pred> method (for I<predecessor>) on its argument,\nwhich gives custom types the freedom to implement their own decrement\nsemantics.\n\nX<|Operators,postfix increment operator>\n=head2 postfix X<C«++»|Postfix operators,postfix ++>\n\n    multi postfix:<++>($x is rw) is assoc<non>\n\nIncrements its argument by one and returns the original value.\n\n    my $x = 3;\n    say $x++;   # OUTPUT: «3␤»\n    say $x;     # OUTPUT: «4␤»\n\nIt works by calling the L<succ|/routine/succ> method (for I<successor>) on its argument,\nwhich gives custom types the freedom to implement their own increment\nsemantics; when undefined, it sets the value to 1 and returns it.\n\n    my $x;\n    $x++;\n    say $x;     # OUTPUT: «1␤»\n\nNote that this does not necessarily return its argument; e.g., for\nundefined values, it returns 0:\n\n    my $x;\n    say $x++;   # OUTPUT: «0␤»\n    say $x;     # OUTPUT: «1␤»\n\nIncrement on L<C<Str>|/type/Str> will increment the number part of a string and\nassign the resulting string to the container. An C<is rw> container is required.\n\n    my $filename = \"somefile-001.txt\";\n    say $filename++ for 1..3;\n    # OUTPUT: «somefile-001.txt␤somefile-002.txt␤somefile-003.txt␤»\n\nThis will act on any Unicode numeral:\n\n=for code\nmy $was٧ = \"ثمانية٧\";\n$was٧++;\nsay $was٧; # OUTPUT: «ثمانية٨␤»\n\nIncluding, since version 6.d, Thai numerals\n\n=for code\nmy $เลขไทย=\"๙๙\";\n$เลขไทย++;\nsay $เลขไทย; # OUTPUT: «๑๐๐␤»\n\nX<|Operators,postfix decrement operator>\n=head2 postfix X<C«--»|Postfix operators,postfix -->\n\n    multi postfix:<-->($x is rw) is assoc<non>\n\nDecrements its argument by one and returns the original value.\n\n    my $x = 3;\n    say $x--;   # OUTPUT: «3␤»\n    say $x;     # OUTPUT: «2␤»\n\nIt works by calling the L<pred|/routine/pred> method (for I<predecessor>) on its argument,\nwhich gives custom types the freedom to implement their own decrement\nsemantics.\n\nNote that this does not necessarily return its argument;e.g., for\nundefined values, it returns 0:\n\n    my $x;\n    say $x--;   # OUTPUT: «0␤»\n    say $x;     # OUTPUT: «-1␤»\n\nDecrement on L<C<Str>|/type/Str> will decrement the number part of a string and\nassign the resulting string to the container. An C<is rw> container is required.\nCrossing 0 is prohibited and throws L<C<X::AdHoc>|/type/X::AdHoc>.\n\n    my $filename = \"somefile-003.txt\";\n    say $filename-- for 1..3;\n    # OUTPUT: «somefile-003.txt␤somefile-002.txt␤somefile-001.txt␤»\n\n=head1 Exponentiation precedence\n\n=head2 infix C«**»\n\n    multi infix:<**>(Any, Any --> Numeric:D) is assoc<right>\n\nThe X<exponentiation operator|Operators,exponentiation operator> coerces both arguments to L<C<Numeric>|/type/Numeric>\nand calculates the left-hand-side raised to the power of the right-hand side.\n\nIf the right-hand side is a non-negative integer and the left-hand side\nis an arbitrary precision type (L<C<Int>|/type/Int>, L<C<FatRat>|/type/FatRat>), then the calculation\nis carried out without loss of precision.\n\nUnicode superscripts will behave in exactly the same way.\n\n    sub squared( Int $num ) { $num² };\n    say squared($_) for ^5; # OUTPUT: «0␤1␤4␤9␤16␤»\n\nIt also works for sequences of several Unicode superscript numbers:\n\n    sub twenty-second-power( Int $num ) { $num²² };\n    say twenty-second-power($_) for ^5; # OUTPUT: «0␤1␤4194304␤31381059609␤17592186044416␤»\n\n\n=head1 Symbolic unary precedence\n\n=head2 prefix C«?»\n\n    multi prefix:<?>(Mu --> Bool:D)\n\nX<Boolean context operator|Operators,Boolean context operator>.\n\nCoerces the argument to L<C<Bool>|/type/Bool> by calling the L<C<Bool>|/type/Bool> method on it.\nNote that this collapses L<C<Junction>|/type/Junction>s.\n\n=head2 prefix C«!»\n\n    multi prefix:<!>(Mu --> Bool:D)\n\nX<Negated Boolean context operator|Operators,Negated Boolean context operator>.\n\nCoerces the argument to L<C<Bool>|/type/Bool> by calling the L<C<Bool>|/type/Bool> method on it,\nand returns the negation of the result.\nNote that this collapses L<C<Junction>|/type/Junction>s.\n\n=head2 prefix C«//»\n\n    multi prefix:<//>(Any --> Bool:D)\n\nX<Boolean context operator|Operators,Boolean context operator>.\n\nAvailable as of 6.e language version (early implementation exists in Rakudo\ncompiler 2022.12+).\n\nCoerces the argument to L<C<Boolean>|/type/Bool> by calling the C<defined> method on it.\n\n=head2 prefix C«+»\n\n    multi prefix:<+>(Any --> Numeric:D)\n\nX<Numeric context operator|Operators,Numeric context operator>.\n\nCoerces the argument to L<C<Numeric>|/type/Numeric> by calling the C<Numeric> method on it.\n\n=head2 prefix C«-»\n\n    multi prefix:<->(Any --> Numeric:D)\n\nX<Negative numeric context operator|Prefix operators,Negative numeric context operator>.\n\nCoerces the argument to L<C<Numeric>|/type/Numeric> by calling the C<Numeric> method on it,\nand then negates the result.\n\n=head2 prefix C«~»\n\n    multi prefix:<~>(Any --> Str:D)\n\nX<String context operator|Prefix operators,String context operator>.\n\nCoerces the argument to L<C<Str>|/type/Str> by calling the L<Str|/type/List#method_Str> method on it.\n\n=head2 prefix C«|»\n\nFlattens objects of type L<C<Capture>|/type/Capture>, L<C<Pair>|/type/Pair>, L<C<List>|/type/List>, L<C<Map>|/type/Map> and\nL<C<Hash>|/type/Hash> into an argument list.\n\n    sub slurpee( |args ){\n        say args.raku\n    };\n    slurpee( <a b c d>, { e => 3 }, 'e' => 'f' => 33 )\n    # OUTPUT: «\\((\"a\", \"b\", \"c\", \"d\"), {:e(3)}, :e(:f(33)))␤»\n\nPlease see the L<signature literals page, specially the section on\nCaptures|/language/signatures#Capture_parameters> for more information on the\nsubject.\n\nOutside of argument lists, it returns a L<C<Slip>|/type/Slip>, which makes\nit flatten into the outer list. Inside L<argument\nlist|/language/list#Argument_list_(Capture)_context>\nL<C<Positional>s|/type/Positional> are turned into positional arguments\nand L<C<Associative>s|/type/Associative> are turned into named\narguments.\n\n=head2 prefix C«+^»\n\n    multi prefix:<+^>(Any --> Int:D)\n\nX<Integer bitwise negation operator|Prefix operators,Integer bitwise negation operator>: converts the number to binary using as\nmany bytes as needed by the number plus one; flips all bits and returns the\nresult assuming it is a\nL<two's complement|https://en.wikipedia.org/wiki/Two%27s_complement>\nrepresentation.\n\n=for code\nsay +^255; # OUTPUT: «-256␤»\n\nIn this case, 255 is 11111111 and would need a single byte. We use the\nrepresentation in bytes needed for this value plus one, converting it to 0000\n 0000 1111 1111. Bitwise negation turns it into 1111 1111 0000 0000 and this\n is the representation in two's complement of -256, which is returned.\n\n=for code\nsay +^1;        # OUTPUT: «-2␤»\nsay +^(-256);   # OUTPUT: «255␤»\n\nNegative numbers are assumed to be represented as two's complements, and thus\n circle back to the original number.\n\n=head2 prefix C«~^»\n\nCoerces the argument to a non-variable-encoding string buffer type (e.g. C<buf8>, C<buf16>, C<buf32>)\nand then flips each bit in that buffer.\n\nPlease note that this has not yet been implemented.\n\n=head2 prefix C«?^»\n\n    multi prefix:<?^>(Mu --> Bool:D)\n\nX<Boolean bitwise negation operator|Prefix operators,Boolean bitwise negation operator>: Coerces the argument to L<C<Bool>|/type/Bool>\nand then does a bit flip, which makes it the same as C«prefix:<!>».\n\n=head2 prefix C«^»\n\n    multi prefix:<^>(Any --> Range:D)\n\nI<upto> operator.X<|Prefix operators,upto operator>\n\nCoerces the argument to L<C<Numeric>|/type/Numeric>, and generates a range from 0 up to (but\nexcluding) the argument.\n\n    say ^5;         # OUTPUT: «0..^5␤»\n    for ^5 { }      # 5 iterations\n\n=head1 Dotty infix precedence\n\nThese operators are like their Method Postfix counterparts, but require\nsurrounding whitespace (before and/or after) to distinguish them.\n\n=head2 infix C«.=»\n\nCalls the right-side method on the value in the left-side container,\nreplacing the resulting value in the left-side container.\n\nIn most cases, this behaves identically to postfix L<C<.=>|#methodop_.=>,\nbut the precedence is lower:\n\n=for code\nmy $a = -5;\nsay ++$a.=abs; # with postfix mutator; equivalent to ++($a.=abs)\n# OUTPUT: «6␤»\n=for code :skip-test<illustrates error>\nmy $a = -5;\nsay ++$a .= abs; # with infix mutator; evaluated as -4 .= abs\n# OUTPUT: «Cannot modify an immutable Int (-4)␤\n#           in block <unit> at <tmp> line 1␤␤»\n\n=head2 infix C«.»\n\nCalls the following method (whose name must be alphabetic) on the left-side\ninvocant.\n\nNote that the infix form of the operator has a slightly lower precedence\nthan postfix C<.meth>.\n\n    say -5.abs;      # like: -(5.abs)\n    # OUTPUT: «-5␤»\n    say -5 . abs;    # like: (-5) . abs\n    # OUTPUT: «5␤»\n    say -5 .abs;     # following whitespace is optional\n    # OUTPUT: «5␤»\n\n=head1 Multiplicative precedence\n\n=head2 infix C«*»\n\n    multi infix:<*>(Any, Any --> Numeric:D)\n\nX<Multiplication operator|Infix operators,Multiplication operator>.\n\nCoerces both arguments to L<C<Numeric>|/type/Numeric> and multiplies them. The result\nis of the wider type. See L<C<Numeric>|/type/Numeric> for details.\n\n=head2 infix C«/»\n\n    multi infix:</>(Any, Any --> Numeric:D)\n\nX<Division operator|Infix operators,Division operator>.\n\nCoerces both argument to L<C<Numeric>|/type/Numeric> and divides the left through the right\nnumber. Division of L<C<Int>|/type/Int> values returns L<C<Rat>|/type/Rat>, otherwise the \"wider type\"\nrule described in L<C<Numeric>|/type/Numeric> holds.\n\nNote there is also L<C<div>|#infix_div> for L<C<Int>|/type/Int> division.\n\n=head2 infix C«div»\n\n    multi infix:<div>(Int:D, Int:D --> Int:D)\n\nX<Integer division operator|Infix operators,Integer division operator>. Rounds down.\n\nNote there is also L<C</>|#infix_/> for L<C<Numeric>|/type/Numeric> division.\n\n=head2 infix C«%»\n\n    multi infix:<%>($x, $y --> Numeric:D)\n\nX<Modulo operator|Infix operators,Modulo operator>. Coerces to L<C<Numeric>|/type/Numeric> first.\n\nGenerally the following identity holds:\n\n    my ($x, $y) = 1,2;\n    $x % $y == $x - floor($x / $y) * $y\n\nNote there is also L<C<mod>|#infix_%> for L<C<Int>|/type/Int> modulo.\n\n=head2 infix C«%%»\n\n    multi infix:<%%>($a, $b --> Bool:D)\n\nX<Divisibility operator|Infix operators,Divisibility operator>. Returns C<True> if C<$a % $b == 0>.\n\n=head2 infix C«mod»\n\n    multi infix:<mod>(Int:D $a, Int:D $b --> Int:D)\n\nX<Integer modulo operator|Infix operators,Integer modulo operator>. Returns the remainder of an integer modulo operation.\n\nNote there is also L<C<%>|#infix_%> for L<C<Numeric>|/type/Numeric> modulo.\n\n=head2 infix C«+&»\n\n    multi infix:<+&>($a, $b --> Int:D)\n\nNumeric bitwise I<AND> operator. Coerces both arguments to L<C<Int>|/type/Int> and does a bitwise\nI<AND> operation assuming two's complement.X<|Infix operators,Numeric bitwise AND operator>\n\n=head2 infix C«+<»\n\n    multi infix:«+<»($a, $b --> Int:D)\n\nInteger bit shift to the left.X<|Infix operators,integer left bit shift operator>\n\n=head2 infix C«+>»\n\n    multi infix:«+>»($a, $b --> Int:D)\n\nInteger bit shift to the right.X<|Infix operators,integer right bit shift operator>\n\n=head2 infix C«~&»\n\nCoerces each argument to a non-variable-encoding string buffer type (e.g. C<buf8>, C<buf16>, C<buf32>)\nand then performs a numeric bitwise AND on corresponding integers of the two buffers, padding the\nshorter buffer with zeroes.\n\n=head2 infix C«~<»\n\nCoerces the left argument to a non-variable-encoding string buffer type (e.g. C<buf8>, C<buf16>, C<buf32>)\nand then performs a numeric bitwise left shift on the bits of the buffer.\n\nPlease note that this has not yet been implemented.\n\n=head2 infix C«~>»\n\nCoerces the left argument to a non-variable-encoding string buffer type (e.g. C<buf8>, C<buf16>, C<buf32>)\nand then performs a numeric bitwise right shift on the bits of the buffer.\n\nPlease note that this has not yet been implemented.\n\n=head2 infix C«?&»\n\n    multi infix:<?&>(Mu $x = Bool::True)\n    multi infix:<?&>(Mu \\a, Mu \\b)\n\nX<Boolean logical AND operator|Infix operators,Boolean logical AND operator>. Coerces the argument(s) to L<C<Bool>|/type/Bool>\nand performs logical AND on it(them): it will return True if and only if both\narguments are True. On a single argument it behaves as identity, returning\nthe coerced value.\n\n=head2 infix C«gcd»\n\n    multi infix:<gcd>($a, $b --> Int:D)\n\nCoerces both arguments to L<C<Int>|/type/Int> and returns the greatest common divisor.X<|Infix operators,greatest common divisor operator>\nIf one of its arguments is 0, the other is returned (when both arguments are 0, the operator returns 0).\n\n=head2 infix C«lcm»\n\n    multi infix:<lcm>($a, $b --> Int:D)\n\nCoerces both arguments to L<C<Int>|/type/Int> and returns the least common multiple; that is,\nthe smallest integer that is evenly divisible by both arguments.X<|Infix operators,least common multiple operator>\n\n=head1 Additive precedence\n\n=head2 infix C«+»\n\n    multi infix:<+>($a, $b --> Numeric:D)\n\nX<Addition operator|Infix operators,Addition operator>: Coerces both arguments to L<C<Numeric>|/type/Numeric> and\nadds them. From version 6.d it works also on L<C<Duration>|/type/Duration>,\nL<C<DateTime>|/type/DateTime> and L<C<Real>|/type/Real> types.\n\n=head2 infix C«-»\n\n    multi infix:<->($a, $b --> Numeric:D)\n\nX<Subtraction operator|Infix operators,Subtraction operator>: Coerces both arguments to L<C<Numeric>|/type/Numeric>\nand subtracts the second from the\nfirst. From version 6.d it works also on L<C<Duration>|/type/Duration>,\nL<C<DateTime>|/type/DateTime> and L<C<Real>|/type/Real> types.\n\n=head2 infix C«+|»\n\n    multi infix:<+|>($a, $b --> Int:D)\n\nX<Integer bitwise OR operator|Infix operators,Integer bitwise OR operator>: Coerces both arguments to L<C<Int>|/type/Int> and\ndoes a bitwise I<OR> (inclusive OR) operation.\n\n=head2 infix C«+^»\n\n    multi infix:<+^>($a, $b --> Int:D)\n\nX<Integer bitwise XOR operator|Infix operators,Integer bitwise XOR operator>: Coerces both arguments to L<C<Int>|/type/Int> and\ndoes a bitwise I<XOR> (exclusive OR) operation.\n\n=for code\nsay (0b00001101 +^ 0b00001001).base(2); # OUTPUT: «100␤»\n\n=head2 infix C«~|»\n\nCoerces each argument to a non-variable-encoding string buffer type (e.g. C<buf8>, C<buf16>, C<buf32>)\nand then performs a numeric bitwise OR on corresponding integers of the two buffers, padding the\nshorter buffer with zeroes.\n\n=head2 infix C«~^»\n\nCoerces each argument to a non-variable-encoding string buffer type (e.g. C<buf8>, C<buf16>, C<buf32>)\nand then performs a numeric bitwise XOR on corresponding integers of the two buffers, padding the\nshorter buffer with zeroes.\n\n=head2 infix C«?^»\n\n    multi infix:<?^>(Mu $x = Bool::False)\n    multi infix:<?^>(Mu \\a, Mu \\b)\n\nX<Boolean logical XOR operator|Infix operators,Boolean logical XOR operator>. Coerces the argument(s) to L<C<Bool>|/type/Bool>\nand performs logical XOR on it(them): it will return True if and only if just one of\nthe argument is True. On a single argument it behaves as identity, returning\nthe coerced value.\n\n=head2 infix C«?|»\n\n    multi infix:<?|>(Mu $x = Bool::False)\n    multi infix:<?|>(Mu \\a, Mu \\b)\n\nX<Boolean logical OR operator|Infix operators,Boolean logical OR operator>. Coerces the argument(s) to L<C<Bool>|/type/Bool>\nand performs logical OR (inclusive OR) on it(them): it will return True if at least one of\nthe argument is True. On a single argument it behaves as identity, returning\nthe coerced value.\n\n=head1 Replication precedence\n\n=head2 infix C«x»\n\n    sub infix:<x>($a, $b --> Str:D)\n\nX<String repetition operator|Infix operators,String repetition operator>.\n\nRepeats the string C<$a> C<$b> times, if necessary coercing C<$a> to L«C<Str>|/type/Str»\nand C<$b> to L«C<Int>|/type/Int». Returns an empty string if C«$b <= 0». An exception\nL<C<X::Numeric::CannotConvert>|/type/X::Numeric::CannotConvert> will be thrown if C<$b> is C<-Inf> or C<NaN>.\n\n    say 'ab' x 3;           # OUTPUT: «ababab␤»\n    say 42 x 3;             # OUTPUT: «424242␤»\n\n    my $a = 'a'.IO;\n    my $b = 3.5;\n    say $a x $b;            # OUTPUT: «aaa␤»\n\n=head2 infix C«xx»\n\n    multi infix:<xx>()\n    multi infix:<xx>(Mu \\x)\n    multi infix:<xx>(&x, Num:D() $n)\n    multi infix:<xx>(&x, Whatever)\n    multi infix:<xx>(&x, Bool:D $b)\n    multi infix:<xx>(&x, Int:D $n)\n    multi infix:<xx>(Mu \\x, Num:D() $n)\n    multi infix:<xx>(Mu \\x, Whatever)\n    multi infix:<xx>(Mu \\x, Bool:D $b)\n    multi infix:<xx>(Mu \\x, Int:D $n)\n\nX<List repetition operator|Infix operators,List repetition operator>\n\nIn general, it returns a Sequence of C<$a> repeated and evaluated C<$b> times\n(C<$b> is coerced to L<C<Int>|/type/Int>). If C«$b <= 0», the empty list is\nreturned. It will return an error with no operand, and return the operand itself\nwith a single operand. An exception L<C<X::Numeric::CannotConvert>|/type/X::Numeric::CannotConvert> will be\nthrown if C<$b> is C<-Inf> or C<NaN>.\n\nThe left-hand side is evaluated for each repetition, so\n\n    say [1, 2] xx 5;\n    # OUTPUT: «([1 2] [1 2] [1 2] [1 2] [1 2])␤»\n\nreturns five distinct arrays (but with the same content each time), and\n\n    rand xx 3\n\nreturns three pseudo random numbers that are determined independently.\n\nThe right-hand side can be C<*>, in which case a lazy, infinite list is\nreturned. If it's a L<C<Bool>|/type/Bool>, a L<C<Seq>|/type/Seq> with a single element is returned if it's\nC<True>.\n\n=head1 Concatenation\n\nSame as the rest of the infix operators, these can be combined with\nmetaoperators such as\nL<assignment|#Assignment_operators>, for instance.\n\n=head2 infix C«~»\n\n    multi infix:<~>(Any,   Any)\n    multi infix:<~>(Str:D, Str:D)\n    multi infix:<~>(Buf:D, Buf:D)\n    multi infix:<~>(Blob:D $a, Blob:D $b)\n    multi infix:<~>(Junction:D \\a, Junction:D \\b)\n\nThis is the X<string concatenation operator|Infix operators,string concatenation operator>, which coerces both\narguments to L<C<Str>|/type/Str> and concatenates them. If both arguments\nare L<C<Buf>|/type/Buf>, a combined buffer is returned.\n\n=for code\nsay 'ab' ~ 'c';     # OUTPUT: «abc␤»\nmy $bob = Blob.new([1,2,3]);\nmy $bao = Blob.new([3,4,5]);\nsay $bao ~ $bob;     # OUTPUT: «Blob:0x<03 04 05 01 02 03>␤»\n\nThe arity-1 version of this operator will be called when the hyper version of\nthe operator is used on an array or list with a single element, or simply an\nelement\n\n=for code\nsay [~] Blob.new([3,4,5]);     # OUTPUT: «Blob:0x<03 04 05>␤»\nsay [~] 1|2;                   # OUTPUT: «any(1, 2)␤»\n\n=head2 infix C<o>, infix C«∘»\n\n    multi infix:<o>()\n    multi infix:<o>(&f)\n    multi infix:<o>(&f, &g --> Block:D)\n\nX<|Infix operators,o>\nThe X<function composition operator|Infix operators,function composition operator> C«infix:<∘>» or C«infix:<o>»\ncombines two functions, so that the left function is called with the\nreturn value of the right function. If the L«C<.count>|/routine/count»\nof the left function is greater than 1, the return value of the right\nfunction will be L<slipped|/type/Slip> into the left function.\n\nBoth C<.count> and C<.arity> of the right-hand side will be maintained, as\nwell as the C<.of> of the left-hand side.\n\n=begin code\nsub f($p){ say 'f'; $p / 2 }\nsub g($p){ say 'g'; $p * 2 }\n\nmy &composed = &f ∘ &g;\nsay composed 2; # OUTPUT: «g␤f␤2␤»\n# equivalent to:\nsay 2.&g.&f;\n# or to:\nsay f g 2;\nsay &composed.arity; #  OUTPUT: «1␤»\nsay &composed.count; #  OUTPUT: «1␤»\nsay &composed.of;    #  OUTPUT: «(Mu)␤»\n=end code\n\n=begin code\nsub f($a, $b, $c) { [~] $c, $b, $a }\nsub g($str){ $str.comb }\nmy &composed = &f ∘ &g;\nsay composed 'abc'; # OUTPUT: «cba␤»\n# equivalent to:\nsay f |g 'abc';\n=end code\n\nThe single-arg candidate returns the given argument as is. The zero-arg candidate\nreturns an identity routine that simply returns its argument.\n\n    my &composed = [∘] &uc;\n    say composed 'foo'; # OUTPUT: «FOO␤»\n\n    my &composed = [∘];\n    say composed 'foo'; # OUTPUT: «foo␤»\n\n=head1 Junctive AND (all) precedence\n\n=head2 infix C«&»\n\n    multi infix:<&>($a, $b --> Junction:D) is assoc<list>\n\nX<All junction operator|Infix operators,All junction operator>.\n\nCreates an I<all> L<C<Junction>|/type/Junction> from its arguments. See L<C<Junction>|/type/Junction> for more\ndetails.\n\n=head2 infix C«(&)», infix C«∩»\n\n    multi infix:<(&)>(**@p)\n\nX<Intersection operator|Infix operators,Intersection operator>.\n\n'&' as in left-hand side arguments 'and' right-hand side arguments.\nReturns the B<intersection> of all of its arguments. This creates a new\nL<C<Set>|/type/Set> that contains only the elements common to all of the\narguments if none of the arguments are a L<C<Bag>|/type/Bag>,\nL<C<BagHash>|/type/BagHash>, L<C<Mix>|/type/Mix> or L<C<MixHash>|/type/MixHash>.\n\n    =begin code\n    say <a b c> (&) <b c d>; # OUTPUT: «Set(b c)␤»\n    say <a b c d> ∩ <b c d e> ∩ <c d e f>; # OUTPUT: «Set(c d)␤»\n    =end code\n\nIf any of the arguments are L<C<Baggy>|/type/Baggy> or L<C<Mixy>|/type/Mixy>,\nthe result is a new L<C<Bag>|/type/Bag> (or L<C<Mix>|/type/Mix>) containing the common elements, each\nweighted by the largest I<common> weight (which is the minimum of the weights\nof that element over all arguments).\n\n    =begin code\n    say <a a b c a> (&) bag(<a a b c c>); # OUTPUT: «Bag(a(2) b c)␤»\n    =end code\n\n=head2 infix C«(.)», infix C«⊍»\n\n    multi infix:<(.)>(**@p)\n\nX<Baggy multiplication operator|Infix operators,Baggy multiplication operator>.\n\nReturns the Baggy B<multiplication> of its arguments, i.e., a L<C<Bag>|/type/Bag>\nthat contains each element of the arguments with the weights of the element\nacross the arguments multiplied together to get the new weight.  Returns a\nL<C<Mix>|/type/Mix> if any of the arguments is a L<C<Mixy>|/type/Mixy>.\n\n    =begin code\n    say <a b c> (.) <a b c d>; # OUTPUT: «Bag(a b c)␤»\n                               # Since 1 * 0 == 0, in the case of 'd'\n    say <a a b c a d> ⊍ bag(<a a b c c>); # OUTPUT: «Bag(a(6) b c(2))␤»\n    =end code\n\n=head1 Junctive OR (any) precedence\n\n=head2 infix C«|»\n\n    multi infix:<|>($a, $b --> Junction:D) is assoc<list>\n\nX<|Infix operators,Any junction operator>\nCreates an I<any> L<C<Junction>|/type/Junction> from its arguments.\n\n    my $three-letters = /<[a b c]>/ | /<[i j k]>/ | /<[x y z]>/;\n    say $three-letters.raku; # OUTPUT: «any(/<[a b c]>/, /<[i j k]>/, /<[x y z]>/)␤»\n    say 'b' ~~ $three-letters; # OUTPUT: «True␤»\n\nThis first creates an C<any> L<C<Junction>|/type/Junction> of three regular expressions\n(every one of them matching any of 3 letters), and then uses\nsmartmatching to check whether the letter C<b> matches any of them,\nresulting in a positive match. See also L<C<Junction>|/type/Junction> for more details.\n\n=head2 infix C«(|)», infix C«∪»\n\n    multi infix:<(|)>(**@p)\n\nX<Union operator|Infix operators,Union operator>.\n\n'|' as in left-hand side arguments 'or' right-hand side arguments.\n\nReturns the B<union> of all of its arguments. This creates a new\nL<C<Set>|/type/Set> that contains all the elements its arguments contain if none\nof the arguments are a L<C<Bag>|/type/Bag>, L<C<BagHash>|/type/BagHash>,\nL<C<Mix>|/type/Mix> or L<C<MixHash>|/type/MixHash>.\n\n    =begin code\n    say <a b d> ∪ bag(<a a b c>); # OUTPUT: «Bag(a(2) b c d)␤»\n    =end code\n\nIf any of the arguments are L<C<Baggy>|/type/Baggy> or L<C<Mixy>|/type/Mixy>,\nthe result is a new L<C<Bag>|/type/Bag> (or L<C<Mix>|/type/Mix>) containing all the elements, each\nweighted by the I<highest> weight that appeared for that element.\n\n    =begin code\n    say <a b d> ∪ bag(<a a b c>); # OUTPUT: «Bag(a(2) b c d)␤»\n    =end code\n\n=head2 infix C«(+)», infix C«⊎»\n\n    multi infix:<(+)>(**@p)\n\nX<Baggy addition operator|Infix operators,Baggy addition operator>.\n\nReturns the Baggy B<addition> of its arguments.  This creates a new\nL<C<Bag>|/type/Bag> from each element of the arguments with the weights of the\nelement added together to get the new weight, if none of the arguments are a\nL<C<Mix>|/type/Mix> or L<C<MixHash>|/type/MixHash>.\n\n    =begin code\n    say <a a b c a d> (+) <a a b c c>; # OUTPUT: «Bag(a(5) b(2) c(3) d)␤»\n    =end code\n\nIf any of the arguments is a L<C<Mixy>|/type/Mixy>, the result is a new L<C<Mix>|/type/Mix>.\n\n    =begin code\n    say <a b c> (+) (a => 2.5, b => 3.14).Mix; # OUTPUT: «Mix(a(3.5) b(4.14) c)␤»\n    =end code\n\n=head2 infix C«(-)», infix C«∖»\n\n    multi infix:<(-)>(**@p)\n\nX<Set difference operator|Infix operators,Set difference operator>.\n\nReturns the B<set difference> of all its arguments.  This creates a new\nL<C<Set>|/type/Set> that contains all the elements the first argument has but the\nrest of the arguments don't, i.e., of all the elements of the first argument,\nminus the elements from the other arguments.  But only if none of the arguments\nare a L<C<Bag>|/type/Bag>, L<C<BagHash>|/type/BagHash>, L<C<Mix>|/type/Mix> or L<C<MixHash>|/type/MixHash>.\n\n    =begin code\n    say <a a b c a d> (-) <a a b c c>; # OUTPUT: «Set(d)␤»\n    say <a b c d e> (-) <a b c> (-) <a b d>; # OUTPUT: «Set(e)␤»\n    =end code\n\nIf any of the arguments are L<C<Baggy>|/type/Baggy> or L<C<Mixy>|/type/Mixy>,\nthe result is a new L<C<Bag>|/type/Bag> (or L<C<Mix>|/type/Mix>) containing all the elements remaining\nafter the first argument with its weight subtracted by the weight of that\nelement in each of the other arguments.\n\n    =begin code\n    say <a a b c a d> (-) bag(<a b c c>); # OUTPUT: «Bag(a(2) d)␤»\n    say <a a b c a d>  ∖  mix(<a b c c>); # OUTPUT: «Mix(a(2) c(-1) d)␤»\n    =end code\n\n=head2 infix C«^»\n\n    multi infix:<^>($a, $b --> Junction:D) is assoc<list>\n\nX<One junction operator|Infix operators,One junction operator>.\n\nCreates a I<one> L<C<Junction>|/type/Junction> from its arguments. See L<C<Junction>|/type/Junction> for more\ndetails.\n\n=head2 infix C«(^)», infix C«⊖»\n\n    multi infix:<(^)>($a, $b)\n    multi infix:<(^)>(**@p)\n\nX<Symmetric set difference operator|Infix operators,Symmetric set difference operator>.\n\nReturns the B<symmetric set difference> of all its arguments. This creates a\nnew L<C<Set>|/type/Set> made up of all the elements that C<$a> has but C<$b>\ndoesn't and all the elements C<$b> has but C<$a> doesn't if none of the\narguments are a L<C<Bag>|/type/Bag>, L<C<BagHash>|/type/BagHash>, L<C<Mix>|/type/Mix>\nor L<C<MixHash>|/type/MixHash>. Equivalent to C<($a ∖ $b) ∪ ($b ∖ $a)>.\n\n    =begin code\n    say <a b> (^) <b c>; # OUTPUT: «Set(a c)␤»\n    =end code\n\nIf any of the arguments are L<C<Baggy>|/type/Baggy> or L<C<Mixy>|/type/Mixy>,\nthe result is a new L<C<Bag>|/type/Bag> (or L<C<Mix>|/type/Mix>).\n\n    =begin code\n    say <a b> ⊖ bag(<b c>); # OUTPUT: «Bag(a c)␤»\n    =end code\n\n=head1 Named unary precedence\n\n=head2 prefix C«temp»\n\n    sub prefix:<temp>(Mu $a is rw)\n\n\"temporizes\" the variable passed as the argument. The variable begins\nwith the same value as it had in the outer scope, but can be assigned\nnew values in this scope. Upon exiting the scope, the variable will be\nrestored to its original value.\n\n    my $a = \"three\";\n    say $a; # OUTPUT: «three␤»\n    {\n        temp $a;\n        say $a; # OUTPUT: «three␤»\n        $a = \"four\";\n        say $a; # OUTPUT: «four␤»\n    }\n    say $a; # OUTPUT: «three␤»\n\nYou can also assign immediately as part of the call to temp:\n\n=begin code :preamble<my $a>\ntemp $a = \"five\";\n=end code\n\nBe warned the C<temp> effects get removed once the block is left. If\nyou were to access the value from, say, within a L<C<Promise>|/type/Promise> after\nthe C<temp> was undone, you'd get the original value, not the C<temp> one:\n\n    =begin code\n    my $v = \"original\";\n    {\n        temp $v = \"new one\";\n        start {\n            say \"[PROMISE] Value before block is left: `$v`\";\n            sleep 1;\n            say \"[PROMISE] Block was left while we slept; value is now `$v`\";\n        }\n        sleep ½;\n        say \"About to leave the block; value is `$v`\";\n    }\n    say \"Left the block; value is now `$v`\";\n    sleep 2;\n\n    # OUTPUT:\n    # [PROMISE] Value before block is left: `new one`\n    # About to leave the block; value is `new one`\n    # Left the block; value is now `original`\n    # [PROMISE] Block was left while we slept; value is now `original`\n    =end code\n\n\n=head2 prefix C«let»\n\n    sub prefix:<let>(Mu $a is rw)\n\nRefers to a variable in an outer scope whose value will be restored if the block\nexits unsuccessfully, implying that the block returned a defined object.\n\n=begin code\nmy $name = \"Jane Doe\";\n\n{\n    let $name = prompt(\"Say your name \");\n    die if !$name;\n    CATCH {\n        default { say \"No name entered\" }\n    }\n    say \"We have $name\";\n}\n\nsay \"We got $name\";\n=end code\n\nThis code provides a default name for C<$name>. If the user exits from the\nprompt or simply does not provide a valid input for C<$name>; C<let> will\nrestore the default value provided at the top. If user input is valid, it will\nkeep that.\n\n=comment this is duplicated in variables.pod\n\n=head1 Nonchaining binary precedence\n\n=head2 infix C«does»\n\n    sub infix:<does>(Mu $obj, Mu $role) is assoc<non>\n\nMixes C<$role> into C<$obj> at runtime. Requires C<$obj> to be mutable.\n\nSimilar to L<but|/routine/but> operator, if C<$role> supplies exactly one\nattribute, an initializer can be passed in parentheses.\n\nSimilar to L<but|/routine/but> operator, the C<$role> can instead be an instantiated object,\nin which case, the operator will create a role for you automatically.\nThe role will contain a single method named the same as C<$obj.^name>\nand that returns C<$obj>:\n\n    my $o = class { method Str { \"original\" } }.new;\n    put $o;            # OUTPUT: «original␤»\n    $o does \"modded\";\n    put $o;            # OUTPUT: «modded␤»\n\nIf methods of the same name are present already, the last mixed in role takes\nprecedence.\n\n=head2 infix C«but»\n\n    multi infix:<but>(Mu $obj1, Mu   $role) is assoc<non>\n    multi infix:<but>(Mu $obj1, Mu:D $obj2) is assoc<non>\n\nCreates a copy of C<$obj> with C<$role> mixed in. Since C<$obj> is not\nmodified, C<but> can be used to create immutable values with mixins.\n\nIf C<$role> supplies exactly one attribute, an initializer can be passed in\nparentheses:\n\n    =begin code\n    role Answerable {\n        has $.answer;\n    }\n    my $ultimate-question = 'Life, the Universe and Everything' but Answerable(42);\n    say $ultimate-question;         # OUTPUT: «Life, the Universe and Everything␤»\n    say $ultimate-question.^name;   # OUTPUT: «Str+{Answerable}␤»\n    say $ultimate-question.answer;  # OUTPUT: «42␤»\n    =end code\n\nInstead of a role, you can provide an instantiated object. In this case,\nthe operator will create a role for you automatically. The role will contain\na single method named the same as C<$obj.^name> and that returns C<$obj>:\n\n    =begin code\n    my $forty-two = 42 but 'forty two';\n    say $forty-two+33;    # OUTPUT: «75␤»\n    say $forty-two.^name; # OUTPUT: «Int+{<anon|1>}␤»\n    say $forty-two.Str;   # OUTPUT: «forty two␤»\n    =end code\n\nCalling C<^name> shows that the variable is an L<C<Int>|/type/Int> with an anonymous object\nmixed in. However, that object is of type L<C<Str>|/type/Str>, so the variable, through the\nmixin, is endowed with a method with that name, which is what we use in the last\nsentence.\n\nWe can also mixin classes, even created on the fly.\n\n    =begin code\n    my $s = 12 but class Warbles { method hi { 'hello' } }.new;\n    say $s.Warbles.hi;    # OUTPUT: «hello␤»\n    say $s + 42;          # OUTPUT: «54␤»\n    =end code\n\nTo access the mixed-in class, as above, we use the class name as is shown in the\nsecond sentence. If methods of the same name are present already, the last mixed\nin role takes precedence. A list of methods can be provided in parentheses\nseparated by comma. In this case conflicts will be reported at runtime.\n\n=head2 infix C«cmp»\n\n    multi infix:<cmp>(Any,       Any)\n    multi infix:<cmp>(Real:D,    Real:D)\n    multi infix:<cmp>(Str:D,     Str:D)\n    multi infix:<cmp>(Version:D, Version:D)\n\nX<Generic, \"smart\" three-way comparator|Infix operators,Generic three-way comparator>.\n\nCompares strings with string semantics, numbers\nwith number semantics, L<C<Pair>|/type/Pair> objects first by key and then by value etc.\n\nif C<$a eqv $b>, then C<$a cmp $b> always returns C<Order::Same>.\n\n    say (a => 3) cmp (a => 4);   # OUTPUT: «Less␤»\n    say 4        cmp 4.0;        # OUTPUT: «Same␤»\n    say 'b'      cmp 'a';        # OUTPUT: «More␤»\n\nStrings are compared codepoint by codepoint; if leading codepoints are the\nsame, the result of comparing the first differing codepoint is returned or\nthe longer string if their lengths differ.\n\n    \"abcd\" cmp \"abcde\";    # OUTPUT: «Less␤»\n    \"abcd \" cmp \"abcde\";   # OUTPUT: «Less␤»\n    'A' cmp 'Ẳ';           # OUTPUT: «Less␤»\n\n=head2 infix C<coll>\n\n    multi infix:<coll>(Str:D \\a, Str:D \\b --> Order:D)\n    multi infix:<coll>(Cool:D \\a, Cool:D \\b --> Order:D)\n    multi infix:<coll>(Pair:D \\a, Pair:D \\b --> Order:D)\n\nC<coll> is a sorting operator that takes pairs of L<C<Str>|/type/Str>s, L<C<Cool>|/type/Cool>s or L<C<Pair>|/type/Pair>s\nand returns an L<C<Order>|/type/Order> that uses the C<$*COLLATION> order. The default behavior\ndisregards diacritic marks and capitalization, for instance.\n\n    say \"b\" cmp \"à\";  # OUTPUT: «Less␤»\n    say \"b\" coll \"à\"; # OUTPUT: «More␤»\n\nIn the first case, lexicographic or codepoint order is taken into account. In\nthe second, which uses C<coll>, the diacritic is not considered and sorting\nhappens according to intuitive order.\n\nB<NOTE:> These are not yet implemented in the JVM.\n\n=head2 infix C«unicmp»\n\n    multi infix:<unicmp>(Str:D \\a, Str:D \\b --> Order:D)\n    multi infix:<unicmp>(Pair:D \\a, Pair:D \\b --> Order:D)\n    multi infix:<coll>(Pair:D \\a, Pair:D \\b --> Order:D)\n\nUnlike the cmp operator which sorts according to codepoint, C<unicmp> and\nC<coll> sort according to how most users would expect, that is, disregarding\naspects of the particular character like capitalization.\n\n    say 'a' unicmp 'Z'; # OUTPUT: «Less␤»\n    say 'a' coll 'Z';   # OUTPUT: «Less␤»\n    say 'a' cmp 'Z';    # OUTPUT: «More␤»\n\nThe main difference between C<coll> and C<unicmp> is that the behavior of the\nformer can be changed by the\nL<C<$*COLLATION>|/language/variables#index-entry-%24*COLLATION> dynamic\nvariable.\n\nB<NOTE:> These are not yet implemented in the JVM.\n\n=head2 infix C«leg»\n\n    multi infix:<leg>(Any,   Any)\n    multi infix:<leg>(Str:D, Str:D)\n\nX<String three-way comparator|Infix operators,String three-way comparator>. Short for I<less, equal or greater?>.\n\nCoerces both arguments to L<C<Str>|/type/Str> and then does a lexicographic\ncomparison.\n\n    say 'a' leg 'b';       # OUTPUT: «Less␤»\n    say 'a' leg 'a';       # OUTPUT: «Same␤»\n    say 'b' leg 'a';       # OUTPUT: «More␤»\n\n=head2 infix C«<=>»\n\n    multi infix:«<=>»($a, $b --> Order:D) is assoc<non>\n\nX<Numeric three-way comparator|Infix operators,Numeric three-way comparator>.X<|Infix operators,spaceship operator>\n\nCoerces both arguments to L<C<Real>|/type/Real> and then does a numeric comparison.\n\n=head2 infix C«..»\n\n    multi infix:<..>($a, $b --> Range:D) is assoc<non>\n\nX<Range operator|Infix operators,Range operator>\n\nConstructs a L<C<Range>|/type/Range> from the arguments.\n\n=head2 infix C«..^»\n\n    multi infix:<..^>($a, $b --> Range:D) is assoc<non>\n\nX<Right-open range operator|Infix operators,Right-open range operator>.\n\nConstructs a L<C<Range>|/type/Range> from the arguments, excluding the end point.\n\n=head2 infix C«^..»\n\n    multi infix:<^..>($a, $b --> Range:D) is assoc<non>\n\nX<Left-open range operator|Infix operators,Left-open range operator>.\n\nConstructs a L<C<Range>|/type/Range> from the arguments, excluding the start point.\n\n=head2 infix C«^..^»\n\n    multi infix:<^..^>($a, $b --> Range:D) is assoc<non>\n\nX<Open range operator|Infix operators,Open range operator>.\n\nConstructs a L<C<Range>|/type/Range> from the arguments, excluding both start and end point.\n\n=head1 Chaining binary precedence\n\n=head2 infix C«==», infix C«⩵»\n\n    multi infix:<==>(Any, Any)\n    multi infix:<==>(Int:D, Int:D)\n    multi infix:<==>(Num:D, Num:D)\n    multi infix:<==>(Rational:D, Rational:D)\n    multi infix:<==>(Real:D, Real:D)\n    multi infix:<==>(Complex:D, Complex:D)\n    multi infix:<==>(Numeric:D, Numeric:D)\n\nX<Numeric equality operator|Infix operators,Numeric equality operator>.\n\nCoerces both arguments to L<C<Numeric>|/type/Numeric> (if necessary); returns C<True>\nif they are equal.\n\nSince Rakudo release 2021.07, ⩵ is an alias for this operator.\n\n=head2 infix C«!=», infix C«≠»\n\n    sub infix:<!=>(Mu, Mu --> Bool:D)\n\nX<Numeric inequality operator|Infix operators,Numeric inequality operator>.\n\nCoerces both arguments to L<C<Numeric>|/type/Numeric> (if necessary); returns C<True> if they are\ndistinct.\n\nIs equivalent to C«!==».\n\n=head2 infix C«<»\n\n    multi infix:«<»(Int:D, Int:D)\n    multi infix:«<»(Num:D, Num:D)\n    multi infix:«<»(Real:D, Real:D)\n\nX<Numeric less than operator|Infix operators,Numeric less than operator>.\n\nCoerces both arguments to L<C<Real>|/type/Real> (if necessary); returns C<True> if the first argument\nis smaller than the second.\n\n=head2 infix C«<=», infix C«≤»\n\n    multi infix:«<=»(Int:D, Int:D)\n    multi infix:«<=»(Num:D, Num:D)\n    multi infix:«<=»(Real:D, Real:D)\n\nX<Numeric less than or equal to operator|Infix operators,Numeric less than or equal to operator>.\n\nCoerces both arguments to L<C<Real>|/type/Real> (if necessary); returns C<True> if the first argument\nis smaller than or equal to the second.\n\n=head2 infix C«>»\n\n    multi infix:«>»(Int:D, Int:D)\n    multi infix:«>»(Num:D, Num:D)\n    multi infix:«>»(Real:D, Real:D)\n\nX<Numeric greater than operator|Infix operators,Numeric greater than operator>.\n\nCoerces both arguments to L<C<Real>|/type/Real> (if necessary); returns C<True> if the first argument\nis larger than the second.\n\n=head2 infix C«>=», infix C«≥»\n\n    multi infix:«>=»(Int:D, Int:D)\n    multi infix:«>=»(Num:D, Num:D)\n    multi infix:«>=»(Real:D, Real:D)\n\nX<Numeric greater than or equal to operator|Infix operators,Numeric greater than or equal to operator>.\n\nCoerces both arguments to L<C<Real>|/type/Real> (if necessary); returns C<True> if\nthe first argument is larger than or equal to the second.\n\n=head2 infix C«eq»\n\n    multi infix:<eq>(Any,   Any)\n    multi infix:<eq>(Str:D, Str:D)\n\nX<String equality operator|Infix operators,String equality operator>.\n\nCoerces both arguments to L<C<Str>|/type/Str> (if necessary); returns C<True> if both\nare equal.\n\nMnemonic: I<equal>\n\n=head2 infix C«ne»\n\n    multi infix:<ne>(Mu,    Mu)\n    multi infix:<ne>(Str:D, Str:D)\n\nX<String inequality operator|Infix operators,String inequality operator>.\n\nCoerces both arguments to L<C<Str>|/type/Str> (if necessary); returns C<False> if both\nare equal.\n\nMnemonic: I<not equal>\n\n=head2 infix C«gt»\n\n    multi infix:<gt>(Mu,    Mu)\n    multi infix:<gt>(Str:D, Str:D)\n\nX<String greater than operator|Infix operators,String greater than operator>.\n\nCoerces both arguments to L<C<Str>|/type/Str> (if necessary); returns C<True> if\nthe first is larger than the second, as determined by lexicographic\ncomparison.\n\nMnemonic: I<greater than>\n\n=head2 infix C«ge»\n\n    multi infix:<ge>(Mu,    Mu)\n    multi infix:<ge>(Str:D, Str:D)\n\nX<String greater than or equal to operator|Infix operators,String greater than or equal to operator>.\n\nCoerces both arguments to L<C<Str>|/type/Str> (if necessary); returns C<True> if\nthe first is equal to or larger than the second, as determined by lexicographic\ncomparison.\n\nMnemonic: I<greater or equal>\n\n=head2 infix C«lt»\n\n    multi infix:<lt>(Mu,    Mu)\n    multi infix:<lt>(Str:D, Str:D)\n\nX<String less than operator|Infix operators,String less than operator>.\n\nCoerces both arguments to L<C<Str>|/type/Str> (if necessary); returns C<True> if\nthe first is smaller than the second, as determined by lexicographic\ncomparison.\n\nMnemonic: I<less than>\n\n=head2 infix C«le»\n\n    multi infix:<le>(Mu,    Mu)\n    multi infix:<le>(Str:D, Str:D)\n\nX<String less than or equal to operator|Infix operators,String less than or equal to operator>.\n\nCoerces both arguments to L<C<Str>|/type/Str> (if necessary); returns C<True> if\nthe first is equal to or smaller than the second, as determined by lexicographic\ncomparison.\n\nMnemonic: I<less or equal>\n\n=head2 infix C«before»\n\n    multi infix:<before>(Any,       Any)\n    multi infix:<before>(Real:D,    Real:D)\n    multi infix:<before>(Str:D,     Str:D)\n    multi infix:<before>(Version:D, Version:D)\n\nGeneric ordering, uses the same semantics as L<cmp|/routine/cmp>.\nReturns C<True> if the first argument is smaller than the second.\n\n=head2 infix C«after»\n\n    multi infix:<after>(Any,       Any)\n    multi infix:<after>(Real:D,    Real:D)\n    multi infix:<after>(Str:D,     Str:D)\n    multi infix:<after>(Version:D, Version:D)\n\nGeneric ordering, uses the same semantics as L<cmp|/routine/cmp>.\nReturns C<True> if the first argument is larger than the second.\n\n=head2 infix C«eqv»\n\n    sub infix:<eqv>(Any, Any)\n\nThis could be called an X<equivalence operator|Infix operators,equivalenceoperator>,\nand it will return C<True> if the two arguments are structurally the same,\ni.e. from the same type and (recursively) contain equivalent values.\nA user-defined class may want to provide its own implementation of this\noperator: see L<C<routine eqv>|/routine/eqv> for some examples from core.\n\n    say [1, 2, 3] eqv [1, 2, 3];    # OUTPUT: «True␤»\n    say Any eqv Any;                # OUTPUT: «True␤»\n    say 1 eqv 2;                    # OUTPUT: «False␤»\n    say 1 eqv 1.0;                  # OUTPUT: «False␤»\n\nLazy L«C<Iterable>|/type/Iterable»s cannot be compared, as\nthey're assumed to be infinite. However, the operator will do its best and\nreturn C<False> if the two lazy L<C<Iterable>|/type/Iterable>s are of different types or\nif only one L<C<Iterable>|/type/Iterable> is lazy.\n\n    say (1…∞) eqv (1…∞).List; # Both lazy, but different types;   OUTPUT: «False␤»\n    say (1…∞) eqv (1…3);      # Same types, but only one is lazy; OUTPUT: «False␤»\n    (try say (1…∞) eqv (1…∞)) # Both lazy and of the same type. Cannot compare; throws.\n        orelse say $!.^name;  # OUTPUT: «X::Cannot::Lazy␤»\n\nIn some cases, it will be able to compare lazy operands, as long as they can\nbe iterated\n\n=for code\nmy $a = lazy ^2;\nmy $b = $a;\n$a.cache;\nsay $a eqv $b; # OUTPUT: «True␤»\n\nWhen cached, the two lazy L<C<Seq>|/type/Seq>s can be iterated over, and thus compared.\n\nThe default C<eqv> operator even works with arbitrary objects. E.g., C<eqv>\nwill consider two instances of the same object as being structurally\nequivalent:\n\n    my class A {\n        has $.a;\n    }\n    say A.new(a => 5) eqv A.new(a => 5);  # OUTPUT: «True␤»\n\nAlthough the above example works as intended, the C<eqv> code might fall back\nto a slower code path in order to do its job. One way to avoid this is to\nimplement an appropriate infix C<eqv> operator:\n\n    my class A {\n        has $.a;\n    }\n    multi infix:<eqv>(A $l, A $r) { $l.a eqv $r.a }\n    say A.new(a => 5) eqv A.new(a => 5);            # OUTPUT: «True␤»\n\n\nNote that C<eqv> does not work recursively on every kind of container type,\ne.g. L<C<Set>|/type/Set>:\n\n    my class A {\n        has $.a;\n    }\n    say Set(A.new(a => 5)) eqv Set(A.new(a => 5));  # OUTPUT: «False␤»\n\nEven though the contents of the two sets are C<eqv>, the sets are not.\nThe reason is that C<eqv> delegates the equality check to the L<C<Set>|/type/Set> object\nwhich relies on element-wise C«===» comparison. Turning the class C<A>\ninto a value type (L<C<ValueObjAt>|/type/ValueObjAt>) by giving it a C<WHICH> method\nproduces the expected behavior:\n\n    my class A {\n        has $.a;\n        method WHICH {\n            ValueObjAt.new: \"A|$!a.WHICH()\"\n        }\n    }\n    say Set(A.new(a => 5)) eqv Set(A.new(a => 5));  # OUTPUT: «True␤»\n\nYou can call a single-argument version of the operator by using its full\nname; it will always return true.\n\n=for code\nsay infix:<eqv>(33);    # OUTPUT: «True␤»\nsay infix:<eqv>(False); # OUTPUT: «True␤»\n\n\n=head2 infix C«===»\n\n    sub infix:<===>(Any, Any)\n\nThe ASCII equivalent of L<C<⩶>|#infix_⩶>, the value identity operator.\n\nBefore Rakudo release 2021.07, the ASCII variant was the I<only> variant.\n\n=head2 infix C«⩶»\n\n    sub infix:<⩶>(Any, Any)\n\n⩶\nX<Value identity operator|Infix operators,Value identity operator>. Returns C<True> if both arguments are the same\nobject, disregarding any containerization.\n\n    my class A { };\n    my $a = A.new;\n    say $a ⩶ $a;              # OUTPUT: «True␤»\n    say A.new ⩶ A.new;        # OUTPUT: «False␤»\n    say A ⩶ A;                # OUTPUT: «True␤»\n\nFor value types, C<⩶> behaves like C<eqv>:\n\n    say 'a' ⩶ 'a';            # OUTPUT: «True␤»\n    say 'a' ⩶ 'b';            # OUTPUT: «False␤»\n\n    my $b = 'a';\n    say $b ⩶ 'a';             # OUTPUT: «True␤»\n\n    # different types\n    say 1 ⩶ 1.0;              # OUTPUT: «False␤»\n\nC<⩶> uses the L<WHICH|/routine/WHICH> method to obtain the object identity.\n\nIf you want to create a class that should act as a value type, then that\nclass must create an instance method C<WHICH>, that should return a\nL<C<ValueObjAt>|/type/ValueObjAt> object that won't change for the lifetime of\nthe object.\n\nThe ASCII equivalent of this operator is L<C<===>|#infix_===>.\n\n=head2 infix C«=:=»\n\n    multi infix:<=:=>(Mu \\a, Mu \\b)\n\nX<Container identity operator|Infix operators,Container identity operator>. Returns C<True> if both arguments are bound to the same\ncontainer. If it returns C<True>, it generally means that modifying one will\nalso modify the other.\n\n    my ($a, $b) = (1, 3);\n    say $a =:= $b;      # OUTPUT: «False␤»\n    $b = 2;\n    say $a;             # OUTPUT: «1␤»\n    $b := $a;\n    say $a =:= $b;      # OUTPUT: «True␤»\n    $a = 5;\n    say $b;             # OUTPUT: «5␤»\n\nThe single argument version, called as a routine, will always return True:\n\n=for code\nsay infix:<=:=>(42);    # OUTPUT: «True␤»\nsay infix:<=:=>(False); # OUTPUT: «True␤»\n\nX<|Infix operators,smartmatch operator>\n=head2 infix C«~~»\n\nThe smartmatch operator calls the L<C<.ACCEPTS()>|/routine/ACCEPTS> method on\nits right-hand side, with its left-hand side as the argument. The semantics\nare left to the type of the right-hand side operand.\n\nHere is a partial list of some of the built-in smartmatching functionality. For\nfull details, see L<ACCEPTS|/routine/ACCEPTS> documentation\nfor the type on the right-hand side of the operator.\n\n=begin table\n\n    Right-hand side     Comparison semantics\n    ===============     ====================\n    Mu:U                type check\n    Str                 string equality\n    Numeric             numeric equality\n    Regex               regex match\n    Callable            Boolean result of invocation\n    Set/Bag             equal element values\n    Any:D               object identity\n\n=end table\n\n=head2 infix C<=~=>\n\nThe ASCII equivalent of L<C<≅>|#infix_≅>, the approximately-equal operator.\n\n=head2 infix C<≅>\n\n    multi infix:<≅>(Any, Any)\n    multi infix:<≅>(Int:D, Int:D)\n    multi infix:<≅>(Num:D, Num:D)\n    multi infix:<≅>(Rational:D, Rational:D)\n    multi infix:<≅>(Real:D, Real:D)\n    multi infix:<≅>(Complex:D, Complex:D)\n    multi infix:<≅>(Numeric:D, Numeric:D)\n\nThe approximately-equal operator X<C<≅>|Infix operators,≅>\ncalculates the L<relative percentage difference|https://en.wikipedia.org/wiki/Relative_change>\nbetween the left-hand and right-hand\nsides and returns C<True> if the difference is less than C<$*TOLERANCE>\n(which defaults to C<1e-15>). However, if either side is zero then it checks that\nthe absolute difference between the sides is less than C<$*TOLERANCE>.\n\nThe ASCII equivalent of this operator is L<C<=~=>|#infix_=~=>.\n\nNote that this operator is not arithmetically symmetrical (doesn't do ± Δ):\n\n    my $x = 1;\n    say ($x + $*TOLERANCE) ≅ $x;   # OUTPUT: «False␤»\n    say ($x - $*TOLERANCE) ≅ $x;   # OUTPUT: «True␤»\n\nYou can change C<$*TOLERANCE> lexically:\n\n    {\n        my $*TOLERANCE = .1;\n        say 11 ≅ 10;        # OUTPUT: «True␤»\n    }\n\nNote that setting C<$*TOLERANCE = 0> will cause all comparisons to fail.\n\n    {\n        my $*TOLERANCE = 0;\n        say 1 ≅ 1;        # OUTPUT: «False␤»\n    }\n\n=head2 infix C<(elem)>, infix C<∈>\n\n    multi infix:<(elem)>($a,$b --> Bool:D)\n\nX<Membership operator|Infix operators,Membership operator (elem)>.\n\nReturns C<True> if C<$a> is an B<element> of C<$b>.\n\n=begin code\nsay 2 (elem) (1, 2, 3); # OUTPUT: «True␤»\nsay 4 ∈ (1, 2, 3);      # OUTPUT: «False␤»\n=end code\n\nSince release 2020.05, ∊ is an alias for this operator.\n\n=head2 infix C«∉»\n\n    multi infix:<∉>($a,$b --> Bool:D)\n\nX<Non-membership operator|Infix operators,Non-membership operator (elem)>.\n\nReturns C<True> if C<$a> is B<not> an B<element> of C<$b>.  Equivalent to\nC<!(elem)>.\n\n=begin code\nsay 4 ∉ (1, 2, 3);       # OUTPUT: «True␤»\nsay 2 !(elem) (1, 2, 3); # OUTPUT: «False␤»\n=end code\n\n=head2 infix C«(==)», infix C«≡»\n\n    multi infix:<(==)>($a,$b --> Bool:D)\n\nX<Set equality operator|Infix operators,Set equality operator>.\n\nReturns C<True> if C<$a> and C<$b> are B<identical>.\n\n    =begin code\n    say (1, 2, 3) (==) (1, 3, 2); # OUTPUT: «True␤»\n    say (1, 2, 3) ≡ (1, 2, 4); # OUTPUT: «False␤»\n    =end code\n\n=head2 infix C«≢»\n\n    multi infix:<≢>($a,$b --> Bool:D)\n\nX<Set inequality operator|Infix operators,Set inequality operator>.\n\nReturns C<True> if C<$a> and C<$b> are B<not identical>.  Equivalent to\nC<!(==)>.\n\n    =begin code\n    say (1, 2, 3) ≢ (1, 2, 4); # OUTPUT: «True␤»\n    say (1, 2, 3) ≢ (1, 3, 2); # OUTPUT: «False␤»\n    =end code\n\n=head2 infix C<(cont)>, infix C<∋>\n\n    multi infix:<(cont)>($a,$b --> Bool:D)\n\nX<Membership operator|Infix operators,Membership operator (cont)>.\n\nReturns C<True> if C<$a> B<contains> C<$b> as an element.\n\n=begin code\nsay (1,2,3) (cont) 2; # OUTPUT: «True␤»\nsay (1, 2, 3) ∋ 4;    # OUTPUT: «False␤»\n=end code\n\nSince release 2020.05, ∍ is an alias for this operator.\n\n=head2 infix C«∌»\n\n    multi infix:<∌>($a,$b --> Bool:D)\n\nX<Non-membership operator|Infix operators,Non-membership operator (cont)>.\n\nReturns C<True> if C<$a> does B<not> B<contain> C<$b>.  Equivalent to\nC<!(cont)>.\n\n    =begin code\n    say (1,2,3) ∌ 4;       # OUTPUT: «True␤»\n    say (1,2,3) !(cont) 2; # OUTPUT: «False␤»\n    =end code\n\n=head2 infix C«(<)», infix C«⊂»\n\n    multi infix:«(<)»($a,$b --> Bool:D)\n\nX<Subset of operator|Infix operators,Subset of operator>.\n\nReturns C<True> if C<$a> is a B<strict subset> of C<$b>, i.e., that all the\nelements of C<$a> are elements of C<$b> but C<$a> is a smaller set than C<$b>.\n\n    =begin code\n    say (1,2,3) (<) (2,3,1); # OUTPUT: «False␤»\n    say (2,3) (<) (2,3,1);   # OUTPUT: «True␤»\n    say 4 ⊂ (1,2,3);         # OUTPUT: «False␤»\n    =end code\n\n=head2 infix C«⊄»\n\n    multi infix:<⊄>($a,$b --> Bool:D)\n\nX<Not a subset of operator|Infix operators,Not a subset of operator>.\n\nReturns C<True> if C<$a> is B<not> a C<strict subset> of C<$b>.  Equivalent to\nC«!(<)».\n\n    =begin code\n    say (1,2,3) ⊄ (2,3,1); # OUTPUT: «True␤»\n    say (2,3) ⊄ (2,3,1);   # OUTPUT: «False␤»\n    say 4 !(<) (1,2,3);    # OUTPUT: «True␤»\n    =end code\n\n=head2 infix C«(<=)», infix C«⊆»\n\n    multi infix:«(<=)»($a,$b --> Bool:D)\n\nX<Subset of or equal to operator|Infix operators,Subset of or equal to operator>.\n\nReturns C<True> if C<$a> is a B<subset> of C<$b>, i.e., that all the\nelements of C<$a> are elements of C<$b> but C<$a> is a smaller or equal sized\nset than C<$b>.\n\n    =begin code\n    say (1,2,3) (<=) (2,3,1); # OUTPUT: «True␤»\n    say (2,3) (<=) (2,3,1);   # OUTPUT: «True␤»\n    say 4 ⊆ (1,2,3);          # OUTPUT: «False␤»\n    =end code\n\n=head2 infix C«⊈»\n\n    multi infix:<⊈>($a,$b --> Bool:D)\n\nX<Not a subset of nor equal to operator|Infix operators,Not a subset of nor equal to operator>.\n\nReturns C<True> if C<$a> is B<not> a C<subset> of C<$b>.  Equivalent to\nC«!(<=)».\n\n    =begin code\n    say (1,2,3) ⊈ (2,3,1); # OUTPUT: «False␤»\n    say (2,3) ⊈ (2,3,1);   # OUTPUT: «False␤»\n    say 4 !(<=) (1,2,3);   # OUTPUT: «True␤»\n    =end code\n\n=head2 infix C«(>)», infix C«⊃»\n\n    multi infix:«(>)»($a,$b --> Bool:D)\n\nX<Superset of operator|Infix operators,Superset of operator>.\n\nReturns C<True> if C<$a> is a B<strict superset> of C<$b>, i.e., that all the\nelements of C<$b> are elements of C<$a> but C<$a> is a larger set than C<$b>.\n\n    =begin code\n    say (1,2,3) (>) (2,3,1); # OUTPUT: «False␤»\n    say (1,2,3) (>) (2,3);   # OUTPUT: «True␤»\n    say 4 ⊃ (1,2,3);         # OUTPUT: «False␤»\n    =end code\n\n=head2 infix C«⊅»\n\n    multi infix:<⊅>($a,$b --> Bool:D)\n\nX<Not a superset of operator|Infix operators,Not a superset of operator>.\n\nReturns C<True> if C<$a> is B<not> a C<strict superset> of C<$b>.  Equivalent to\nC«!(>)».\n\n    =begin code\n    say (1,2,3) ⊅ (2,3,1); # OUTPUT: «True␤»\n    say (1,2,3) ⊅ (2,3);   # OUTPUT: «False␤»\n    say 4 !(>) (1,2,3);    # OUTPUT: «True␤»\n    =end code\n\n=head2 infix C«(>=)», infix C«⊇»\n\n    multi infix:«(>=)»($a,$b --> Bool:D)\n\nX<Superset of or equal to operator|Infix operators,Superset of or equal to operator>.\n\nReturns C<True> if C<$a> is a B<superset> of C<$b>, i.e., that all the\nelements of C<$b> are elements of C<$a> but C<$a> is a larger or equal sized\nset than C<$b>.\n\n    =begin code\n    say (1,2,3) (>=) (2,3,1); # OUTPUT: «True␤»\n    say (1,2,3) (>=) (2,3);   # OUTPUT: «True␤»\n    say 4 ⊇ (1,2,3);          # OUTPUT: «False␤»\n    =end code\n\n=head2 infix C«⊉»\n\n    multi infix:<⊉>($a,$b --> Bool:D)\n\nX<Not a superset of nor equal to operator|Infix operators,Not a superset of nor equal to operator>.\n\nReturns C<True> if C<$a> is B<not> a C<superset> of C<$b>.  Equivalent to\nC«!(>=)».\n\n    =begin code\n    say (1,2,3) ⊉ (2,3,1); # OUTPUT: «False␤»\n    say (1,2,3) ⊉ (2,3);   # OUTPUT: «False␤»\n    say 4 !(>=) (1,2,3);   # OUTPUT: «True␤»\n    =end code\n\n=head2 infix C«≼», infix C«≽»\n\nDeprecated.  These were removed in v6.d, please use ⊆ and ⊇ operators instead.\n\n=head1 Tight AND precedence\n\n=head2 infix C«&&»\n\nReturns the first argument that evaluates to C<False> in Boolean context,\notherwise returns the last argument.\n\nNote that this short-circuits, i.e. if one of the arguments evaluates to a\nfalse value, the arguments to the right are never evaluated.\n\n    sub a { 1 }\n    sub b { 0 }\n    sub c { die \"never called\" };\n    say a() && b() && c();      # OUTPUT: «0␤»\n\n=head1 Tight OR precedence\n\n=head2 infix C«||»\n\nReturns the first argument that evaluates to C<True> in Boolean context,\notherwise returns the last argument.\n\nNote that this short-circuits; i.e., if one of the arguments evaluates to a\ntrue value, the remaining arguments are not evaluated.\n\n    sub a { 0 }\n    sub b { 1 }\n    sub c { die \"never called\" };\n    say a() || b() || c();      # OUTPUT: «1␤»\n\n=head2 infix C«^^»\n\nX<Short-circuit exclusive-or|Infix operators,Short-circuit exclusive-or>. Returns the true argument if there\nis one (and only one). Returns the last argument if all arguments are false.\nReturns L<C<Nil>|/type/Nil> when more than one argument is true.\n\nThis operator short-circuits in the sense that it does not evaluate\nany arguments after a 2nd true result.\n\n    say 0 ^^ 42;                             # OUTPUT: «42␤»\n    say '' ^^ 0;                             # OUTPUT: «0␤»\n    say 0 ^^ 42 ^^ 1 ^^ die \"never called\";  # OUTPUT: «Nil␤»\n\nNote that the semantics of this operator may not be what you assume: infix C«^^»\nflips to the first true value it finds and then flips to Nil I<forever> after the\nsecond, no matter how many more true values there are. (In other words, it has\n\"find the one true value\" semantics, not \"Boolean parity\" semantics.)\n\n=head2 infix C«//»\n\nThe X<defined-or operator|Infix operators,defined-or operator> or X<infix //|Infix operators,//> returns the first defined operand, or else the last\noperand. Short-circuits.\n\n    say Any // 0 // 42;         # OUTPUT: «0␤»\n\n=head2 infix C«min»\n\nReturns the smallest of the arguments, as determined by L<cmp|/routine/cmp> semantics.\n\n    my $foo = 42;\n    $foo min= 0   # read as: $foo decreases to 0\n\nB<Note:> Before 2022.06, in the cases of ties L<C<&min>|/type/Any#routine_min>\nwould return the first argument with that value, whereas C<&[min]> would return\nits RHS. After 2022.06, C<&[min]> returns its LHS in the case of ties, and now\nboth return the same value as dictated by their List associativity.\n\n    say min 0, False; # OUTPUT: «0␤»\n    say 0 min False;  # OUTPUT: «0␤»\n    say min False, 0; # OUTPUT: «False␤»\n    say False min 0;  # OUTPUT: «False␤»\n\n=head2 infix C«max»\n\nReturns the largest of the arguments, as determined by L<cmp|/routine/cmp> semantics.\n\n    my $foo = -42;\n    $foo max= 0   # read as: $foo increases to 0\n\nB<Note:> Before 2022.06, in the cases of ties L<C<&max>|/type/Any#routine_max>\nwould return the first argument with that value, whereas C<&[max]> would return\nits RHS. After 2022.06, C<&[max]> returns its LHS in the case of ties, and now\nboth return the same value as dictated by their List associativity.\n\n    say max 0, False; # OUTPUT: «0␤»\n    say 0 max False;  # OUTPUT: «0␤»\n    say max False, 0; # OUTPUT: «False␤»\n    say False max 0;  # OUTPUT: «False␤»\n\n=head2 infix C«minmax»\n\nReturns the L<C<Range>|/type/Range> starting from the lowest to the highest of the values,\nas determined by the L<cmp|/routine/cmp> semantics.\nFor instance:\n\n=begin code\n# numeric comparison\n10 minmax 3;     # 3..10\n\n# string comparison\n'10' minmax '3'; # \"10\"..\"3\"\n'z' minmax 'k';  # \"k\"..\"z\"\n=end code\n\nIf the lowest and highest values coincide, the operator returns a L<C<Range>|/type/Range>\nmade by the same value:\n\n=begin code\n1 minmax 1;  # 1..1\n=end code\n\nWhen applied to L<C<List>|/type/List>s, the operator evaluates the lowest and highest values\namong all available values:\n\n=begin code\n(10,20,30) minmax (0,11,22,33);       # 0..33\n('a','b','z') minmax ('c','d','w');   # \"a\"..\"z\"\n=end code\n\nSimilarly, when applied to L<C<Hash>|/type/Hash>es, it performs a L<cmp|/routine/cmp> way comparison:\n\n=begin code\nmy %winner = points => 30, misses => 10;\nmy %loser = points => 20, misses => 10;\n%winner cmp %loser;      # More\n%winner minmax %loser;\n# ${:misses(10), :points(20)}..${:misses(10), :points(30)}\n=end code\n\n=head1 Conditional operator precedence\n\nX<|Operators,ternary>\nX<|Operators,conditional>\n=head2 infix C<?? !!>\n\nAlso called I<ternary> or I<conditional> operator, C<$condition ?? $true !!\n$false> evaluates C<$condition> and returns the expression right behind ??,\nin this case C<$true> if it is C<True>, otherwise evaluates and returns\nthe expression behind !!, C<$false> in this case.\n\nX<|Infix operators,flipflop>\n=head2 infix C«ff»\n\n    sub infix:<ff>(Mu $a, Mu $b)\n\nAlso called the I<flipflop operator>, compares both arguments to C<$_> (that is,\nC<$_ ~~ $a> and C<$_ ~~ $b>). Evaluates to C<False> until the left-hand\nsmartmatch is C<True>, at which point it evaluates to C<True> until the\nright-hand smartmatch is C<True>.\n\nIn effect, the left-hand argument is the \"start\" condition and the\nright-hand is the \"stop\" condition. This construct is typically used to\npick up only a certain section of lines. For example:\n\n=begin code :allow<V>\nmy $excerpt = q:to/END/;\nHere's some unimportant text.\nV<=>begin code\n    This code block is what we're after.\n    We'll use 'ff' to get it.\nV<=>end code\nMore unimportant text.\nEND\n\nmy @codelines = gather for $excerpt.lines {\n    take $_ if \"=begin code\" ff \"=end code\"\n}\n# this will print four lines, starting with \"=begin code\" and ending with\n# \"=end code\"\nsay @codelines.join(\"\\n\");\n=end code\n\nAfter matching the start condition, the operator will then match the\nsame C<$_> to the stop condition and act accordingly if successful. In\nthis example, only the first element is printed:\n\n    for <AB C D B E F> {\n        say $_ if /A/ ff /B/;  # OUTPUT: «AB␤»\n    }\n\nIf you only want to test against a start condition and have no stop\ncondition, C<*> can be used as such.\n\n    for <A B C D E> {\n        say $_ if /C/ ff *;    # OUTPUT: «C␤D␤E␤»\n    }\n\nFor the C<sed>-like version, which does I<not> try C<$_> on the stop\ncondition after succeeding on the start condition, see L<fff|/routine/fff>.\n\nThis operator cannot be overloaded, as it's handled specially by the\ncompiler.\n\n=head2 infix C«^ff»\n\n    sub infix:<^ff>(Mu $a, Mu $b)\n\nWorks like L<ff|/routine/ff>, except it does not return C<True> for items\nmatching the start condition (including items also matching the stop\ncondition).\n\nA comparison:\n\n    my @list = <X A B C Y>;\n    say $_ if /A/ ff /C/ for @list;    # OUTPUT: «A␤B␤C␤»\n    say $_ if /A/ ^ff /C/ for @list;   # OUTPUT: «B␤C␤»\n\nThe sed-like version can be found in L<C<^fff>|/routine/$CIRCUMFLEX_ACCENTfff>.\n\nThis operator cannot be overloaded, as it's handled specially by the compiler.\n\n=head2 infix C«ff^»\n\n    sub infix:<ff^>(Mu $a, Mu $b)\n\nWorks like L<ff|/routine/ff>, except it does not return C<True> for items matching the\nstop condition (including items that first matched the start condition).\n\n    my @list = <X A B C Y>;\n    say $_ if /A/ ff /C/ for @list;    # OUTPUT: «A␤B␤C␤»\n    say $_ if /A/ ff^ /C/ for @list;   # OUTPUT: «A␤B␤»\n\nThe sed-like version can be found in L<fff^|/routine/fff$CIRCUMFLEX_ACCENT>.\n\nThis operator cannot be overloaded, as it's handled specially by the compiler.\n\n=head2 infix C«^ff^»\n\n    sub infix:<^ff^>(Mu $a, Mu $b)\n\nWorks like L<ff|/routine/ff>, except it does not return C<True> for items matching either\nthe stop or start condition (or both).\n\n    my @list = <X A B C Y>;\n    say $_ if /A/ ff /C/ for @list;    # OUTPUT: «A␤B␤C␤»\n    say $_ if /A/ ^ff^ /C/ for @list;  # OUTPUT: «B␤»\n\nThe sed-like version can be found in L<C<^fff^>|/routine/$CIRCUMFLEX_ACCENTfff$CIRCUMFLEX_ACCENT>.\n\nThis operator cannot be overloaded, as it's handled specially by the compiler.\n\n=head2 infix C«fff»\n\n    sub infix:<fff>(Mu $a, Mu $b)\n\nPerforms a sed-like flipflop operation, wherein it returns C<False> until the\nleft argument smartmatches against C<$_>, then returns C<True> until\nthe right argument smartmatches against C<$_>.\n\nWorks similarly to L<ff|/routine/ff>, except that it only tries one argument per\ninvocation. That is, if C<$_> smartmatches the left argument, C<fff> will B<not>\nthen try to match that same C<$_> against the right argument.\n\n    for <AB C D B E F> {\n        say $_ if /A/ fff /B/;         # OUTPUT: «AB␤C␤D␤B␤»\n    }\n\nThe non-sed-like flipflop (which after successfully matching the left argument\nagainst C<$_> will try that same C<$_> against the right argument and act\naccordingly). See L<ff|/routine/ff>.\n\nThis operator cannot be overloaded, as it's handled specially by the compiler.\n\n=head2 infix C«^fff»\n\n    sub infix:<^fff>(Mu $a, Mu $b)\n\nLike L<fff|/routine/fff>, except it does not return true for matches to the left argument.\n\n    my @list = <X A B C Y>;\n    say $_ if /A/ fff /C/ for @list;   # OUTPUT: «A␤B␤C␤»\n    say $_ if /A/ ^fff /C/ for @list;  # OUTPUT: «B␤C␤»\n\nFor the non-sed version, see L<C<^ff>|/routine/$CIRCUMFLEX_ACCENTff>.\n\nThis operator cannot be overloaded, as it's handled specially by the compiler.\n\n=head2 infix C«fff^»\n\n    sub infix:<fff^>(Mu $a, Mu $b)\n\nLike L<fff|/routine/fff>, except it does not return true for matches to the right\nargument.\n\n    my @list = <X A B C Y>;\n    say $_ if /A/ fff /C/ for @list;   # OUTPUT: «A␤B␤C␤»\n    say $_ if /A/ fff^ /C/ for @list;  # OUTPUT: «A␤B␤»\n\nFor the non-sed version, see L<ff^|/routine/ff$CIRCUMFLEX_ACCENT>.\n\nThis operator cannot be overloaded, as it's handled specially by the compiler.\n\n=head2 infix C«^fff^»\n\n    sub infix:<^fff^>(Mu $a, Mu $b)\n\nLike L<fff|/routine/fff>, except it does not return true for matches to either the left or\nright argument.\n\n    my @list = <X A B C Y>;\n    say $_ if /A/ fff /C/ for @list;   # OUTPUT: «A␤B␤C␤»\n    say $_ if /A/ ^fff^ /C/ for @list; # OUTPUT: «B␤»\n\nFor the non-sed version, see L<C<^ff^>|/routine/$CIRCUMFLEX_ACCENTff$CIRCUMFLEX_ACCENT>.\n\nThis operator cannot be overloaded, as it's handled specially by the compiler.\n\n=head1 Item assignment precedence\n\nX<|Operators,item =>\n=head2 infix C«=» (item assignment)\n\n=begin code :skip-test<compile-time error>\nsub infix:<=>(Mu $a is rw, Mu $b)\n=end code\n\nCalled the I<item assignment operator>. It copies the value of the right-hand\nside into the Scalar container on the left-hand side.\n\nThe item assignment operator should be distinguished from the L<list assignment\noperator|#infix_=_(list_assignment)>, which uses the same\noperator symbol C<=> but has a lower precedence. The context of the left-hand\nside of the C<=> symbol determines whether it is parsed as item assignment or\nlist assignment. See the section on L<item and list\nassignment|/language/variables#Item_and_list_assignment> for a comparative\ndiscussion of the two assignment types.\n\n=head2 infix C«=>»\n\n    sub infix:«=>»($key, Mu $value --> Pair:D)\n\nL<C<Pair>|/type/Pair> constructor.X<|Infix operators,pair constructor>\n\nConstructs a L<C<Pair>|/type/Pair> object with the left-hand side as the key and the\nright-hand side as the value.\n\nNote that the C«=>» operator is syntactically special-cased, in that\nit allows unquoted identifier on the left-hand side.\n\n    my $p = a => 1;\n    say $p.key;         # OUTPUT: «a␤»\n    say $p.value;       # OUTPUT: «1␤»\n\nA L<C<Pair>|/type/Pair> within an argument list with an unquoted identifier on the left\nis interpreted as a named argument.\n\nSee L<the Terms language documentation|/language/terms#Pair> for more ways to\ncreate L<C<Pair>|/type/Pair> objects.\n\n=head1 Loose unary precedence\n\n=head2 prefix C«not»\n\n    multi prefix:<not>(Mu $x --> Bool:D)\n\nEvaluates its argument in Boolean context (and thus collapses L<C<Junction>|/type/Junction>s),\nand negates the result. Please note that C<not> is easy to misuse. See\nL<traps|/language/traps#Loose_Boolean_operators>.\n\n\n=head2 prefix C«so»\n\n    multi prefix:<so>(Mu $x --> Bool:D)\n\nEvaluates its argument in Boolean context (and thus collapses\nL<C<Junction>|/type/Junction>s), and returns the result.\n\n=head1 Comma operator precedence\n\n=head2 infix C«,»\n\n    sub infix:<,>(*@a --> List:D) is assoc<list>\n\nConstructs a higher-order L<C<Cool>|/type/Cool> from its arguments.\n\n    my @list = :god('Þor'), ['is',\"mighty\"];\n    say @list;      # OUTPUT: «[god => Þor [is mighty]]␤»\n    my %hash = :god('Þor'), :is(\"mighty\");\n    say %hash.raku; # OUTPUT: «{:god(\"Þor\"), :is(\"mighty\")}␤»\n    my %a = :11a, :22b;\n    say %(%a, :33x);  # OUTPUT: «{a => 11, b => 22, x => 33}␤»\n\nIn the first case it returns a L<C<List>|/type/List>, in the second case, since the\narguments are L<C<Pair>|/type/Pair>s, it builds a L<C<Hash>|/type/Hash>.\n\nIt can also be used for constructing variables from other variables, collating\nelements of different types, in this case a L<C<Hash>|/type/Hash> and a\nL<C<Pair>|/type/Pair>:\n\n=begin code :preamble<my %hash>\nmy %features = %hash, :wields(\"hammer\");\nsay %features;  # OUTPUT: «{god => Þor, is => mighty, wields => hammer}␤»\n=end code\n\nThe comma is also used syntactically as the separator of arguments in\ncalls.\n\n\n=head2 infix C«:»\n\nUsed as an argument separator just like infix C<,> and marks the\nargument to its left as the invocant. That turns what would otherwise be\na function call into a method call.\n\n    substr('abc': 1);       # same as 'abc'.substr(1)\n\nInfix C<:> is only allowed after the first argument of a non-method call. In\nother positions, it's a syntax error.\n\n=head1 List infix precedence\n\n=head2 infix C«Z»\n\n    sub infix:<Z>(**@lists --> Seq:D) is assoc<list>\n\nThe X<Zip operator|Infix operators,Zip operator> interleaves the lists passed to C<Z> like a zipper,\ntaking index-corresponding elements from each operand. The returned L<C<Seq>|/type/Seq>\ncontains nested lists, each with a value from every operand in the chain. If\none of the operands runs out of elements prematurely, the zip operator will\nstop.\n\n=for code\nsay (1, 2 Z <a b c> Z <+ ->).raku;\n# OUTPUT: «((1, \"a\", \"+\"), (2, \"b\", \"-\")).Seq␤»\nfor <a b c> Z <1 2 3 4> -> [$l, $r] {\n    say \"$l:$r\"\n}\n# OUTPUT: «a:1␤b:2␤c:3␤»\n\nThe C<Z> operator also exists as a L<metaoperator|/language/operators#Zip_metaoperator>,\nin which case the inner lists are replaced by the value from applying the operator to the\nlist:\n\n    say 100, 200 Z+ 42, 23;             # OUTPUT: «(142 223)␤»\n    say 1..3 Z~ <a b c> Z~ 'x' xx 3;    # OUTPUT: «(1ax 2bx 3cx)␤»\n\nC<infix:<Z>> is a shortcut for C<Z,>, which is the L<C<Z> metaoperator|/language/operators#Zip_metaoperator>\napplied to the L<C<,> list-construction operator|/language/operators#infix_,>.\n\nAs any other infix operator, it can be used under its full name:\n\n=for code\nsay infix:<Z>(<a b>,<c d>);             # OUTPUT: «((a c) (b d))␤»\n\nIf no argument is given, it will return an empty L<C<Seq>|/type/Seq>\n\n=for code\nsay infix:<Z>();                        # OUTPUT: «()␤»\n\n\nX<|Infix operators,cross product operator>\nX<|Infix operators,X>\n=head2 infix C«X»\n\n    multi infix:<X>(+lol, :&with! --> Seq:D)\n    multi infix:<X>(+lol --> Seq:D)\n\nCreates a cross product from all the lists, ordered so that the\nrightmost elements vary most rapidly, and returns a L<C<Seq>|/type/Seq>:\n\n    1..3 X <a b c> X 9\n    # produces ((1 a 9) (1 b 9) (1 c 9)\n    #           (2 a 9) (2 b 9) (2 c 9)\n    #           (3 a 9) (3 b 9) (3 c 9))\n\nThe C<X> operator also exists as a metaoperator, in which case the inner\nlists are replaced by the value from applying the operator to the list:\n\n    1..3 X~ <a b c> X~ 9\n    # produces (1a9 1b9 1c9 2a9 2b9 2c9 3a9 3b9 3c9)\n\nX<|Infix operators,...>X<|Infix operators,...^>X<|Infix operators,^...>X<|Infix operators,^...^>\nX<|Infix operators,…>X<|Infix operators,…^>X<|Infix operators,^…>X<|Infix operators,^…^>\n=head2 infix C«...»\n\n    multi infix:<...>(**@) is assoc<list>\n    multi infix:<...^>(**@) is assoc<list>\n    multi infix:<^...>(**@) is assoc<list>\n    multi infix:<^...^>(**@) is assoc<list>\n\nThe X<sequence operator|Infix operators,sequence operator>, which can be written either as C<...> or as\nC<…>, with variants C<...^>, C<^...>, C<^...^>, C<…^>, C<^…> and C<^…^>,\nwill produce (possibly lazy) generic sequences on demand. Such sequences\nare of the L«C<Seq>|/type/Seq» type.\n\nThe variants of the operator with an initial caret, C<^...>, C<^...^>,\nC<^…> and C<^…^>, produce sequences that do not contain the initial\nelement.\n\nThe variants of the operator with a final caret, C<...^>, C<^...^>,\nC<…^> and C<^…^>, produce sequences that do not contain the final\nelement.\n\nNote: the variants C<^...>, C<^...^>, C<^…> and C<^…^> have been\navailable in Rakudo compiler starting from 2020.05 release.\n\nThe left-hand side of the operator specify the initial elements; it may include a\ngenerator after the first element or elements. The right-hand side will\nhave an endpoint, which can be C<Inf> or C<*> for \"infinite\" lists (that is,\nI<lazy> lists whose elements are only produced on demand), an expression which\nwill end the sequence when C<True>, or other elements such as\nL<C<Junction>|/type/Junction>s.\n\nThe sequence operator invokes the generator with as many arguments as necessary.\nThe arguments are taken from the initial elements and the already generated\nelements.\n\nAn endpoint of C<*> (L<C<Whatever>|/type/Whatever>), C<Inf> or C<∞>\ngenerates on demand an infinite sequence, with a default generator of\nC<*.succ>\n\n    say (1 ... *)[^5];  # OUTPUT: «(1 2 3 4 5)␤»\n\nCustom generators need to be the last element of the list before the\n'...' operator. This one takes two arguments, and generates the\neight first Fibonacci numbers\n\n=for code\nsay (1, 1, -> $a, $b { $a + $b } ... *)[^8]; # OUTPUT: «(1 1 2 3 5 8 13 21)␤»\n# same but shorter\nsay (1, 1, * + * ... *)[^8];                 # OUTPUT: «(1 1 2 3 5 8 13 21)␤»\n\nThe generator can also take only one argument.\n\n    say 5, { $_ * 2 } ... 40;                # OUTPUT: «5 10 20 40␤»\n\nOr it can use the L<anonymous state variable\nC<$>|/language/variables#index-entry-$_(variable)> to skip one position in\nthe sequence when computing the next one:\n\n    say (1, 1, 1, -> $a, $b, $ { $a + $b } … ∞)[3..10];\n    # OUTPUT: «(2 2 3 4 5 7 9 12)␤»\n\nThere must be at least as many initial elements as arguments to the\ngenerator.\n\nIf the endpoint is not C<*>, it's smartmatched against each generated\nelement and the sequence is terminated when the smartmatch succeeded.\nThe final element is excluded of the sequence if a sequence operator\nvariant with a final caret is used, it is included otherwise.\n\nThis allows you to write\n\n    say 1, 1, * + * ...^ *>= 100;\n    # OUTPUT: «(1 1 2 3 5 8 13 21 34 55 89)␤»\n\nto generate all Fibonacci numbers up to but excluding 100.\n\nThe C<...> operators consider the initial values as \"generated elements\" as\nwell, so they are also checked against the endpoint:\n\n    my $end = 4;\n    say 1, 2, 4, 8, 16 ... $end;\n    # OUTPUT: «(1 2 4)␤»\n\nIf you do not provide a generator, the sequence operator tries to deduce the\nsequence.  In most cases, this means using a default C<*.>L<succ|/routine/succ>\nor C<*.>L<pred|/routine/pred>, depending on how the end points compare:\n\n    say 1 ... 4;        # OUTPUT: «(1 2 3 4)␤»\n    say 4 ... 1;        # OUTPUT: «(4 3 2 1)␤»\n    say 1 ^... 4;       # OUTPUT: «(2 3 4)␤»\n    say 1 ...^ 4;       # OUTPUT: «(1 2 3)␤»\n    say 1 ^...^ 4;      # OUTPUT: «(2 3)␤»\n    say 'a' ... 'e';    # OUTPUT: «(a b c d e)␤»\n    say 'e' ... 'a';    # OUTPUT: «(e d c b a)␤»\n\nHowever, the sequence operator will deduce a different sequence in some special\ncases.\n\nIf you provide more than one initial element and all initial elements are\nnumeric, the sequence operator tries find an arithmetic or geometric sequence\nthat fits the pattern in the initial elements:\n\n    say 2, 4, 6 ... 12;     # OUTPUT: «(2 4 6 8 10 12)␤»\n    say 1, 2, 4 ... 32;     # OUTPUT: «(1 2 4 8 16 32)␤»\n    say 1, 2, 4 ^... 32;    # OUTPUT: «(2 4 8 16 32)␤»\n    say 1, 2, 4 ^...^ 32;   # OUTPUT: «(2 4 8 16)␤»\n\nIf you provide one L<C<Str>|/type/Str> initial element and a L<C<Str>|/type/Str> final element with the\nsame number of characters, then the sequence operator will deduce a sequence of\nall strings where each letter is C<le> the letter at the corresponding position\nin the final element:\n\n    say 'aa' … 'cc';          # OUTPUT: «(aa ab ac ba bb bc ca cb cc)␤»\n    # Which is the same as\n    say 'a'..'c' X~ 'a'..'c'; # OUTPUT: «(aa ab ac ba bb bc ca cb cc)␤»\n\n\n=head1 List prefix precedence\n\nX<|Syntax,list =>\nX<|Infix operators,List assignment operator>\n=head2 infix C«=» (list assignment)\n\nThe list assignment operator generally copies values from its right-hand side\ninto the container on its left-hand side. Its exact semantics are left to the\nleft-hand side container type. See L<C<Array>|/type/Array> and L<C<Hash>|/type/Hash>\nfor common cases.\n\nThe list assignment operator should be distinguished from the L<item assignment\noperator|#infix_=_(item_assignment)>, which uses the same\noperator symbol C<=> but has a higher precedence. The context of the left-hand\nside of the C<=> symbol determines whether it is parsed as item assignment or\nlist assignment. See the section on L<item and list\nassignment|/language/variables#Item_and_list_assignment> for a comparative\ndiscussion of the two assignment types.\n\n=head2 infix C«:=»\n\nX<Binding operator|Infix operators,binding operator>. Whereas C<$x = $y> puts the value in C<$y> into\nC<$x>, C<$x := $y> makes C<$x> and C<$y> the same thing.\n\n    my $a = 42;\n    my $b = $a;\n    $b++;\n    say $a;\n\nThis will output 42, because C<$a> and C<$b> both contained the number\nC<42>, but the L<containers|/language/containers#Binding> were\ndifferent.\n\n    my $a = 42;\n    my $b := $a;\n    $b++;\n    say $a;\n\nThis will output 43, since C<$b> and C<$a> both represented the same\nobject.\n\nIf type constrains on variables or containers are present a type check\nwill be performed at runtime. On failure C<X::TypeCheck::BindingType>\nwill be thrown.\n\nPlease note that C<:=> is a compile time operator. As such it can not\nbe referred to at runtime and thus can't be used as an argument to\nmetaoperators.\n\n=head2 infix C«::=»\n\nX<Read-only binding operator|Infix operators,Read-only binding operator>, not yet implemented in Rakudo.\nSee L<C<infix :=>|/routine/:=>.\n\nX<|Listop operators,stub operator>\n=head2 listop C«...»\n\nCalled the I<yada, yada, yada> operator or I<stub> operator, if it's the\nonly statement in a routine or type, it marks that routine or type as a\nstub (which is significant in the context of pre-declaring types and\ncomposing roles).\n\nIf the C<...> statement is executed, it calls L<fail|/routine/fail>,\nwith the default message C<Stub code executed>.\n\nThis operator can be used for forward declarations of classes:\n\n=for code\nclass Foo {...}\nclass Bar {\n    has Foo $.foo;\n}\nclass Foo {\n    say \"This is a Foo object\";\n}\n\nor routines, such as this L<C<Sub>|/type/Sub>:\n\n=for code\nsub a() { ... }\nsay a;           # OUTPUT: «42␤»\nsub a() { 42 }\n\nPlease note that, in this case, it's not really necessary, and it will work\nthe same without that forward declaration.\n\nX<|Listop operators,Fatal stub operator>\n=head2 listop C«!!!»\n\nIf it's the only statement in a routine or type, it marks that routine\nor type as a stub (which is significant in the context of pre-declaring\ntypes and composing roles).\n\nIf the C<!!!> statement is executed, it calls L<die|/routine/die>, with\nthe default message C<Stub code executed>.\n\n\nX<|Operators,Admonitory stub operator>\n=head2 listop C«???»\n\nIf it's the only statement in a routine or type, it marks that routine\nor type as a stub (which is significant in the context of pre-declaring\ntypes and composing roles).\n\nIf the C<???> statement is executed, it calls L<warn|/routine/warn>,\nwith the default message C<Stub code executed>.\n\n=head2 Reduction operators\n\nAny infix operator (except for non-associating operators) can be\nsurrounded by square brackets in term position to create a list operator\nthat reduces using that operation.\n\n    say [+] 1, 2, 3;      # 1 + 2 + 3 = 6\n    my @a = (5, 6);\n    say [*] @a;           # 5 * 6 = 30\n\nReduction operators have the same associativity as the operators they\nare based on.\n\n    say [-] 4, 3, 2;      # 4-3-2 = (4-3)-2 = -1\n    say [**] 4, 3, 2;     # 4**3**2 = 4**(3**2) = 262144\n\nApplying [+] to a single element will return that element\n\n=for code\nsay [+] 42;           # OUTPUT: «42␤»\n\n\n=head1 Loose AND precedence\n\n=head2 infix X<C«and»|Operators,and>\n\nSame as L<infix &&|#infix_%26%26>, except with looser\nprecedence.\n\nShort-circuits so that it returns the first operand that evaluates to\nC<False>, otherwise returns the last operand. Note that C<and> is easy\nto misuse, see L<traps|/language/traps#Loose_Boolean_operators>.\n\n=head2 infix X<C«andthen»|Operators,andthen>\n\nThe C<andthen> operator returns L«C<Empty>|/type/Slip#constant_Empty» if the\nfirst argument is L<undefined|/routine/defined>, otherwise the last\nargument. The last argument is returned as-is, without being checked for\ndefinedness at all. Short-circuits. The result of the left side is bound\nto C<$_> for the right side, or passed as arguments if the right side is\na L«C<Callable>|/type/Callable», whose L<count|/routine/count> must be C<0>\nor C<1>.\n\nA handy use of this operator is to alias a routine's return value to C<$_> and\nto do additional manipulation with it, such as printing or returning it to\ncaller. Since the C<andthen> operator short-circuits, statements on the\nright-hand side won't get executed, unless left-hand side is defined (tip:\nL<C<Failure>|/type/Failure>s are never defined, so you can handle them with\nthis operator).\n\n    \"does this match?\" ~~ /this/ andthen {\n        .put;\n        my $thing-to-do-if-match-succeeds;\n        ...\n    } # OUTPUT: «this␤»\n\n    \"does that match?\" ~~ /this/ andthen put 'oops';\n    # NO OUTPUT\n\nThe C<andthen> operator is a close relative of the L«C<with> statement\nmodifier|/language/control#with_orwith_without», and some compilers\ncompile C<with> to C<andthen>, meaning these two lines have equivalent\nbehavior:\n\n    .say with 42;\n    42 andthen .say;\n\n=head2 infix X<C«notandthen»|Infix operators,notandthen>\n\nThe C<notandthen> operator returns L«C<Empty>|/type/Slip#constant_Empty» if the\nfirst argument is L<defined|/routine/defined>, otherwise the last argument. The last argument\nis returned as-is, without being checked for definedness at all. Short-circuits.\nThe result of the left side is bound to C<$_> for the right side, or passed as\narguments if the right side is a L«C<Callable>|/type/Callable», whose\nL<count|/routine/count> must be C<0> or C<1>.\n\nAt first glance, L<notandthen|/routine/notandthen> might appear to be the same\nthing as the L<orelse|/routine/orelse> operator. The difference is subtle:\nL<notandthen|/routine/notandthen> returns\nL«C<Empty>|/type/Slip#constant_Empty» when it encounters a\nL<defined|/routine/defined> item (that isn't the last item), whereas\nL<orelse|/routine/orelse> returns that item. In other words,\nL<notandthen|/routine/notandthen> is a means to act when items aren't defined,\nwhereas L<orelse|/routine/orelse> is a means to obtain the first defined item:\n\n=begin code\nsub all-sensors-down     { [notandthen] |@_, True             }\nsub first-working-sensor { [orelse]     |@_, 'default sensor' }\n\nall-sensors-down Nil, Nil, Nil\n  and say 'OMG! All sensors are down!'; # OUTPUT:«OMG! All sensors are down!␤»\nsay first-working-sensor Nil, Nil, Nil; # OUTPUT:«default sensor␤»\n\nall-sensors-down Nil, 42, Nil\n  and say 'OMG! All sensors are down!'; # No output\nsay first-working-sensor Nil, 42, Nil;  # OUTPUT:«42␤»\n=end code\n\nThe C<notandthen> operator is a close relative of the L«C<without> statement\nmodifier|/language/control#with_orwith_without», and some compilers\ncompile C<without> to C<notandthen>, meaning these two lines have equivalent\nbehavior:\n\n=begin code\nsub good-things { fail }\n\n'boo'.say without good-things;\ngood-things() notandthen 'boo'.say;\n=end code\n\n=head1 Loose OR precedence\n\n=head2 infix C«or»\n\nSame as L<infix C<||>|/routine/||>, except with looser precedence.\n\nReturns the first argument that evaluates to C<True> in Boolean context, or\notherwise the last argument, it short-circuits. Please note that C<or> is easy\nto misuse. See L<traps|/language/traps#Loose_Boolean_operators>.\n\nX<|Infix operators,orelse>\n=head2 infix C«orelse»\n\nThe C<orelse> operator is similar to C<infix //>, except with looser precedence\nand C<$_> aliasing.\n\nReturns the first defined argument, or else the last argument. Last argument\nis returned as-is, without being checked for definedness at all.\nShort-circuits. The result of the left side is bound to\nC<$_> for the right side, or passed as an argument if the right side is a\nL«C<Callable>|/type/Callable», whose L<count|/routine/count> must be C<0> or C<1>.\n\nThis operator is useful for handling L<C<Failure>|/type/Failure>s returned by\nroutines since the expected value is usually L<defined|/routine/defined>\nand L<C<Failure>|/type/Failure> never is:\n\n    sub meows { ++$ < 4 ?? fail 'out of meows!' !! '🐱' }\n\n    sub meows-processor1 { meows() orelse .return } # return handled Failure\n    sub meows-processor2 { meows() orelse fail $_ } # return re-armed Failure\n    sub meows-processor3 {\n        # Use non-Failure output, or else print a message that stuff's wrong\n        meows() andthen .say orelse ‘something's wrong’.say;\n    }\n\n    say \"{.^name}, {.handled}\"  # OUTPUT: «Failure, True␤»\n        given meows-processor1;\n    say \"{.^name}, {.handled}\"  # OUTPUT: «Failure, False␤»\n        given meows-processor2;\n    meows-processor3;           # OUTPUT: «something's wrong␤»\n    meows-processor3;           # OUTPUT: «🐱␤»\n\n=head2 infix C«xor»\n\nSame as L<infix C<^^>|/routine/$CIRCUMFLEX_ACCENT$CIRCUMFLEX_ACCENT>, except with looser precedence.\n\nReturns the operand that evaluates to C<True> in Boolean context, if and\nonly if the other operand evaluates to C<False> in Boolean context. If\nboth operands evaluate to C<False>, returns the last argument. If both\noperands evaluate to C<True>, returns L<C<Nil>|/type/Nil>.\n\nWhen chaining, returns the operand that evaluates to C<True>, if and\nonly if there is one such operand. If more than one operand is true,\nit short-circuits after evaluating the second and returns L<C<Nil>|/type/Nil>. If all\noperands are false, returns the last one.\n\n=head1 Sequencer precedence\n\n=head2 infix C«==>»\n\nThis X<feed|Infix operators,feed> operator takes the result from the left and passes it to the\nnext (right) routine as the last parameter.\n\n     my @array = 1, 2, 3, 4, 5;\n     @array ==> sum() ==> say();   # OUTPUT: «15␤»\n\nThis simple example, above, is the equivalent of writing:\n\n     my @array = 1, 2, 3, 4, 5;\n     say(sum(@array));             # OUTPUT: «15␤»\n\nOr if using methods:\n\n     my @array = 1, 2, 3, 4, 5;\n     @array.sum.say;               # OUTPUT: «15␤»\n\nThe precedence is very loose so you will need to use parentheses to\nassign the result or you can even just use another feed operator! In the\ncase of routines/methods that take a single argument or where the first argument\nis a block, it's often required that you call with parentheses (though this\nis not required for the very last routine/method).\n\nThis  \"traditional\" structure, read bottom-to-top, with the last two\nlines creating the data structure that is going to be processed\n\n    my @fractions = <TWO THREE FOUR FIVE SEVEN> »~» \" \" X~ <FIFTHS SIXTHS EIGHTHS>;\n    my @result = map { .uniparse },                    # (3) Converts to unicode\n        grep { .uniparse },                            # (2) Checks if it parses\n        map( {\"VULGAR FRACTION \" ~ $^þ }, @fractions); # (1) Adds string to input\n\n    # @result is [⅖ ⅗ ⅜ ⅘ ⅚ ⅝ ⅞]\n\nNow we use the feed operator (left-to-right) with parentheses, read\ntop-to-bottom\n\n    my @result = (\n        <TWO THREE FOUR FIVE SEVEN> »~» \" \" X~ <FIFTHS SIXTHS EIGHTHS> # (1) Input\n        ==> map( {\"VULGAR FRACTION \" ~ $^þ } )                         # (2) Converts to Unicode name\n        ==> grep({ .uniparse })                                        # (3) Filters only real names\n        ==> map( { .uniparse} );                                       # (4) Converts to unicode\n    );\n\nFor illustration, method chaining equivalent, read top-to-bottom, using the same sequence as above\n\n    my @result = ( <TWO THREE FOUR FIVE SEVEN> »~» \" \" X~ <FIFTHS SIXTHS EIGHTHS>)\n        .map( {\"VULGAR FRACTION \" ~ $^þ } )\n        .grep({ .uniparse })\n        .map({ .uniparse });\n\nAlthough in this particular case the result is the same, the feed operator\nC«==>» more clearly shows intent with arrow pointing in the direction of the\ndata flow.  To assign without the need of parentheses use another feed operator\n\n    <people of earth>\n        ==> map({ .tc })\n        ==> grep /<[PE]>/\n        ==> sort()\n        ==> my @result;\n\nIt can be useful to capture a partial result, however, unlike the\n    leftward feed operator, it does require parentheses or a semicolon\n\n    <people of earth>\n        ==> map({ .tc })\n        ==> my @caps; @caps   # also could wrap in parentheses: (my @caps)\n        ==> grep /<[PE]>/\n        ==> sort()\n        ==> my @result;\n\nThe feed operator lets you construct method-chaining-like patterns out of\nroutines and the results of methods on unrelated data. In method-chaining,\nyou are restricted to the methods available on the data or the result of\nprevious method call. With feed operators, that restriction is gone.\nThe resulting code could also be seen to be more readable than a series of\nmethod calls broken over multiple lines.\n\nNote: In the future, this operator will see some change as it gains the\nability to run list operations in parallel. It will enforce that the\nB<left> operand is enclosable as a closure (that can be cloned and run in\na subthread).\n\n=head2 infix C«<==»\n\nThis X<leftward feed|Infix operators,leftward feed> operator takes the result from the right and passes\nit to the previous (left) routine as the last parameter. This\nelucidates the right-to-left dataflow for a series of list manipulating\nfunctions.\n\n    # Traditional structure, read bottom-to-top\n    my @result =\n        sort                   # (4) Sort, result is <Earth People>\n        grep { /<[PE]>/ },     # (3) Look for P or E\n        map { .tc },           # (2) Capitalize the words\n        <people of earth>;     # (1) Start with the input\n\n    # Feed (right-to-left) with parentheses, read bottom-to-top\n    my @result = (\n        sort()                 # (4) Sort, result is <Earth People>\n        <== grep({ /<[PE]>/ }) # (3) Look for P or E\n        <== map({ .tc })       # (2) Capitalize the words\n        <== <people of earth>  # (1) Start with the input\n    );\n\n    # To assign without parentheses, use another feed operator\n    my @result\n        <== sort()              # (4) Sort, result is <Earth People>\n        <== grep({ /<[PE]>/ })  # (3) Look for P or E\n        <== map({ .tc })        # (2) Capitalize the words\n        <== <people of earth>;  # (1) Start with the input\n\n    # It can be useful to capture a partial result\n    my @result\n        <== sort()\n        <== grep({ /<[PE]>/ })\n        <== my @caps            # unlike ==>, there's no need for additional statement\n        <== map({ .tc })\n        <== <people of earth>;\n\nUnlike the rightward feed operator, the result is not closely mappable\nto method-chaining. However, compared to the traditional structure above\nwhere each argument is separated by a line, the resulting code is more\ndemonstrative than commas. The leftward feed operator also allows you\nto \"break into\" the statement and capture an intermediary result which\ncan be extremely useful for debugging or to take that result and create\nanother variation on the final result.\n\nNote: In the future, this operator will see some change as it gains the\nability to run list operations in parallel. It will enforce that the\nB<right> operand is enclosable as a closure (that can be cloned and run in\na subthread).\n\n=head1 Identity\n\nIn general, infix operators can be applied to a single or no element without\nyielding an error, generally in the context of a L<reduce|/routine/reduce>\noperation.\n\n    say [-] ()  # OUTPUT: «0␤»\n\nThe design documents specify that this should return\nL<an identity value|https://en.wikipedia.org/wiki/Identity_element>,\nand that an identity value\nL<must be specified for every operator|http://design.raku.org/S03.html#Reduction_operators>.\nIn general, the\nidentity element returned should be intuitive. However, here is a table that\nspecifies how it is defined for operator classes in Raku, which corresponds to\nthe table in the above definition in the types and operators defined by the\nlanguage:\n\n=begin table\nOperator class | Identity value\n===============+===============\nEquality       | True\nArithmetic \\+  | 0\nArithmetic *   | 1\nComparison     | True\nBitwise        | 0\nStringy        | ''\nSets           | Empty set or equivalent\nOr-like Bool   | False\nAnd-like Bool  | True\n=end table\n\nFor instance, union of an empty list will return an empty set:\n\n    say [∪];  # OUTPUT: «Set()␤»\n\nThis only applies to operators where empty or 0 is always a valid operand. For\ninstance, applying it to division will yield an exception.\n\n=for code\nsay [%] ();  # OUTPUT: «(exit code 1) No zero-arg meaning for infix:<%>␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Language/optut.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"tutorial\")\n\n=TITLE Creating operators\n\n=SUBTITLE A short tutorial on how to declare operators and create new ones.\n\nOperators are declared by using the C<sub> keyword followed by\nC<prefix>, C<infix>, C<postfix>, C<circumfix>, or C<postcircumfix>;\nthen a colon and the operator name in a quote construct. For (post-)circumfix\noperators separate the two parts by white space.\n\n    sub hello {\n        say \"Hello, world!\";\n    }\n\n    say &hello.^name;   # OUTPUT: «Sub␤»\n    hello;              # OUTPUT: «Hello, world!␤»\n\n    my $s = sub ($a, $b) { $a + $b };\n    say $s.^name;       # OUTPUT: «Sub␤»\n    say $s(2, 5);       # OUTPUT: «7␤»\n\n    # Alternatively we could create a more\n    # general operator to sum n numbers\n    sub prefix:<Σ>( *@number-list ) {\n        [+] @number-list\n    }\n\n    say Σ (13, 16, 1); # OUTPUT: «30␤»\n\n    sub infix:<:=:>( $a is rw, $b is rw ) {\n        ($a, $b) = ($b, $a)\n    }\n\n    my ($num, $letter) = ('A', 3);\n    say $num;          # OUTPUT: «A␤»\n    say $letter;       # OUTPUT: «3␤»\n\n    # Swap two variables' values\n    $num :=: $letter;\n\n    say $num;          # OUTPUT: «3␤»\n    say $letter;       # OUTPUT: «A␤»\n\n    sub postfix:<!>( Int $num where * >= 0 ) { [*] 1..$num }\n    say 0!;            # OUTPUT: «1␤»\n    say 5!;            # OUTPUT: «120␤»\n\n    sub postfix:<♥>( $a ) { say „I love $a!“ }\n    42♥;               # OUTPUT: «I love 42!␤»\n\n    sub postcircumfix:<⸨ ⸩>( Positional $a, Whatever ) {\n        say $a[0], '…', $a[*-1]\n    }\n\n    [1,2,3,4]⸨*⸩;      # OUTPUT: «1…4␤»\n\n    constant term:<♥> = \"♥\"; # We don't want to quote \"love\", do we?\n    sub circumfix:<α ω>( $a ) {\n        say „$a is the beginning and the end.“\n    };\n\n    α♥ω;               # OUTPUT: «♥ is the beginning and the end.␤»\n\nThese operators use the\nL<extended identifier|/language/syntax#Extended_identifiers>\nsyntax; that is\nwhat enables the use of any kind of codepoint to refer to them.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/packages.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Packages\n\n=SUBTITLE Organizing and referencing namespaced program elements\n\n=begin comment\n\nTODO\n* Take a lot of stuff from S02 for this\n* Document 'import'\n\n=end comment\n\nPackages are nested namespaces of named program elements.\nL<Modules|/language/module-packages>, classes, grammars, and others are types of\npackages. Like files in a directory, you can generally refer to named elements\nwith their short-name if they are local, or with the longer name that includes\nthe namespace to disambiguate as long as their scope allows that.\n\n=head1 Names\n\nA package I<name> is anything that is a legal part of a variable name (not\ncounting the sigil). This includes:\n\n=begin code\nclass Foo {\n    sub zape () { say \"zipi\" }\n    class Bar {\n        method baz () { return 'Þor is mighty' }\n        our &zape = { \"zipi\" };\n        our $quux = 42;\n    }\n}\n\nmy $foo;                # simple identifiers\nsay Foo::Bar.baz;       # calling a method; OUTPUT: «Þor is mighty␤»\nsay Foo::Bar::zape;     # compound identifiers separated by ::; OUTPUT: «zipi␤»\nmy $bar = 'Bar';\nsay $Foo::($bar)::quux; # compound identifiers with interpolations; OUTPUT: «42␤»\n$42;                    # numeric names\n$!;                     # certain punctuation variables\n=end code\n\nX<|Syntax,::>\nC<::> is used to separate nested package names.\n\nPackages do not really have an identity; they can be simply part of a module or\nclass name, for instance. They are more similar to namespaces than to modules. A\nmodule of the same name will I<capture> the identity of a package if it\nexists.\n\n=begin code\npackage Foo:ver<0> {};\nmodule Foo:ver<1> {};\nsay Foo.^ver; # OUTPUT: «1␤»\n=end code\n\nThe syntax allows the declared package to use a version as well as an\nI<authority> C<auth>, but as a matter of\nfact, it's dismissed; only modules, classes and other higher order type\nobjects have an identity that might include C<auth> and C<ver>.\n\n=for code\npackage Foo:ver<0>:auth<bar> {};\nsay Foo.^auth;\n# OUTPUT: «(exit code 1) No such method 'auth' for invocant of type\n# 'Perl6::Metamodel::PackageHOW' ...\n\n=head2 Package-qualified names\n\nOrdinary package-qualified names look like this: C<$Foo::Bar::quux>,\nwhich would be the C<$quux> variable in package C<Foo::Bar>;\nC<Foo::Bar::zape> would represent the C<&zape> variable in the same\npackage.\n\nSometimes it's clearer to keep the sigil with the variable name, so an\nalternate way to write this is:\n\n    Foo::Bar::<$quux>\n\nThis does not work with the C<Foo«&zape»> variable, since C<sub>s, by default,\nhave lexical scope. The name is resolved at compile time because the variable\nname is a constant. We can access the rest of the variables in C<Bar> (as shown\nin the example above) since classes, by default, have package scope.\n\nIf the name part before C<::> is null, it means the package is unspecified and\nmust be searched for. Generally this means that an initial C<::> following the\nmain sigil is a no-op on names that are known at compile time, though C<::()>\ncan also be used to introduce an interpolation. Also, in the absence of another\nsigil, C<::> can serve as its own sigil indicating intentional use of a\nnot-yet-declared package name.\n\n=head1 Pseudo-packages\n\nX«|Reference,MY (package)»X«|Reference,OUR (package)»X«|Reference,CORE (package)»X«|Reference,GLOBAL (package)»X«|Reference,PROCESS (package)»X«|Reference,COMPILING(package)»\nThe following pseudo-package names are reserved at the front of a name:\n\n=begin table\nMY          Symbols in the current lexical scope\nOUR         Symbols in the current package\nCORE        Outermost lexical scope, definition of standard Raku\nGLOBAL      Interpreter-wide package symbols, really UNIT::GLOBAL\nPROCESS     Process-related globals (superglobals). The last place dynamic variable lookup will look.\n=end table\n\nX«|Reference,CALLER (package)»X«|Reference,CALLERS (package)»X«|Reference,DYNAMIC (package)»\nX«|Reference,OUTER (package)»X«|Reference,OUTERS (package)»X«|Reference,LEXICAL (package)»\nX«|Reference,UNIT (package)»X«|Reference,SETTING (package)»X«|Reference,PARENT (package)»X«|Reference,CLIENT (package)»\nThe following relative names are also reserved but may be used\nanywhere in a name:\n\n=begin table\n    CALLER      Dynamic symbols in the immediate caller's lexical scope\n    CALLERS     Dynamic symbols in any caller's lexical scope\n    DYNAMIC     Dynamic symbols in my or any caller's lexical scope\n    OUTER       Symbols in the next outer lexical scope\n    OUTERS      Symbols in any outer lexical scope\n    LEXICAL     Dynamic symbols in my or any outer's lexical scope\n    UNIT        Symbols in the outermost lexical scope of compilation unit\n    SETTING     Lexical symbols in the unit's DSL (usually CORE)\n    PARENT      Symbols in this package's parent package (or lexical scope)\n    CLIENT      The nearest CALLER that comes from a different package\n=end table\n\nThe file's scope is known as C<UNIT>, but there are one or more lexical\nscopes outside of that corresponding to the linguistic setting (often\nknown as the prelude in other cultures). Hence, the C<SETTING> scope is\nequivalent to C<UNIT::OUTERS>. For a standard Raku program C<SETTING>\nis the same as C<CORE>, but various startup options (such as C<-n> or\nC<-p>) can put you into a domain specific language, in which case\nC<CORE> remains the scope of the standard language, while C<SETTING>\nrepresents the scope defining the DSL that functions as the setting of\nthe current file. When used as a search term in the middle of a name,\nC<SETTING> includes all its outer scopes up to C<CORE>. To get I<only>\nthe setting's outermost scope, use C<UNIT::OUTER> instead.\n\n=head1 Looking up names\n\n=head2 X<Interpolating into names|Language,interpolating into names>\n\nX<|Syntax,::()> You may L<interpolate|https://en.wikipedia.org/wiki/String_interpolation> a string into a\npackage or variable name using C<::($expr)> where you'd ordinarily put a package\nor variable name. The string is allowed to contain additional instances of\nC<::>, which will be interpreted as package nesting. You may only interpolate\nentire names, since the construct starts with C<::>, and either ends immediately\nor is continued with another C<::> outside the parentheses. Most symbolic\nreferences are done with this notation:\n\n=for code :skip-test<compile time error>\nmy $foo = \"Foo\";\nmy $bar = \"Bar\";\nmy $foobar = \"Foo::Bar\";\n$::($bar)              # lexically-scoped $Bar\n$::(\"MY::$bar\")        # lexically-scoped $Bar\n$::(\"OUR::$bar\")       # package-scoped $Bar\n$::(\"GLOBAL::$bar\")    # global $Bar\n$::(\"PROCESS::$bar\")   # process $Bar\n$::(\"PARENT::$bar\")    # current package's parent's $Bar\n$::($foobar)           # $Foo::Bar\n@::($foobar)::baz      # @Foo::Bar::baz\n@::($foo)::Bar::baz    # @Foo::Bar::baz\n@::($foobar)baz        # ILLEGAL at compile time (no operator baz)\n@::($foo)::($bar)::baz # @Foo::Bar::baz\n\nAn initial C<::> doesn't imply global; here as part of the interpolation\nsyntax it doesn't even imply package. After the interpolation of the\nC<::()> component, the indirect name is looked up exactly as if it had\nbeen there in the original source code, with priority given first to\nleading pseudo-package names, then to names in the lexical scope\n(searching scopes outwards, ending at C<CORE>). The current package is\nsearched last.\n\nUse the C<MY> pseudopackage to limit the lookup to the current lexical scope,\nand C<OUR> to limit the scopes to the current package scope.\n\nIn the same vein, class and method names can be interpolated too:\n\n    role with-method {\n        method a-method { return 'in-a-method of ' ~ $?CLASS.^name  };\n    }\n\n    class a-class does with-method {\n        method another-method { return 'in-another-method' };\n    }\n\n    class b-class does with-method {};\n\n    my $what-class = 'a-class';\n\n    say ::($what-class).a-method; # OUTPUT: «in-a-method of a-class␤»\n    $what-class = 'b-class';\n    say ::($what-class).a-method; # OUTPUT: «in-a-method of b-class␤»\n\n    my $what-method = 'a-method';\n    say a-class.\"$what-method\"(); # OUTPUT: «in-a-method of a-class␤»\n    $what-method = 'another-method';\n    say a-class.\"$what-method\"(); # OUTPUT: «in-another-method␤»\n\n=head2 X<Direct lookup|Syntax,::($c).m>\n\nX<|Syntax,A.\"$m\"()>\nTo do direct lookup in a package's symbol table without scanning, treat the\npackage name as a hash:\n\n=for code :skip-test<error>\nFoo::Bar::{'&baz'}  # same as &Foo::Bar::baz\nPROCESS::<$IN>      # same as $*IN\nFoo::<::Bar><::Baz> # same as Foo::Bar::Baz\n\nUnlike C<::()> symbolic references, this does not parse the argument for C<::>,\nnor does it initiate a namespace scan from that initial point. In addition, for\nconstant subscripts, it is guaranteed to resolve the symbol at compile time.\n\nYou cannot use this kind of direct lookup inside regular expressions, unless you\nissue a C<MONKEY-SEE-NO-EVAL> pragma. The main intention of this measure is to\navoid user input being executed externally.\n\nThe null pseudo-package is the same search list as an ordinary name search.\nThat is, the following are all identical in meaning:\n\n=for code :skip-test<error>\n$foo\n::{'$foo'}\n::<$foo>\n\nEach of them scans the lexical scopes outward, and then the current\npackage scope (though the package scope is then disallowed when `use strict` is\nin effect).\n\n=head2 Package lookup\n\nSubscript the package object itself as a hash object, the key of which is\nthe variable name, including any sigil. The package object can be derived\nfrom a type name by use of the C<::> postfix:\n\n=for code :skip-test<showcasing syntax>\nMyType::<$foo>\n\n=head2 Class member lookup\n\nMethods—including auto-generated methods, such as public attributes'\naccessors—are stored in the class metaobject and can be looked up through by\nthe L<lookup|/routine/lookup> method.\n\n=for code\nStr.^lookup('chars')\n\n=head1 Globals\n\nInterpreter globals live in the C<GLOBAL> package. The user's program\nstarts in the C<GLOBAL> package, so \"our\" declarations in the mainline code\ngo into that package by default. Process-wide variables live in the\nC<PROCESS> package. Most predefined globals such as C<$*UID> and C<$*PID>\nare actually process globals.\n\n=head1 Programmatic use of modules\n\nIt is sometimes useful to be able to programmatically define and use modules.\nHere is a practical example.\n\nAssume we have a series of modules with the module files in a directory\ntree like this:\n\n=begin code :lang<text>\nlib/\n    TomtomMaps/\n        Example/\n            # a directory of example file modules programmatically\n            # created from the Tomtom Maps SDK\n            A01.rakumod\n            #...\n            C09.rakumod\n            #...\n=end code\n\nModule C<TomtomMaps::Example::C09> looks like this:\n\n=begin code :solo\nunit module TomtomMaps::Example::C09;\n\n# ensure you use the 'our' declarator\nour sub print-example($fh, # filehandle open for writing\n                      :$api-maps-key\n) { # do not need to export the sub\n    $fh.print: qq:to/HERE/;\n    # ... the example html file\n    HERE\n}\n=end code\n\nWe can access and use the subroutines like this:\n\n=begin code :solo\nuse lib 'lib';\nmy $module-dir = 'TomtomMaps::Example';\nmy $example    = 'C09';\nmy $m          = \"{$module-dir}::{$example}\";\n\n# you must use the runtime 'require', not the compile-time 'use'\nrequire ::($m);\n\nmy $fh = open \"./example-{$example}.html\", :w;\nmy $api-maps-key = 'ghghfxnnhrgfsWE.mmn';\n\n# execute the subroutine\n&::($m)::print-example($fh, :$api-maps-key); # the map's html file is written\n\n$fh.close;\n=end code\n\n=end pod\n"
  },
  {
    "path": "doc/Language/performance.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Performance\n\n=SUBTITLE Measuring and improving runtime or compile-time performance\n\nThis page is about L<computer performance|https://en.wikipedia.org/wiki/Computer_performance> in the context\nof Raku.\n\n=head1 First, profile your code\n\nB<Make sure you're not wasting time on the wrong code>: start by identifying\nyour L<\"critical 3%\"|https://en.wikiquote.org/wiki/Donald_Knuth> by profiling\nyour code's performance. The rest of this document shows you how to do that.\n\n=head2 Time with C<now - INIT now>\n\nExpressions of the form C<now - INIT now>, where C<INIT> is a L<phase in the\nrunning of a Raku program|/language/phasers>, provide a great idiom for timing\ncode snippets.\n\nUse the C<m: your code goes here> L<#raku channel\nevalbot|/language/glossary#Camelia> to write lines like:\n\n=begin code :lang<irc command>\nm: say now - INIT now\nrakudo-moar abc1234: OUTPUT«0.0018558␤»\n=end code\n\nThe C<now> to the left of C<INIT> runs 0.0018558 seconds I<later> than the\nC<now> to the right of the C<INIT> because the latter occurs during L<the INIT\nphase|/language/phasers#INIT>.\n\n=head2 Profile locally\n\nWhen using the L<MoarVM|https://moarvm.org> backend, the\nL<Rakudo|https://rakudo.org> compiler's C<--profile> command line option writes\nthe profile data to an HTML file.\n\nThis file will open to the \"Overview\" section, which gives some overall data\nabout how the program ran, e.g., total runtime, time spent doing garbage\ncollection. One important piece of information you'll get here is percentage of\nthe total call frames (i.e., blocks) that were interpreted (slowest, in red),\nL<speshed|/language/glossary#Spesh> (faster, in orange), and jitted\n(fastest, in green).\n\nThe next section, \"Routines\", is probably where you'll spend the most time. It\nhas a sortable and filterable table of routine (or block) name+file+line, the\nnumber of times it ran, the inclusive time (time spent in that routine + time\nspent in all routines called from it), exclusive time (just the time spent in\nthat routine), and whether it was interpreted, speshed, or jitted (same color\ncode as the \"Overview\" page). Sorting by exclusive time is a good way to know\nwhere to start optimizing. Routines with a filename that starts like\nC<SETTING::src/core/> or C<gen/moar/> are from the compiler, a good way to just\nsee the stuff from your own code is to put the filename of the script you\nprofiled in the \"Name\" search box.\n\nThe \"Call Graph\" section gives a flame graph representation of much of the same\ninformation as the \"Routines\" section.\n\nThe \"Allocations\" section gives you information about the amount of different\ntypes that were allocated, as well as which routines did the allocating.\n\nThe \"GC\" section gives you detailed information about all the garbage\ncollections that occurred.\n\nThe \"OSR / Deopt\" section gives you information about On Stack Replacements\n(OSRs), which is when routines are \"upgraded\" from interpreted to speshed or\njitted. Deopts are the opposite, when speshed or jitted code has to be\n\"downgraded\" to being interpreted.\n\nIf the profile data is too big, it could take a long time for a browser to open\nthe file. In that case, output to a file with a C<.json> extension using the\nC<--profile=filename> option, then open the file with the\nL<Qt viewer|https://github.com/tadzik/p6profiler-qt>.\n\nTo deal with even larger profiles, output to a file with a C<.sql> extension.\nThis will write the profile data as a series of SQL statements, suitable for\nopening in SQLite.\n\n    =begin code :lang<shell>\n    # create a profile\n    raku --profile=demo.sql -e 'say (^20).combinations(3).elems'\n\n    # create a SQLite database\n    sqlite3 demo.sqlite\n\n    # load the profile data\n    sqlite> .read demo.sql\n\n    # the query below is equivalent to the default view of the \"Routines\" tab in the HTML profile\n    sqlite> select\n          case when r.name = \"\" then \"<anon>\" else r.name end as name,\n          r.file,\n          r.line,\n          sum(entries) as entries,\n          sum(case when rec_depth = 0 then inclusive_time else 0 end) as inclusive_time,\n          sum(exclusive_time) as exclusive_time\n        from\n          calls c,\n          routines r\n        where\n          c.routine_id = r.id\n        group by\n          r.id\n        order by\n          inclusive_time desc\n        limit 30;\n    =end code\n\nThe in-progress, next-gen profiler is L<moarperf|https://github.com/timo/moarperf>, which\ncan accept .sql or SQLite files and has a bunch of new functionality compared to the original\nprofiler. However, it has more dependencies than the relatively stand-alone original profiler,\nso you'll have to install some modules before using it.\n\nTo learn how to interpret the profile info, use the C<prof-m: your code goes\nhere> evalbot (explained above) and ask questions on the IRC channel.\n\n=head2 Profile compiling\n\nIf you want to profile the time and memory it takes to compile your code, use\nRakudo's C<--profile-compile> or C<--profile-stage> options.\n\n=head2 Create or view benchmarks\n\nUse L<perl6-bench|https://github.com/japhb/perl6-bench>.\n\nIf you run perl6-bench for multiple compilers (typically, versions of Perl,\nRaku, or NQP), results for each are visually overlaid on the same graphs,\nto provide for quick and easy comparison.\n\n=head2 Share problems\n\nOnce you've used the above techniques to identify the code to improve,\nyou can then begin to address (and share) the problem with others:\n\n=item For each problem, distill it down to a one-liner or the\ngist and either provide performance numbers or make the snippet small enough\nthat it can be profiled using C<prof-m: your code or gist URL goes here>.\n\n=item Think about the minimum speed increase (or ram reduction or whatever) you\nneed/want, and think about the cost associated with achieving that goal. What's\nthe improvement worth in terms of people's time and energy?\n\n=item Let others know if your Raku use-case is in a production setting or just for fun.\n\n=head1 Solve problems\n\nThis bears repeating: B<make sure you're not wasting time on the wrong code>.\nStart by identifying the L<\"critical 3%\"|https://en.wikiquote.org/wiki/Donald_Knuth>\nof your code.\n\n=head2 Line by line\n\nA quick, fun, productive way to try improve code line-by-line is to collaborate\nwith others using the L<#raku|/language/glossary#IRC> evalbot\nL<camelia|/language/glossary#Camelia>.\n\n=head2 Routine by routine\n\nWith multi-dispatch, you can drop in new variants of routines \"alongside\"\nexisting ones:\n\n    # existing code generically matches a two arg foo call:\n    multi foo(Any $a, Any $b) { ... }\n\n    # new variant takes over for a foo(\"quux\", 42) call:\n    multi foo(\"quux\", Int $b) { ... }\n\nThe call overhead of having multiple C<foo> definitions is generally\ninsignificant (though see discussion of C<where> below), so if your new\ndefinition handles its particular case more efficiently than the previously\nexisting set of definitions, then you probably just made your code that much\nmore efficient for that case.\n\n=head2 Speed up type-checks and call resolution\n\nMost L<C<where> clauses|/language/signatures#Type_constraints> – and thus most\nL<subsets|https://github.com/Raku/old-design-docs/blob/master/S12-objects.pod#Types_and_Subtypes> – force dynamic\n(runtime) type checking and call resolution for any call it I<might> match.\nThis is slower, or at least later, than compile-time.\n\nMethod calls are generally resolved as late as possible (dynamically at runtime),\nwhereas sub calls are generally resolved statically at compile-time.\n\n=head2 Choose better algorithms\n\nOne of the most reliable techniques for making large performance improvements,\nregardless of language or compiler, is to pick a more appropriate algorithm.\n\nA classic example is\nL<Boyer-Moore|https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm>.\nTo match a small string in a large string, one obvious way to do it is to\ncompare the first character of the two strings and then, if they match, compare\nthe second characters, or, if they don't match, compare the first character of\nthe small string with the second character in the large string, and so on. In\ncontrast, the Boyer-Moore algorithm starts by comparing the *last* character of\nthe small string with the correspondingly positioned character in the large\nstring. For most strings, the Boyer-Moore algorithm is close to N times faster\nalgorithmically, where N is the length of the small string.\n\nThe next couple sections discuss two broad categories for algorithmic\nimprovement that are especially easy to accomplish in Raku. For more on this\ngeneral topic, read the wikipedia page on L<algorithmic efficiency|https://en.wikipedia.org/wiki/Algorithmic_efficiency>, especially the\n'See also' section near the end.\n\n=head3 Change sequential/blocking code to parallel/non-blocking\n\nThis is another very important class of algorithmic improvement.\n\nSee the slides for\nL<Parallelism, Concurrency, and Asynchrony in Raku|https://jnthn.net/papers/2015-yapcasia-concurrency.pdf#page=17>\nand/or L<the matching video|https://www.youtube.com/watch?v=JpqnNCx7wVY&list=PLRuESFRW2Fa77XObvk7-BYVFwobZHdXdK&index=8>.\n\n=head2 Use existing high performance code\n\nThere are plenty of high performance C libraries that you can use within Raku and\nL<NativeCall|/language/nativecall> makes it easy to create wrappers for them. There's\nexperimental support for C++ libraries, too.\n\nIf you want to L<use Perl modules in Raku|https://stackoverflow.com/a/27206428/1077672>,\nmix in Raku types and the L<Metaobject Protocol|/language/mop>.\n\nMore generally, Raku is designed to smoothly interoperate with other languages and\nthere are a number of L<modules aimed at facilitating the use of libs from other langs|https://raku.land/?q=inline>.\n\n=head2 Make the Rakudo compiler generate faster code\n\nTo date, the focus for the compiler has been correctness, not\nhow fast it generates code or how fast or lean the code it\ngenerates runs. But that's expected to change, eventually... You\ncan talk to compiler devs on the libera.chat IRC channels #raku and #moarvm about\nwhat to expect. Better still, you can contribute yourself:\n\n=item Rakudo is largely written in Raku. So if you can write Raku, then you\ncan hack on the compiler, including optimizing any of the large body of existing\nhigh-level code that impacts the speed of your code (and everyone else's).\n\n=item Most of the rest of the compiler is written in a small language called\nL<NQP|https://github.com/Raku/nqp> that's basically a subset of Raku. If you\ncan write Raku, you can fairly easily learn to use and improve the mid-level\nNQP code too, at least from a pure language point of view. To dig into NQP and\nRakudo's guts, start with\nL<NQP and internals course|https://edumentab.github.io/rakudo-and-nqp-internals-course/>.\n\n=item If low-level C hacking is your idea of fun, checkout\nL<MoarVM|https://moarvm.org> and visit the libera.chat IRC channel #moarvm\n(L<logs|https://irclogs.raku.org/moarvm/index.html>).\n\n=head2 Still need more ideas?\n\nSome known current Rakudo performance weaknesses not yet covered in this page\ninclude the use of gather/take, junctions, regexes, and string handling in\ngeneral.\n\nIf you think some topic needs more coverage on this page, please submit a PR or\ntell someone your idea. Thanks. :)\n\n=head1 Not getting the results you need/want?\n\nIf you've tried everything on this page to no avail, please consider discussing\nthings with a compiler dev on #raku, so we can learn from your use-case and what\nyou've found out about it so far.\n\nOnce a dev knows of your plight, allow enough time for\nan informed response (a few days or weeks, depending on the exact nature of your\nproblem and potential solutions).\n\nIf I<that> hasn't worked out, please consider filing an issue about your experience at\nL<our user experience repo|https://github.com/Raku/user-experience/issues> before moving on.\n\nThanks. :)\n\n=end pod\n"
  },
  {
    "path": "doc/Language/perl-func.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"migration\")\n\n=TITLE Perl to Raku guide - functions\n\n=SUBTITLE Builtin functions in Perl to Raku\n\n=head1 DESCRIPTION\n\nA (hopefully) comprehensive list of Perl builtin functions with their Raku\nequivalents with notes on variations between them where necessary.\n\n=head1 NOTE\n\nThis document is an\nattempt to guide you from the functions in Perl's C<perlfunc> document to\ntheir equivalents in Raku. For full documentation on the Raku\nfunctions, follow the links in this document to their respective documentation.\n\nOne general comment: Raku takes its objects a lot more seriously than\nPerl. In Raku, everything is an object, although the language is\nflexible enough to not force you to work in an object oriented manner if\nyou do not wish to do so. What this does mean, however, is that a lot of\nthings that are function calls of the form C<function(@args)> are now\nalso method calls of the form C<@args.function> (In rare cases, there is\nI<only> a method call). This should be obvious in the following text,\nbut it probably behooves you to get into that frame of mind now.\n\nAlso, unless otherwise stated, the use of the term \"function\" here will mean a\nfunction in the style of C<func(@args)>, while \"method\" will refer to a\nfunction in the style of C<@args.func>.\n\n=head1 Alphabetical listing of Perl functions\n\n=head2 X<Filetests|Other languages,filetests - perlfunc>\n\n=item -X FILEHANDLE\n\n=item -X EXPR\n\n=item -X DIRHANDLE\n\n=item -X\n\nRaku gives you a couple of options when it comes to file tests. You can do a\nsmartmatch (C<~~>) or you can call a method.\n\nIn Raku, you don't need to actually open a filehandle in the\ntraditional way (although you can) to do a filetest. You can simply append\nC<.IO> to the filename. For instance, here is how to check if a file is\nreadable using smartmatch:\n\n    '/path/to/file'.IO ~~ :r\n\nYou can use an already opened filehandle. Here, using the filehandle\nC<$fh>, is an example, using the method syntax for the file test:\n\n=for code :preamble<my $fh;>\n$fh.r\n\nMost of the former filetests have colon equivalents for use with smartmatch:\n\n=table\n    :e Exists\n    :d Directory\n    :f File\n    :l Symbolic link\n    :r Readable\n    :w Writable\n    :x Executable\n    :s Size\n    :z Zero size\n\nAll of these tests can be used as methods (without the colon).\n\nThree tests, however, I<only> have method equivalents:\n\n=for code :preamble<my $fh;>\n$fh.modified; # -M $fh\n$fh.accessed; # -A $fh\n$fh.changed;  # -C $fh\n\nThe remaining filetests in Perl are not implemented in Raku.\n\nThe documentation for this can be found at\nL<File test operators|/type/IO::Path#File_test_operators>.\n\nThere is more information on reading and writing files at\nL<io|/language/io>. Also, the section on C<open()>\nbelow may be helpful.\n\nThe Raku ecosystem has a module L<C<P5-X>|https://raku.land/zef:lizmat/P5-X>\nwhich exports the behavior as much as possible in Raku.\n\n=head2 X<abs|Other languages,abs - perlfunc>\n\n=item abs VALUE\n\nWorks as a function (C<abs($x)>), but also as a method. One gotcha,\nhowever - method calls bind more tightly than C<->, so, for example,\nC<-15.abs> evaluates as C<-(15.abs)> giving you C<-15>. In this example, you\nwould have to do something like C<(-15).abs>.\n\nC<abs> also operates on C<$_> in the absence of a value, but not as a\nfunction, and as a method you need to call it as C<.abs> rather than simply\nC<abs>.\n\nThe Raku ecosystem has a module L<C<P5math>|https://raku.land/zef:lizmat/P5math>\nwhich exports an C<abs> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<accept|Other languages,accept - perlfunc>\n\n=item accept NEWSOCKET, GENERICSOCKET\n\nC<accept> is a method you can call on a server, e. g.\nC<$server.accept()>. Instead of returning a packed address, it returns a\nsocket, most likely an L<C<IO::Socket>|/type/IO::Socket> object of some sort.\n\n=head2 X<alarm|Other languages,alarm - perlfunc>\n\n=item alarm SECONDS\n\nC<alarm()> is no more.  But it is possible to have code execute after a\ncertain time has elapsed, or at a given time:\n\n  Promise.in(5).then: { say \"five seconds have passed\" }\n\n  Promise.at(now + 5).then: { say \"five seconds have passed\" }\n\nIn Raku, this does I<not> involve any (dummy) signals.\n\n=head2 X<atan2|Other languages,atan2 - perlfunc>\n\n=item atan2 Y, X\n\nAvailable as a function as well as being able to be used as a method.\nFor instance, these are equivalent:\n\n    atan2(100);\n    100.atan2;\n\n=head2 X<bind|Other languages,bind - perlfunc>\n\n=item bind SOCKET, NAME\n\n[NEEDS FURTHER RESEARCH] No sign of a socket-related C<bind()> in Raku. At a\nguess, whatever socket binding is needed happens when you create a new socket\nobject.\n\n=head2 X<binmode|Other languages,binmode - perlfunc>\n\n=item binmode FILEHANDLE\n\nInstead of this, you would use C<:bin> as the file mode when opening the\nsocket. E. g. C<my $fh = open(\"path/to/file\", :bin);>\n\n=head2 X<bless|Other languages,bless - perlfunc>\n\n=item bless REF, CLASSNAME\n\nWith the changes in class creation in Raku, this may find less use\nthan in Perl, and is a method as well as a function. The Raku docs\nsay \"Creates a new object of the same type as the invocant, uses the\nnamed arguments to initialize attributes, and returns the created\nobject.\" If you're porting a module from Perl to Raku, it's quite\npossible you'll want to use C<new> for creating objects rather than\nC<bless>, although there may be some situations in which the latter may\nstill be useful.\n\n=head2 X<break|Other languages,break - perlfunc>\n\n=item break\n\nIt does not exist in Raku. For breaking out of C<given> blocks, you should\nprobably take a look at\nL<C<proceed> and C<succeed>|/language/control#proceed_and_succeed>.\n\n=head2 X<caller|Other languages,caller - perlfunc>\n\n=item caller EXPR\n\nThere are a couple different ways to get at caller information in Raku.\nThe basic functionality is provided through L<callframe|/routine/callframe> now. However, Raku\nconstructs call frames for regular blocks, not just for subroutines, so there\nare more frames to look through. The following will retrieve the basic\ninformation that C<caller> can return:\n\n    my $frame   = callframe(0); # OR just callframe()\n    my ($subroutine, $package);\n    if $frame.code ~~ Routine {\n        $subroutine = $frame.code.name;\n        $package    = $frame.code.package;\n    }\n    my $file    = $frame.file;\n    my $line    = $frame.line;\n\nMany of the other details returned by C<caller> are specific to Perl and have\nno meaning in Raku.\n\nYou can also get some of the information for the current frame or routine frame\nby using the dynamic variables\nL«C<&?ROUTINE>|/language/variables#Compile-time_variables»,\nL«C<&?BLOCK>|/language/variables#Compile-time_variables»,\nL«C<$?PACKAGE>|/language/variables#Compile-time_variables»,\nL«C<$?FILE>|/language/variables#Compile-time_variables», and\nL«C<$?LINE>|/language/variables#Compile-time_variables». For many purposes,\nL<C<Backtrace>|/type/Backtrace> may provide an easier way to browse through the call stack.\n\nThe Raku ecosystem has a module L<C<P5caller>|https://raku.land/zef:lizmat/P5caller>\nwhich exports a C<caller> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<chdir|Other languages,chdir - perlfunc>\n\n=item chdir EXPR\n\nWorks as it does in Perl but B<must> take an argument.  The behavior\nof C<chdir()> (with regards to looking at HOME and LOGDIR) is not supported.\n\nIn Raku, L<chdir|/routine/chdir> only changes the C<$*CWD> dynamic variable.  It does\nB<not> actually change the default directory from the OS's point of view; the\nspecial dynamic-variable routine L«C<&*chdir>|/routine/&*chdir» can be used\nfor that, if needed.\n\nThis is done this way, because there is no concept of a \"default directory\nper OS thread\".  And since Raku does not fork, but only does threading,\nit was felt that the \"current directory\" concept should be in the C<$*CWD>\ndynamic variable, which can be lexically scoped, and thus can be thread-safe.\n\nThe Raku ecosystem has a module L<C<P5chdir>|https://raku.land/zef:lizmat/P5chdir>\nwhich exports a C<chdir> function that mimics the original Perl behavior\nas much as possible, including looking at HOME and LOGDIR.\n\n=head2 X<chmod|Other languages,chmod - perlfunc>\n\n=item chmod LIST\n\nFunctions as under Perl, with the difference that octal numbers are\nrepresented differently (C<0o755> rather than C<0755>). You may also use\nit as a method, e. g. C<$fh.chmod(0o755)>.\n\n=head2 X<chomp|Other languages,chomp - perlfunc>\n\n=item chomp VARIABLE\n\nThe behavior of C<chomp> is different than in Perl. It leaves the\ntarget unaffected and I<returns> a copy of the target with a final logical\nnewline removed, e.g. C<$x = \"howdy\\n\";$y = chomp($x);> results in C<$x>\ncontaining \"howdy\\n\" and C<$y> containing \"howdy\". Also works as a\nmethod, e.g. C<$y = $x.chomp>. As with many other methods, also works\nwith assignment to modify the target in place, e.g. C<$x.=chomp> results\nin C<$x> containing \"howdy\".\n\nNote that C<chomp()> (without arguments) is not supported in Raku.\n\nThe Raku ecosystem has a module L<C<P5chomp>|https://raku.land/zef:lizmat/P5chomp>\nwhich exports a C<chomp> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<chop|Other languages,chop - perlfunc>\n\n=item chop VARIABLE\n\nAs with C<chomp>, in Raku, this returns the chopped string, rather than\nchopping in place. I. e. C<$x = \"howdy\";$y = chop($x);> results in C<$x>\nbeing \"howdy\" and C<$y> being \"howd\". Also works as a method: C<$y = $x.chop>.\n\nNote that C<chop()> (without arguments) is not supported in Raku.\n\nThe Raku ecosystem has a module L<C<P5chomp>|https://raku.land/zef:lizmat/P5chomp>\nwhich exports a C<chop> function that mimics the original Perl behavior\nas much as possible.\n\n.head2 chown\n\n=item chown LIST\n\nC<chown> is not in Raku.\n\n=head2 X<chr|Other languages,chr - perlfunc>\n\n=item chr NUMBER\n\nSimilar to the Perl version, coerces the target to an integer, and uses that\nas a Unicode code point to return the relevant character. Can be used as a\nfunction and a method:\n\n    chr(65); # \"A\"\n    65.chr;  # \"A\"\n\nNote that C<chr()> (without arguments) is not supported in Raku.\n\nThe Raku ecosystem has a module L<C<P5chr>|https://raku.land/zef:lizmat/P5chr>\nwhich exports a C<chr> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<chroot|Other languages,chroot - perlfunc>\n\n=item chroot FILENAME\n\nC<chroot> is not in Raku.\n\n=head2 X<close|Other languages,close - perlfunc>\n\n=item close FILEHANDLE\n\nAs in Perl, closes a filehandle. Returns a Boolean value. Both C<close\n$fh> and C<$fh.close> will work.\n\nNote that C<close()> (without arguments) is not supported in Raku.\n\n=head2 X<closedir|Other languages,closedir - perlfunc>\n\n=item closedir DIRHANDLE\n\nNot supported in Raku.\n\nThe Raku ecosystem has a module L<C<P5opendir>|https://raku.land/zef:lizmat/P5opendir>\nwhich exports a C<closedir> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<connect|Other languages,connect - perlfunc>\n\n=item connect SOCKET, NAME\n\nUse L<connect|/routine/connect> from L<C<IO::Socket::Async>|/type/IO::Socket::Async> for\nan asynchronous socket or create an L<C<IO::Socket::INET>|/type/IO::Socket::INET> socket\nfor a synchronous one.\n\n=head2 X<continue|Other languages,continue - perlfunc>\n\n=item continue BLOCK\n\n=item continue\n\nInstead of a C<continue> block, you should use a C<NEXT> block. The\nclosest analog to a bare C<continue;> in Perl appears to be\nC<proceed>/C<succeed>.\n\n=head2 X<cos|Other languages,cos - perlfunc>\n\n=item cos EXPR\n\nWorks as in Perl.\n\nC<cos> also operates on C<$_> in the absence of a value, but not as a\nfunction, and as a method you need to call it as C<.cos> rather than simply\nC<cos>.\n\nThe Raku ecosystem has a module L<C<P5math>|https://raku.land/zef:lizmat/P5math>\nwhich exports a C<cos> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<crypt|Other languages,crypt - perlfunc>\n\n=item crypt PLAINTEXT, SALT\n\nNot available in Raku.\n\nThe Raku ecosystem has a module L<C<P5math>|https://raku.land/zef:lizmat/P5math>\nwhich exports a C<crypt> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<dbm functions|Other languages,dbm - perlfunc>\n\n=item dbmclose HASH\n\n=item dbmopen HASH, DBNAME, MASK\n\nThese functions have largely been superseded in Perl, and are unlikely to\never turn up in Raku.\n\n=head2 X<defined|Other languages,defined - perlfunc>\n\n=item defined EXPR\n\nProbably does what you expect, but technically it returns C<False> on\nthe type object, and C<True> otherwise. This may make more sense when\nyou realize that C<$num.raku> is the type L<C<Any>|/type/Any> if you haven't assigned\nanything to it, and the assigned value if you have. It can be\nused as a method: C<$num.defined>.  And any newly created class can have\nits own C<.defined> method, thereby deciding how and when it should be\nconsidered undefined.\n\nNote that C<defined()> (without arguments) is not supported in Raku.\n\nThe Raku ecosystem has a module L<C<P5defined>|https://raku.land/zef:lizmat/P5defined>\nwhich exports a C<defined> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<delete|Other languages,delete - perlfunc>\n\n=item delete EXPR\n\nRaku replaces this with the new adverb syntax, specifically the\nC<:delete> adverb. E. g. C<my $deleted_value = %hash{$key}:delete;> and\nC<my $deleted_value = @array[$i]:delete;>.\n\n=head2 X<die|Other languages,die - perlfunc>\n\n=item die LIST\n\nWorks similarly to the Perl version, but Raku's Exception mechanism\nmay give you more power and flexibility than is available in Perl.\nSee L<exceptions|/language/exceptions>. To omit the stacktrace\nand location, like Perl's C<die \"...\\n\">, use:\n\n    note \"...\";\n    exit 1;\n\n=head2 X<do|Other languages,do - perlfunc>\n\n=item do BLOCK\n\nSimilar to the Perl version. Note that there must be a space between the\nC<do> and the block.\n\n=item do EXPR\n\nHas been replaced in Raku by C<EVALFILE>.\n\n=head2 X<dump|Other languages,dump - perlfunc>\n\n=item dump LABEL\n\nAccording to S29, C<dump> has been... dumped.\n\n=head2 X<each|Other languages,each - perlfunc>\n\n=item each HASH\n\nThere is no exact equivalent, because in Raku Hashes are composed of Pair objects.\nYou can use C<%hash.kv> which\nreturns a list of keys and values. example:\nC«for %hash.kv -> $k, $v { say \"$k: $v\" }».\nHowever Raku offers more possibilities, C<%hash.pairs> gives you each Pair object as\nan entity, and C<%hash.antipairs> does the same with the keys and values reversed.\n\nIncidentally, what we have there with the C«->» is called a pointy\nblock and, though there are a number of examples in the documentation,\nthere doesn't seem to be a really clear explanation of how they work.\nL<https://github.com/Raku/old-design-docs/blob/master/S04-control.pod#The_for_statement> may be of some\nhelp here, as well as the design document at\nL<https://github.com/Raku/old-design-docs/blob/master/S06-routines.pod#%22Pointy_blocks%22>. There is also\nsome information at L<https://en.wikibooks.org/wiki/Perl_6_Programming/Blocks_and_Closures#Pointy_Blocks>\n\nThe Raku ecosystem has a module L<C<P5each>|https://raku.land/zef:lizmat/P5each>\nwhich exports an C<each> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<eof|Other languages,eof - perlfunc>\n\n=item eof FILEHANDLE\n\nIn Raku, this is not usable as a function, but only as a method. I. e.\nC<$filehandle.eof>. Returns C<True> if at end of file.\n\n=head2 X<eval|Other languages,eval - perlfunc>\n\n=item eval EXPR\n\n=item eval EXPR\n\nThe closest replacement is the L<EVAL|/routine/EVAL> function. However,\nthis function has to be allowed explicitly using a pragma to work in the\nsame way. Note that C<EVAL> does not do any L<exception\nhandling|/language/exceptions>!\n\n=head2 X<evalbytes|Other languages,evalbytes - perlfunc>\n\n=item evalbytes EXPR\n\nNo equivalent.\n\n=head2 X<exec|Other languages,exec - perlfunc>\n\n=item exec LIST\n\nNothing in Raku exactly replicates the Perl C<exec>. C<shell> and\nC<run> are similar to Perl's C<system>, but C<exec>'s behavior of not\nreturning after executing a system command would have to be emulated by\nsomething like C<shell($command);exit();> or possibly C<exit\nshell($command);>.\n\nNeither of these workarounds have the behavior (on Unix-like systems)\nof I<replacing> your Perl program's process with the new program;\nnotably, they will not work for the practice in some long-running\ndaemons of periodically redoing exec on themselves to reset their state\nor force operating-system cleanup. Nor will they serve C<exec>'s\nfunction of returning stale resources to the operating system.\n\nIf you want C<exec> for these behaviors, you can use an C<exec*>\nfunction via the C<NativeCall> interface. Consult your operating\nsystem manual pages for C<exec> (or other similarly-named calls such\nas C<execl>, C<execv>, C<execvp>, or C<execvpe>). (Beware: these calls\nare not generally portable between Unix-like operating system\nfamilies.)  Given those caveats, the Raku ecosystem\nL<C<Native::Exec>|https://raku.land/cpan:CTILMES/Native::Exec> module\nexports an C<exec> function for Unix-like systems.\n\n=head2 X<exists|Other languages,exists - perlfunc>\n\n=item exists EXPR\n\nIn Raku, this is not a function, but an adverb:\n\n=for code :preamble<no strict;>\n%hash{$key}:exists;\n@array[$i]:exists;\n\n=head2 X<exit|Other languages,exit - perlfunc>\n\n=item exit EXPR\n\nAppears to do the same thing as in Perl.\n\n=head2 X<exp|Other languages,exp - perlfunc>\n\n=item exp EXPR\n\nSame as in Perl.\n\nC<exp> also operates on C<$_> in the absence of a value, but not as a\nfunction, and as a method you need to call it as C<.exp> rather than simply\nC<exp>.\n\nThe Raku ecosystem has a module L<C<P5math>|https://raku.land/zef:lizmat/P5math>\nwhich exports an C<exp> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<fc|Other languages,fc - perlfunc>\n\n=item fc EXPR\n\nLooks like it does the same thing as in Perl except that calling it without\narguments is not supported in Raku.\n\nThe Raku ecosystem has a module L<C<P5fc>|https://raku.land/zef:lizmat/P5fc>\nwhich exports a C<fc> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<fcntl|Other languages,fcntl - perlfunc>\n\n=item fcntl FILEHANDLE, FUNCTION, SCALAR\n\nAppears not to be in Raku.\n\n=head2 X<__FILE__|Other languages,__FILE__ - perlfunc>\n\n=item __FILE__\n\nReplaced by C<$?FILE> which is slightly different from C<__FILE__> in that\nit is always an absolute path, rather than a relative one in the Perl case.\n\nThe Raku ecosystem has a module L<C<P5__FILE__>|https://raku.land/zef:lizmat/P5__FILE__>\nwhich exports a C<__FILE__> term that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<fileno|Other languages,fileno - perlfunc>\n\n=item fileno FILEHANDLE\n\nThe C<native-descriptor> method on L<C<IO::Handle>|/type/IO::Handle> returns the equivalent of\nC<fileno>.\n\nThe Raku ecosystem has a module L<C<P5fileno>|https://raku.land/zef:lizmat/P5fileno>\nwhich exports a C<fileno> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<flock|Other languages,flock - perlfunc>\n\n=item flock FILEHANDLE, OPERATION\n\nCurrently unimplemented.\n\n=head2 X<fork|Other languages,fork - perlfunc>\n\n=item fork\n\nThere is no built-in C<fork> function. While it's possible to call it using\nNativeCall, it's highly unlikely that the resulting process will be usable.\n\nRaku provides extensive support for, and internally uses, threads. However,\nC<fork> only clones the thread that called C<fork>, resulting in a process that\nwill be missing its other threads, which will have been in unknown states and\nprobably holding locks. Even if a Raku program doesn't knowingly start any\nthreads, the compiler may create some of its own in the process of precompilation,\nand the VMs that Raku runs on also create their own internal worker threads for\ndoing things like optimization and GC in the background. Thus, the presence of\nthreads is pretty much assured, and there's no reasonable way to make C<fork>\nreliably work in this case.\n\n=head2 X<formats|Other languages,formats - perlfunc>\n\n=item format\n\n=item formline PICTURE, LIST\n\nRaku does not have built-in formats.\n\n=head2 X<getc|Other languages,getc - perlfunc>\n\n=item getc FILEHANDLE\n\nReads a single character from the input stream as in Perl. May now\nalso be used as a method: C<$filehandle.getc>\n\n=head2 X<getpeername|Other languages,getpeername - perlfunc>\n\n=item getpeername SOCKET\n\nOriginally speculated in S29, but not implemented in Raku.\n\n=head2 X<getpgrp|Other languages,getpgrp - perlfunc>\n\n=item getpgrp PID\n\nWill not be implemented.\n\nThe Raku ecosystem has a module L<C<P5getpriority>|https://raku.land/zef:lizmat/P5getpriority>\nwhich exports a C<getpgrp> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<getppid|Other languages,getppid - perlfunc>\n\n=item getppid PID\n\nWill not be implemented.\n\nThe Raku ecosystem has a module L<C<P5getpriority>|https://raku.land/zef:lizmat/P5getpriority>\nwhich exports a C<getppid> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<getpriority|Other languages,getpriority - perlfunc>\n\n=item getpriority WHICH, WHO\n\nWill not be implemented.\n\nThe Raku ecosystem has a module L<C<P5getpriority>|https://raku.land/zef:lizmat/P5getpriority>\nwhich exports a C<getpriority> function that mimics the original Perl\nbehavior as much as possible.\n\n=head2 X<get and set functions|Other languages,get and set - perlfunc>\n\n=item endpwent\n\n=item getlogin\n\n=item getpwent\n\n=item getpwnam NAME\n\n=item getpwuid UID\n\n=item setpwent\n\nThe Raku ecosystem has a module L<C<P5getpwnam>|https://raku.land/zef:lizmat/P5getpwnam>\nwhich exports the C<endpwent>, C<getlogin>, C<getpwent>, C<getpwnam>,\nC<getpwuid> and C<setpwent> functions that mimic the original Perl behavior\nas much as possible.\n\n=item endgrent\n\n=item getgrent\n\n=item getgrgid GID\n\n=item getgrnam NAME\n\n=item setgrent\n\nThe Raku ecosystem has a module L<C<P5getgrnam>|https://raku.land/zef:lizmat/P5getgrnam>\nwhich exports the C<endgrent>, C<getgrent>, C<getgrgid>, C<getgrnam> and\nC<setgrent> functions that mimic the original Perl behavior as much as\npossible.\n\n=item endnetent\n\n=item getnetbyaddr ADDR, ADDRTYPE\n\n=item getnetbyname NAME\n\n=item getnetent\n\n=item setnetent STAYOPEN\n\nThe Raku ecosystem has a module L<C<P5getnetbyname>|https://raku.land/zef:lizmat/P5getnetbyname>\nwhich exports the C<endnetent>, C<getnetent>, C<getnetbyaddr>, C<getnetbyname>\nand C<setnetent> functions that mimic the original Perl behavior as much as\npossible.\n\n=item endservent\n\n=item getservbyname NAME, PROTO\n\n=item getservbyport PORT, PROTO\n\n=item getservent\n\n=item setservent STAYOPEN\n\nThe Raku ecosystem has a module L<C<P5getservbyname>|https://raku.land/zef:lizmat/P5getservbyname>\nwhich exports the C<endservent>, C<getservent>, C<getservbyname>,\nC<getservbyport> and C<setservent> functions that mimic the original Perl\nbehavior as much as possible.\n\n=item endprotoent\n\n=item getprotobyname NAME\n\n=item getprotobynumber NUMBER\n\n=item getprotoent\n\n=item setprotoent STAYOPEN\n\nThe Raku ecosystem has a module L<C<P5getprotobyname>|https://raku.land/zef:lizmat/P5getprotobyname>\nwhich exports the C<endprotoent>, C<getprotoent>, C<getprotobyname>,\nC<getprotobynumber> and C<setprotoent> functions that mimic the original\nPerl behavior as much as possible.\n\n=item gethostbyname NAME\n\n=item gethostbyaddr ADDR, ADDRTYPE\n\n=item gethostent\n\n=item sethostent STAYOPEN\n\n=item endhostent\n\n[NEEDS FURTHER RESEARCH] Apparently this range of functions are to be handled\nby roles like User, Group, etc.\n\n=head2 X<getsock*|Other languages,getsock - perlfunc>\n\n=item getsockname SOCKET\n\n=item getsockopt SOCKET, LEVEL, OPTNAME\n\n[NEEDS FURTHER RESEARCH] These are likely implemented by some kind of\nL<C<IO::Socket>|/type/IO::Socket> object, but details are unclear.\n\n=head2 X<glob|Other languages,glob - perlfunc>\n\n=item glob EXPR\n\nNot available in core, although some of the functionality is offered by\nL<dir|/routine/dir> routine and its C<test> argument.\n\nSee L«C<IO::Glob> module in ecosystem|https://raku.land/cpan:HANENKAMP/IO::Glob»\n\n=head2 X<gmtime|Other languages,gmtime - perlfunc>\n\n=item gmtime EXPR\n\nLike the various parts of C<localtime>, C<gmtime>'s functionality\nappears to in the L<C<DateTime>|/type/DateTime> object. To get a UTC version of a\nL<C<DateTime>|/type/DateTime> object for the current time, for instance, use C<my $gmtime\n= DateTime.now.utc>.\n\nThe Raku ecosystem has a module L<C<P5localtime>|https://raku.land/zef:lizmat/P5localtime>\nwhich exports a C<gmtime> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<goto|Other languages,goto - perlfunc>\n\n=item goto LABEL\n\n=item goto EXPR\n\n=item goto &NAME\n\nThe syntax for C<goto LABEL> is already accepted, but the runtime part of\nC<goto> is not yet implemented.  So this will result in a runtime error:\n\n    FOO: goto FOO; # Label.goto() not yet implemented. Sorry.\n\n=head2 X<grep|Other languages,grep - perlfunc>\n\n=item grep BLOCK LIST\n\n=item grep EXPR, LIST\n\nStill in Raku, with the caveat that the block form now requires a\ncomma after the block. I.e. C<@foo = grep { $_ = \"bars\" }, @baz>. Can\nalso be used as a method: C<@foo = @bar.grep(/^f/)>\n\n=head2 X<hex|Other languages,hex - perlfunc>\n\n=item hex EXPR\n\nIn Raku an expression B<must> be specified.\n\nReplaced by the adverbial form C<:16>. E. g. C<:16(\"aF\")> returns 175. This is\nStr->Int.\n\nThe opposite result can be achieved (Int->Str) by using the C<.base> method:\nC<0xaF.base(10)>\n\nIt just so happens that C<.Str> defaults to base 10, so if you just C<say\n0xaF>, that will also print 175, but that may not be immediately obvious, so\nmay not be the best way to go for this.\n\nThe Raku ecosystem has a module L<C<P5hex>|https://raku.land/zef:lizmat/P5hex>\nwhich exports a C<hex> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<import|Other languages,import - perlfunc>\n\n=item import LIST\n\nWas never a builtin function in Perl in the first place. In Raku,\ntypically, one declares functions as exportable or not, and all the\nexportable ones are exported. Nevertheless, selective importing is\npossible, but beyond the scope of this document. For details, see\nL<this section|/language/perl-nutshell#Importing_specific_functions_from_a_module>.\n\n=head2 X<index|Other languages,index - perlfunc>\n\n=item index STR, SUBSTR, POSITION\n\nWorks as in Perl. Can also now be used as a method:\nC<\"howdy!\".index(\"how\"); # 0>.  Main difference with Perl is that L<C<Nil>|/type/Nil> is\nreturned instead of C<-1> when the substring is not found.  This is very\nuseful in combination with the C<with> command:\n\n    with index(\"foo\",\"o\") -> $index {\n        say \"Found it at $index\";\n    }\n    else {\n        say \"Not found\"\n    }\n\nThe Raku ecosystem has a module L<C<P5index>|https://raku.land/zef:lizmat/P5index>\nwhich exports an C<index> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<int|Other languages,int - perlfunc>\n\n=item int EXPR\n\nThere is a C<truncate> function in Raku (also usable as a method) that\ndoes what Perl's C<int> does. You may want to use that as a direct\ntranslation of Perl code, but in Raku, you can just as easily call\nthe C<.Int> method on the number. C<3.9.Int; # 3> and C<3.9.truncate>\nare equivalent.\n\nPlease note that C<int> B<does> have a meaning in Raku.  It is type that\ncan be used to indicate a native integer:\n\n    my int $a = 42;   # a native integer, similar to Perl's integer values\n\nC<int> also operates on C<$_> in the absence of a value, but not as a\nfunction, and as a method you need to call it as C<.int> rather than simply\nC<int>.\n\nThe Raku ecosystem has a module L<C<P5math>|https://raku.land/zef:lizmat/P5math>\nwhich exports an C<int> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<ioctl|Other languages,ioctl - perlfunc>\n\n=item ioctl FILEHANDLE, FUNCTION, SCALAR\n\nCurrently unimplemented in Raku.\n\n=head2 X<join|Other languages,join - perlfunc>\n\n=item join EXPR, LIST\n\nWorks as in Perl, and also works as a method: C<@x.join(\",\")>\n\n=head2 X<keys|Other languages,keys - perlfunc>\n\n=item keys HASH\n\nWorks as in Perl, and can also be used as a method: C<%hash.keys>\n\n=head2 X<kill|Other languages,kill - perlfunc>\n\n=item kill SIGNAL, LIST\n\n=item kill SIGNAL\n\nNo pre-defined core alternative exists. A non-portable method can be to use\nL<NativeCall|/language/nativecall>:\n\n    use NativeCall;\n    sub kill(int32, int32) is native {*};\n    kill $*PID, 9; # OUTPUT: «Killed␤»\n\nTo kill processes that were started by creating a L<C<Proc::Async>|/type/Proc::Async>, use\nL«C<Proc::Async.kill> method|/type/Proc::Async#method_kill».\n\n=head2 X<last|Other languages,last - perlfunc>\n\n=item last LABEL\n\n=item last EXPR\n\n=item last\n\nSame as in Perl.\n\n=head2 X<lc|Other languages,lc - perlfunc>\n\n=item lc EXPR\n\nWorks as in Perl, and also as a method: C<\"UGH\".lc>.  In Raku an\nexpression B<must> be specified.\n\nThe Raku ecosystem has a module L<C<P5lc>|https://raku.land/zef:lizmat/P5lc>\nwhich exports an C<lc> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<lcfirst|Other languages,lcfirst - perlfunc>\n\n=item lcfirst EXPR\n\nDoes not exist in Raku.\n\nThe Raku ecosystem has a module L<C<P5lcfirst>|https://raku.land/zef:lizmat/P5lcfirst>\nwhich exports an C<lcfirst> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<length|Other languages,length - perlfunc>\n\n=item length EXPR\n\nReplaced by C<chars>, typically used as a method (C<$string.chars>), but\nalso works as a function.\n\nThe Raku ecosystem has a module L<C<P5length>|https://raku.land/zef:lizmat/P5length>\nwhich exports a C<length> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<__LINE__|Other languages,__LINE__ - perlfunc>\n\n=item __LINE__\n\nReplaced by C<$?LINE>.\n\nThe Raku ecosystem has a module L<C<P5__FILE__>|https://raku.land/zef:lizmat/P5__FILE__>\nwhich exports a C<__LINE__> term that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<link|Other languages,link - perlfunc>\n\n=item link OLDFILE, NEWFILE\n\nSee L<link|/routine/link>\n\n=head2 X<listen|Other languages,listen - perlfunc>\n\n=item listen SOCKET, QUEUESIZE\n\nNot clearly documented, but it appears that C<listen> will be a method\nyou would call on some variety of L<C<IO::Socket>|/type/IO::Socket> object.\n\n=head2 X<local|Other languages,local - perlfunc>\n\n=item local EXPR\n\nThe Raku equivalent is C<temp>. Unlike C<local>, however, the value of\nthe given variable is not immediately unset: it retains its original value\nuntil assigned to.\n\n=head2 X<localtime|Other languages,localtime - perlfunc>\n\n=item localtime EXPR\n\nMost of the functionality of C<localtime> is found in L<C<DateTime>|/type/DateTime>. The\nspecific parts of C<localtime> can be found as follows:\n\n=begin code\n\nmy $d = DateTime.now;\nmy $sec  = $d.second; # Potentially includes fractional seconds\nmy $min  = $d.minute;\nmy $hour = $d.hour;\nmy $mday = $d.day-of-month; # or $d.day; 1..31\nmy $mon  = $d.month; # 1..12\nmy $year = $d.year;\nmy $wday = $d.day-of-week; # 1 => Monday, 2 => Tuesday, etc.\nmy $yday = $d.day-of-year; # 1..366\n=end code\n\nPlease note that ranges are not 0-based in Raku, as shown in the\ncomments in the example.\n\nThere does not currently appear to be a way to get Perl's\nC<$isdst>. Also, the result of C<scalar(localtime)> that Perl\nprovides is not available. C<$d.Str> will give something along the\nlines of \"2015-06-29T12:49:31-04:00\".\n\nThe Raku ecosystem has a module L<C<P5localtime>|https://raku.land/zef:lizmat/P5localtime> which exports a C<localtime> function that mimics the original\nPerl behavior as much as possible.\n\n=head2 X<lock|Other languages,lock - perlfunc>\n\n=item lock THING\n\nThere currently is no equivalent for this In Raku.  There is a L<C<Lock>|/type/Lock>\nclass for creating a Lock object, that can be locked/unlocked as needed.\nBut such a lock does not refer to any external objects.\n\n=head2 X<log|Other languages,log - perlfunc>\n\n=item log EXPR\n\nSame as in Perl.\n\nC<log> also operates on C<$_> in the absence of a value, but not as a\nfunction, and as a method you need to call it as C<.log> rather than simply\nC<log>.\n\nThe Raku ecosystem has a module L<C<P5math>|https://raku.land/zef:lizmat/P5math>\nwhich exports a C<log> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<lstat|Other languages,lstat - perlfunc>\n\n=item lstat FILEHANDLE\n\n=item lstat EXPR\n\n=item lstat DIRHANDLE\n\n=item lstat\n\nLikely implemented somewhere in one of the L<C<IO>|/type/IO> classes in Raku, but\nit is not clear where at this time.\n\n=head2 X<m//|Other languages,m// - perlfunc>\n\n=item m//\n\nRegular expression syntax is somewhat different in Raku, but the match\noperator still exists. If you're trying to rewrite some Perl code, the\nmost important difference is that C<=~> is replaced by the smartmatch\noperator, C<~~>. Similarly, C<!~> is replaced by C<!~~>. Options for\nregex operators are adverbs and are complicated. For details, see\nL<Adverbs|/language/regexes#Adverbs>\n\n=head2 X<map|Other languages,map - perlfunc>\n\n=item map BLOCK LIST\n\n=item map EXPR, LIST\n\nAs a function, the only difference between Perl and Raku is that, if\nyou're using a block, the block must be followed by a comma. Can also be\nused as a method: C<@new = @old.map: { $_ * 2 }>\n\nSince flattening doesn't work exactly the same, it may be necessary to\nflatten the arrays as well: C<my @combined = map { $_ ~ ' b' }, |@old1, |@old2>.\nThis also means that it's possible to do things like:\nC<@counts = map { .elems }, @old1, @old2>.\n\n=head2 X<mkdir|Other languages,mkdir - perlfunc>\n\n=item mkdir FILENAME, MASK\n\n=item mkdir FILENAME\n\nWorks as in Perl.  When giving a multi-level directory specification,\nit will automatically create non-existing intermediate directories with\nthe same MASK (similar to what \"make_path\" does of the File::Path module\nin Perl).\n\n=item mkdir\n\nThe zero argument (implicit C<$_>) version is not permitted in Raku.\n=head2 X<msg*|Other languages,msg* - perlfunc>\n\n=item msgctl ID, CMD, ARG\n\n=item msgget KEY, FLAGS\n\n=item msgrcv ID, VAR, SIZE, TYPE, FLAGS\n\n=item msgsnd ID, MSG, FLAGS\n\nNot builtins in Raku. May appear in an external module at some point. Maybe.\n=head2 X<my|Other languages,my - perlfunc>\n\n=item my VARLIST\n\n=item my TYPE VARLIST\n\n=item my VARLIST : ATTRS\n\n=item my TYPE VARLIST : ATTRS\n\nWorks as in Perl.\n=head2 X<next|Other languages,next - perlfunc>\n\n=item next LABEL\n\n=item next EXPR\n\n=item next\n\nThe same in Raku.\n\n=head2 X<no|Other languages,no - perlfunc>\n\n=item no MODULE VERSION\n\n=item no MODULE LIST\n\n=item no MODULE\n\n=item no VERSION\n\nIn Raku, this is usable for pragmas such as C<strict>, but not for\nmodules or versions.\n\n=head2 X<oct|Other languages,oct - perlfunc>\n\n=item oct\n\nReplaced by the adverbial form C<:8>. E. g. C<:8(\"100\")> returns 64.\n\nIf you want to deal with strings that start in C<0x>, C<0o>, or C<0b>,\nyou can just use the C«prefix:<+>» operator.\n\nThe Raku ecosystem has a module L<C<P5hex>|https://raku.land/zef:lizmat/P5hex>\nwhich exports an C<oct> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<open|Other languages,open - perlfunc>\n\n=item open FILEHANDLE, EXPR\n\n=item open FILEHANDLE, MODE, EXPR\n\n=item open FILEHANDLE, MODE, EXPR, LIST\n\n=item open FILEHANDLE, MODE, REFERENCE\n\n=item open FILEHANDLE\n\nThe most obvious change from Perl is the file mode syntax. To open a\nfile for reading only, you would say C<open(\"file\", :r)>. For write-\nonly, read-write, and append, you would use C<:w>, C<:rw>, and C<:a>\nrespectively. There are also options for encoding and how the filehandle\ndeals with newlines. Details L<here|/routine/open>.\n\nAnother important change is that filehandles don't get automatically closed on scope exit. It's necessary to call L<close|/routine/close> explicitly.\n\n=head2 X<opendir|Other languages,opendir - perlfunc>\n\n=item opendir DIRHANDLE, EXPR\n\nNo replacement. See L«C<&dir>/C<IO::Path.dir>|/routine/dir» for alternatives.\n\nThe Raku ecosystem has a module L<C<P5opendir>|https://raku.land/zef:lizmat/P5opendir>\nwhich exports an C<opendir> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<ord|Other languages,ord - perlfunc>\n\n=item ord EXPR\n\nSame as in Perl. May be used as a method: C<\"howdy!\".ord; # 104>\n\nNote that C<ord()> (without arguments) is not supported in Raku.\n\nThe Raku ecosystem has a module L<C<P5chr>|https://raku.land/zef:lizmat/P5chr>\nwhich exports an C<ord> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<our|Other languages,our - perlfunc>\n\n=item our VARLIST\n\n=item our TYPE VARLIST\n\n=item our VARLIST : ATTRS\n\n=item our TYPE VARLIST : ATTRS\n\nThe same in Raku.\n\n=head2 X<pack|Other languages,pack - perlfunc>\n\n=item pack TEMPLATE, LIST\n\nAvailable in Raku when C<use experimental :pack> has been specified in the\nscope where C<pack> needs to be called. The template options are currently\nmore restricted than they are in Perl. The current documented list can be\nfound at L<unpack|/routine/unpack>.\n\nThe Raku ecosystem has a module L<C<P5pack>|https://raku.land/zef:lizmat/P5pack>\nwhich exports a C<pack> function that mimics the original Perl behavior as\nmuch as possible and which has a bigger set of supported features than the\nexperimental Raku version.\n\n=head2 X<package|Other languages,package - perlfunc>\n\n=item package NAMESPACE\n\n=item package NAMESPACE VERSION\n\n=item package NAMESPACE BLOCK\n\n=item package NAMESPACE VERSION BLOCK\n\nS10 indicates that C<package> can be used in Raku, but only with a\nblock. I. e. C<package Foo { ... }> means that the code within the block\nwould be in package Foo. There is a special case where a declaration of\nthe form C<package Foo;> as the first statement in a file indicates that\nthe rest of the file is Perl code, but the usefulness of this is\nunclear. In fact, as modules and classes are declared with distinct\nkeywords (such as C<class>), it's unlikely you will use C<package>\ndirectly in Raku.\n\n=head2 X<__PACKAGE__|Other languages,__PACKAGE__ - perlfunc>\n\n=item __PACKAGE__\n\nReplaced by C<$?PACKAGE> which is slightly different from C<__PACKAGE__> in\nthat it is the actual package object.  You should call the C<.^name> method\non it to get a string.\n\nThe Raku ecosystem has a module L<C<P5__FILE__>|https://raku.land/zef:lizmat/P5__FILE__>\nwhich exports a C<__PACKAGE__> term that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<pipe|Other languages,pipe - perlfunc>\n\n=item pipe READHANDLE, WRITEHANDLE\n\nDepending on your needs, see L«C<Channel>|/type/Channel» to shuttle\ndata between threads (and L<Concurrency tutorial|/language/concurrency>\nfor other options), or see L«C<Proc>|/type/Proc» type for piping to\nand from processes.\n\n=head2 X<pop|Other languages,pop - perlfunc>\n\n=item pop ARRAY\n\nWorks in Raku, and can also be used as a method. I. e. C<my $x = pop\n@a;> and C<my $x = @a.pop;> are equivalent.\n\nThe non-parameter version of C<pop> does not exist.  Also, if the array\nis empty, a Failure will be returned in Raku, which will throw if the\nvalue is actually used in a significant way.\n\nIf you are using only defined values in your array, you can use the C<with>\nfunction to handle this case:\n\n=for code :preamble<my @array;>\nwith pop @array -> $popped {\n    say \"popped '$popped' of the array\";\n}\nelse {\n    say \"there was nothing to pop\";\n}\n\nThe Raku ecosystem has a module L<C<P5push>|https://raku.land/zef:lizmat/P5push>\nwhich exports a C<pop> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<pos|Other languages,pos - perlfunc>\n\n=item pos SCALAR\n\nNot available in Raku. The closest equivalent is the C<:c> adverb,\nwhich defaults to C<$/.to> if C<$/> is true, and C<0> if it isn't. For\ninformation on C<:c>, see\nL<Continue|/language/regexes#Continue>.\n\n=head2 X<print|Other languages,print - perlfunc>\n\n=item print FILEHANDLE LIST\n\n=item print FILEHANDLE\n\n=item print LIST\n\n=item print\n\nC<print> can be used as a function in Raku, writing to standard\nout. To use C<print> as a function with a filehandle I<instead> of\nstandard out, you can use a method call: C<$fh.print(\"howdy!\")>\n\nThe Raku ecosystem has a module L<C<P5print>|https://raku.land/zef:lizmat/P5print>\nwhich exports a C<print> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<printf|Other languages,printf - perlfunc>\n\n=item printf FORMAT, LIST\n\n=item printf\n\nRaku version is similar; see\nL<sprintf|/routine/sprintf> for details\non acceptable format directives. To print to a filehandle other than\nSTDOUT, use the L«C<.printf>|/routine/printf» method on that filehandle.\n\nThe Raku ecosystem has a module L<C<P5print>|https://raku.land/zef:lizmat/P5print>\nwhich exports a C<printf> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<prototype|Other languages,prototype - perlfunc>\n\n=item prototype FUNCTION\n\nNot available in Raku. The closest equivalent is\nC<.signature>. E. g. C<say &sprintf.signature> results in \"(Cool\n$format, *@args)\".\n\n=head2 X<push|Other languages,push - perlfunc>\n\n=item push ARRAY, LIST\n\nWorks as in Perl, as well as being available as a method:\nC<@a.push(\"foo\");>. I<Note:> the flattening behavior is different in Raku:\nC<@b.push: @a> will push C<@a> into C<@b> as a single element. See also the\nL<append method|/type/Array#method_append>.\n\nAlso note that C<push> in Raku returns the array to which was pushed,\ncontrary to Perl where it returns the new number of elements.\n\nThe Raku ecosystem has a module L<C<P5push>|https://raku.land/zef:lizmat/P5push>\nwhich exports a C<push> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<quoting|Other languages,quoting - perlfunc>\n\n=item q/STRING/\n\n=item qq/STRING/\n\n=item qw/STRING/\n\n=item qx/STRING/\n\nThese survive the transition to Raku. Some notes:\n\n=for code :lang<perl>\nq/.../;  # is still equivalent to using single quotes.\nqq/.../; # is still equivalent to using double quotes.\nqw/.../; # is more commonly written as <...> in Raku.\n\nThere are some added quoting constructs and equivalents, as explained at\nL<quoting|/language/quoting>.\n\n=item qr/STRING/\nX<|Other languages,qr (Perl)>\n\nHas been replaced by C<rx/.../>.\n\n=item quotemeta EXPR\n\nNo direct equivalent, i.e. nothing that just returns the string with all\nthe ASCII non-word characters backslashed. In regexes, however, using\nC<$foo> will treat C<$foo> as a literal string, and using C«<$foo>»\nwill interpret the contents of C<$foo> as regex code. Note that the\nangle brackets are doing something different here than they do outside a\nregex. For more information on this, see\nL<https://github.com/Raku/old-design-docs/blob/master/S05-regex.pod#Extensible_metasyntax_(%3C...%3E)>\n\nThe Raku ecosystem has a module L<C<P5quotemeta>|https://raku.land/zef:lizmat/P5quotemeta>\nwhich exports a C<quotemeta> function that mimics the original Perl\nbehavior as much as possible.\n\n=head2 X<rand|Other languages,rand - perlfunc>\n\n=item rand EXPR\n\nC<rand> by itself works as it does in Perl, but you can no longer give\nit an argument. You can, however, use it as a method on a number to get\nthat behavior. I. e. the Perl C<rand(100)> is equivalent to\nC<100.rand> in Raku. Additionally, you can get a random integer by\nusing something like C<(^100).pick>. For I<why> you are able to do that,\nsee L<^ operator|/language/operators#prefix_%5E> and\nL<pick|/routine/pick>.\n\nThe Raku ecosystem has a module L<C<P5math>|https://raku.land/zef:lizmat/P5math>\nwhich exports a C<rand> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<read|Other languages,read - perlfunc>\n\n=item read FILEHANDLE, SCALAR, LENGTH, OFFSET\n\nC<read> is found in L<C<IO::Handle>|/type/IO::Handle> and L<C<IO::Socket>|/type/IO::Socket> in Raku. It reads\nthe specified number of bytes (rather than characters) from the relevant\nhandle or socket. The use of an offset available in Perl is not\ndocumented to exist at this time.\n\n=head2 X<readdir|Other languages,readdir - perlfunc>\n\n=item readdir DIRHANDLE\n\nNot a builtin function. To iterate through the contents of a directory,\ntake a look at L<dir routine|/type/IO::Path#routine_dir>.\n\nThe Raku ecosystem has a module L<C<P5opendir>|https://raku.land/zef:lizmat/P5opendir>\nwhich exports a C<readdir> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<readline|Other languages,readline - perlfunc>\n\n=item readline\n\nNot available in Raku. You most likely want to use the C<.lines>\nmethod in some way. For more detailed information on reading from files,\nsee L<io|/language/io>.\n\n=head2 X<readlink|Other languages,readlink - perlfunc>\n\n=item readlink EXPR\n\nAppears to be gone from Raku.  There B<is> a method C<resolve> in\nL<C<IO::Path>|/type/IO::Path> that will follow symlinks if the OS / Filesystem supports them.\n\nThe Raku ecosystem has a module L<C<P5readlink>|https://raku.land/zef:lizmat/P5readlink>\nwhich exports a C<readlink> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<readpipe|Other languages,readpipe - perlfunc>\n\n=item readpipe EXPR\n\n=item readpipe\n\nDoesn't appear to be working in Raku, but C<qx//> is functional, so it might\nbe lurking around in some class that isn't obvious.\n\n=head2 X<recv|Other languages,recv - perlfunc>\n\n=item recv SOCKET, SCALAR, LENGTH, FLAGS\n\nAppears to be in L<C<IO::Socket>|/type/IO::Socket>. Not extensively documented at this time.\n\n=head2 X<redo|Other languages,redo - perlfunc>\n\n=item redo LABEL\n\n=item redo EXPR\n\n=item redo\n\nUnchanged in Raku.\n\n=head2 X<ref|Other languages,ref - perlfunc>\n\n=item ref EXPR\n\nGone. To quote S29, \"If you really want the type name, you can\nuse C<$var.WHAT.^name>.\n\nThe Raku ecosystem has a module L<C<P5ref>|https://raku.land/zef:lizmat/P5ref>\nwhich exports a C<ref> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<rename|Other languages,rename - perlfunc>\n\n=item rename OLDNAME, NEWNAME\n\nStill available in Raku.\n\n=head2 X<requires|Other languages,requires - perlfunc>\n\n=item require VERSION\n\nNo equivalent.\n\n=head2 X<reset|Other languages,reset - perlfunc>\n\n=item reset EXPR\n\nNo equivalent.\n\nThe Raku ecosystem has a module L<C<P5reset>|https://raku.land/zef:lizmat/P5reset>\nwhich exports a C<reset> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<return|Other languages,return - perlfunc>\n\n=item return EXPR\n\nAppears to be available in Raku, although not clearly documented.\n\n=head2 X<reverse|Other languages,reverse - perlfunc>\n\n=item reverse LIST\n\nIn Raku, this only reverses the elements of a list. C<reverse(@a)>\nor C<@a.reverse>. To reverse the characters in a string, use the\nC<.flip> method.\n\nC<reverse> without parameters is not supported in Raku.\n\nThe Raku ecosystem has a module L<C<P5reverse>|https://raku.land/zef:lizmat/P5reverse>\nwhich exports a C<reverse> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<rewinddir|Other languages,rewinddir - perlfunc>\n\n=item rewinddir DIRHANDLE\n\nNot supported in Raku.\n\nThe Raku ecosystem has a module L<C<P5opendir>|https://raku.land/zef:lizmat/P5opendir>\nwhich exports a C<rewinddir> function that mimics the original Perl\nbehavior as much as possible.\n\n=head2 X<rindex|Other languages,rindex - perlfunc>\n\n=item rindex STR, SUBSTR, POSITION\n\nWorks as in Perl, and may also be used as a method. E. g. C<$x =\n\"babaganush\";say $x.rindex(\"a\"); say $x.rindex(\"a\", 3); # 5, 3>.  Main\ndifference with Perl is that L<C<Nil>|/type/Nil> is returned instead of C<-1> when\nthe substring is not found.  This is very useful in combination with the\nC<with> command:\n\n    with index(\"foo\",\"o\") -> $index {\n        say \"Found it at $index\";\n    }\n    else {\n        say \"Not found\"\n    }\n\nThe Raku ecosystem has a module L<C<P5index>|https://raku.land/zef:lizmat/P5index>\nwhich exports a C<rindex> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<rmdir|Other languages,rmdir - perlfunc>\n\n=item rmdir FILENAME\n\nWorks in Raku and can also be used as a method. C<rmdir \"Foo\";> and\nC<\"Foo\".IO.rmdir;> are equivalent.\n\n=head2 X<s///|Other languages,s/// - perlfunc>\n\n=item s///\n\nRegular expression syntax is somewhat different in Raku, but the\nsubstitution operator exists. If you're trying to rewrite some\nPerl code, the most important difference is that C<=~> is replaced\nby the smartmatch operator, C<~~>. Similarly, C<!~> is C<!~~>.\nOptions for regex operators are adverbs and are complicated. For\ndetails, see L<Adverbs page|/language/regexes#Adverbs>\n\n=head2 X<say|Other languages,say - perlfunc>\n\n=item say FILEHANDLE\n\n=item say LIST\n\n=item say\n\nC<say> can be used as a function, defaulting to standard out. To use\nC<say> as a function with a filehandle I<instead> of standard out, you\nneed to put a colon after the filehandle. I. e. C<say $fh: \"Howdy!\">.\nThe use of the colon as an \"invocant marker\" here is discussed at\nL<https://github.com/Raku/old-design-docs/blob/master/S03-operators.pod#line_4019>. Alternately, you can use\na method call: C<$fh.say(\"howdy!\")>\n\nThe Raku ecosystem has a module L<C<P5print>|https://raku.land/zef:lizmat/P5print>\nwhich exports a C<say> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<scalar|Other languages,scalar - perlfunc>\n\n=item scalar EXPR\n\nGone. Apparently \"very\" gone.\n\nSome functions of the modules created for the CPAN Butterfly Plan accept\na C<:scalar> named parameter to indicate that the C<scalar> behavior of\nthe function is required.\n\n=head2 X<seek|Other languages,seek - perlfunc>\n\n=item seek FILEHANDLE, POSITION, WHENCE\n\nNot documented in any real way yet, but listed as a method of the\nL<C<IO::Handle>|/type/IO::Handle> class.\n\nThe Raku ecosystem has a module L<C<P5seek>|https://raku.land/zef:lizmat/P5seek>\nwhich exports a C<seek> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<seekdir|Other languages,seekdir - perlfunc>\n\n=item seekdir DIRHANDLE, POS\n\nNot supported in Raku.\n\nThe Raku ecosystem has a module L<C<P5opendir>|https://raku.land/zef:lizmat/P5opendir>\nwhich exports a C<seekdir> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<select|Other languages,select - perlfunc>\n\n=item select FILEHANDLE\n\n\"[S]elect as a global concept is dead.\" When I asked around about C<select>, I\nwas told that $*OUT and such are overridable in dynamic scope, and that\nC<IO::Capture::Simple> (at L<https://github.com/sergot/IO-Capture-Simple>) may\nbe of use for something you might be doing with the value of C<select>.\n=head2 semctl\n\n=item semctl ID, SEMNUM, CMD, ARG\n\nNo longer in core.\n\n=head2 X<semget|Other languages,semget - perlfunc>\n\n=item semget KEY, NSEMS, FLAGS\n\nNo longer in core.\n\n=head2 X<semop|Other languages,semop - perlfunc>\n\n=item semop KEY, OPSTRING\n\nNo longer in core.\n\n=head2 X<send|Other languages,send - perlfunc>\n\n=item send SOCKET, MSG, FLAGS, TO\n\nCan be found in the L<C<IO::Socket>|/type/IO::Socket> class.\n\n=head2 X<setpgrp|Other languages,setpgrp - perlfunc>\n\n=item setpgrp PID, PGRP\n\nWill not be implemented.\n\nThe Raku ecosystem has a module L<C<P5getpriority>|https://raku.land/zef:lizmat/P5getpriority>\nwhich exports a C<setpgrp> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<setpriority|Other languages,setpriority - perlfunc>\n\n=item setpriority WHICH, WHO, PRIORITY\n\nWill not be implemented.\n\nThe Raku ecosystem has a module L<C<P5getpriority>|https://raku.land/zef:lizmat/P5getpriority>\nwhich exports a C<setpriority> function that mimics the original Perl\nbehavior as much as possible.\n\n=head2 X<setsockopt|Other languages,setsockopt - perlfunc>\n\n=item setsockopt SOCKET, LEVEL, OPTNAME, OPTVAL\n\nNot documented, but probably hiding in an L<C<IO>|/type/IO> class somewhere.\n\n=head2 X<shift|Other languages,shift - perlfunc>\n\n=item shift ARRAY\n\n=item shift EXPR\n\n=item shift\n\nWorks in Raku, and can also be used as a method. I. e. C<my $x = shift\n@a;> and C<my $x = @a.shift;> are equivalent.\n\nThe non-parameter version of C<shift> does not exist.  Also, if the array\nis empty, a Failure will be returned in Raku, which will throw if the\nvalue is actually used in a significant way.\n\nIf you are using only defined values in your array, you can use the C<with>\nfunction to handle this case:\n\n=for code :preamble<my @array;>\nwith shift @array -> $shifted {\n    say \"shifted '$shifted' of the array\";\n}\nelse {\n    say \"there was nothing to shift\";\n}\n\nThe Raku ecosystem has a module L<C<P5shift>|https://raku.land/zef:lizmat/P5shift>\nwhich exports a C<shift> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<shm*|Other languages,shm* - perlfunc>\n\n=item shmctl ID, CMD, ARG\n\n=item shmget KEY, SIZE, FLAGS\n\n=item shmread ID, VAR, POS, SIZE\n\n=item shmwrite ID, STRING, POS, SIZE\n\nGone from the core. May turn up in a module somewhere.\n\n=head2 X<shutdown|Other languages,shutdown - perlfunc>\n\n=item shutdown SOCKET, HOW\n\nNot documented, but likely moved into L<C<IO::Socket>|/type/IO::Socket>.\n\n=head2 X<sin|Other languages,sin - perlfunc>\n\n=item sin EXPR\n\nSame as in Perl.\n\nC<sin> also operates on C<$_> in the absence of a value, but not as a\nfunction, and as a method you need to call it as C<.sin> rather than simply\nC<sin>.\n\nThe Raku ecosystem has a module L<C<P5math>|https://raku.land/zef:lizmat/P5math>\nwhich exports a C<sin> function that mimics the original Perl behavior as\nmuch as possible.\n=head2 X<sleep|Other languages,sleep - perlfunc>\n\n=item sleep EXPR\n\nStill works as in Perl, but is not limited to integer values for seconds.\nAnd it always returns Nil.\n\nIf you're interested in the return values of C<sleep> to ensure sleeping until\na specified time, then you should use C<sleep-until> in Raku (which takes\nan L<C<Instant>|/type/Instant>).\n\nIf you're interested in running some code every N seconds, and you don't care\non which thread it runs, you should probably use C<react> and C<whenever>\nwith a C<Supply.interval>.\n\nThe Raku ecosystem has a module L<C<P5sleep>|https://raku.land/zef:lizmat/P5sleep>\nwhich exports a C<sleep> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<sockets|Other languages,sockets - perlfunc>\n\n=item socket SOCKET, DOMAIN, TYPE, PROTOCOL\n\n=item socketpair SOCKET1, SOCKET2, DOMAIN, TYPE, PROTOCOL\n\nNot currently documented, but will likely wind up in L<C<IO::Socket>|/type/IO::Socket>.\n\n=head2 X<sort|Other languages,sort - perlfunc>\n\n=item sort SUBNAME LIST\n\nC<sort> exists in Raku, but is somewhat different. C<$a> and C<$b> are\nno longer special (see L<Special Variables|/language/perl-var>) and sort routines no\nlonger return positive integers, negative integers, or 0, but rather\nC<Order::Less>, C<Order::Same>, or C<Order::More> objects. See\nL<sort|/routine/sort> for details. May also be used as a\nmethod I. e. C<sort(@a)> is equivalent to C<@a.sort>.\n\n=head2 X<splice|Other languages,splice - perlfunc>\n\n=item splice ARRAY, OFFSET, LENGTH\n\n=item splice ARRAY, OFFSET\n\n=item splice ARRAY\n\n=item splice EXPR, OFFSET, LENGTH, LIST\n\n=item splice EXPR, OFFSET, LENGTH\n\n=item splice EXPR, OFFSET\n\n=item splice EXPR\n\nAvailable in Raku. Can also be used as a method. C<<splice(@foo, 2, 3,\n<M N O P>)>> is equivalent to C<<@foo.splice(2, 3, <M N O P>);>>.\n\n=head2 X<split|Other languages,split - perlfunc>\n\n=item split /PATTERN/, EXPR, LIMIT\n\n=item split /PATTERN/, EXPR\n\n=item split /PATTERN/\n\nWorks mostly as in Perl. There are some exceptions, though. To get the\nspecial behavior of using the empty string, you must actually use the\nempty string - the special case of the empty pattern C<//> being treated\nas the empty string does not apply. If you use a regex for the split, it\nwill use the regex, while a literal string will be treated literally. If\nyou wish to have the delimiters included in the resulting list, you need\nto use the named parameter C<:all>, like this: C<split(';', \"a;b;c\",\n:all) # a ; b ; c> Empty chunks are not removed from the result list as\nthey are in Perl. For that behavior, see C<comb>. Details on C<split>\nare L<here|/routine/split>. Unsurprisingly, C<split>\nalso now works as a method: C<\"a;b;c\".split(';')>\n\n=item split\n\nC<split> now requires a pattern. For the equivalent of Perl's behavior\nof splitting on whitespace when no pattern is specified, use\nL<words|/routine/words> (or use C<split> with C</\\s+/> as the pattern\nand C<:skip-empty> as a named argument).\n\n=head2 X<sprintf|Other languages,sprintf - perlfunc>\n\n=item sprintf FORMAT, LIST\n\nWorks as in Perl. The formats currently available are:\n\n=table\n    %   a literal percent sign\n    c   a character with the given codepoint\n    s   a string\n    d   a signed integer, in decimal\n    u   an unsigned integer, in decimal\n    o   an unsigned integer, in octal\n    x   an unsigned integer, in hexadecimal\n    e   a floating-point number, in scientific notation\n    f   a floating-point number, in fixed decimal notation\n    g   a floating-point number, in %e or %f notation\n    X   like x, but using uppercase letters\n    E   like e, but using an uppercase \"E\"\n    G   like g, but with an uppercase \"E\" (if applicable)\n\nCompatibility:\n\n=table\n    i   a synonym for %d\n    D   a synonym for %ld\n    U   a synonym for %lu\n    O   a synonym for %lo\n    F   a synonym for %f\n\nPerl (non-)compatibility:\n\n=table\n    n   produces a runtime exception\n    p   produces a runtime exception\n\nThere are modifiers for integers, but they're mainly no-ops, as the\nsemantics aren't settled:\n\n=table\n    h   interpret integer as native \"short\" (typically int16)\n    l   interpret integer as native \"long\" (typically int32 or int64)\n    ll  interpret integer as native \"long long\" (typically int64)\n    L   interpret integer as native \"long long\" (typically uint64)\n    q   interpret integer as native \"quads\" (typically int64 or larger)\n\n=head2 X<sqrt|Other languages,sqrt - perlfunc>\n\n=item sqrt EXPR\n\nSame as in Perl.\n\nC<sqrt> also operates on C<$_> in the absence of a value, but not as a\nfunction, and as a method you need to call it as C<.sqrt> rather than simply\nC<sqrt>.\n\nThe Raku ecosystem has a module L<C<P5math>|https://raku.land/zef:lizmat/P5math>\nwhich exports a C<sqrt> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<srand|Other languages,srand - perlfunc>\n\n=item srand EXPR\n\nAvailable in Raku.\n=head2 stat\n\n=item stat EXPR\n\n=item stat DIRHANDLE\n\n=item stat\n\nUnlikely to be implemented as a built in function since it's POSIX specific,\nbut available through the C<NativeCall> interface.\n\n=head2 X<state|Other languages,state - perlfunc>\n\n=item state VARLIST\n\n=item state TYPE VARLIST\n\n=item state VARLIST : ATTRS\n\n=item state TYPE VARLIST : ATTRS\n\nAvailable in Raku, see L<state|/syntax/state>.\n\n=head2 X<study|Other languages,study - perlfunc>\n\n=item study SCALAR\n\n=item study\n\nC<study> is no more.\n\nThe Raku ecosystem has a module L<C<P5study>|https://raku.land/zef:lizmat/P5study>\nwhich exports a C<study> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<sub|Other languages,sub - perlfunc>\n\n=item sub NAME BLOCK\n\n=item sub NAME(PROTO) BLOCK\n\n=item sub NAME : ATTRS BLOCK\n\n=item sub NAME(PROTO) : ATTRS BLOCK\n\nUnsurprisingly, we still have subroutines! You can have a signature in\nyour subroutine which allows you to specify arguments. Nevertheless, in\nthe absence of a signature (and only in the absence of a signature),\nC<@_> still contains what is passed to the function. So, in theory, you\ndon't need to change that aspect of a function if porting from Perl to\nRaku (although you should probably consider the option of using a\nsignature). For all the gory details, see\nL<functions|/language/functions>.\n\n=head2 X<__SUB__|Other languages,__SUB__ - perlfunc>\n\n=item __SUB__\n\nReplaced by C<&?ROUTINE> which is slightly different from C<__SUB__> in\nthat it is the actual L<C<Sub>|/type/Sub> (or L<C<Method>|/type/Method>) object.  You should call the\nC<.name> method on it to get a string.\n\nThe Raku ecosystem has a module L<C<P5__FILE__>|https://raku.land/zef:lizmat/P5__FILE__>\nwhich exports a C<__SUB__> term that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<substr|Other languages,substr - perlfunc>\n\n=item substr EXPR, OFFSET, LENGTH, REPLACEMENT\n\nSee L<substr-rw|/routine/substr-rw>.\n\nCan be used as a function or a method. Can't be used\non L<C<Str>|/type/Str> literals, as they are immutable.\n\n=begin code\n    my $a = 'Cheesy';\n    $a.substr-rw(4,1)=\"k\"; # returns 'k'\n    say $a; # OUTPUT: «Cheeky␤»\n\n    substr-rw($a, 0, 3) = \"Lea\";\n    say $a; # OUTPUT: «Leaky␤»\n=end code\n\n=item substr EXPR, OFFSET, LENGTH\n\n=item substr EXPR, OFFSET\n\nSee L<substr|/routine/substr>.\n\nCan be used as a function or a method. C<substr(\"hola!\", 1, 3)> and\nC<\"hola!\".substr(1, 3)> both return \"ola\".\n\n=head2 X<symlink|Other languages,symlink - perlfunc>\n\n=item symlink OLDFILE, NEWFILE\n\nSee L<symlink|/routine/symlink>.\n\n=head2 X<syscall|Other languages,syscall - perlfunc>\n\n=item syscall NUMBER, LIST\n\nNot a builtin in Raku. Most likely out in a module somewhere, but it's\ncurrently unclear where.\n\n=head2 X<sys*|Other languages,sys* - perlfunc>\n\n=item sysopen FILEHANDLE, FILENAME, MODE\n\n=item sysopen FILEHANDLE, FILENAME, MODE, PERMS\n\n=item sysread FILEHANDLE, SCALAR, LENGTH, OFFSET\n\n=item sysread FILEHANDLE, SCALAR, LENGTH\n\n=item sysseek FILEHANDLE, POSITION, WHENCE\n\nAs with the non-sys versions of these functions, are probably lurking in the\nL<C<IO>|/type/IO> classes somewhere.\n\n=head2 X<system|Other languages,system - perlfunc>\n\n=item system LIST\n\n=item system PROGRAM LIST\n\nFor this, you probably want (L<run|/routine/run>)\nor (L<shell routine|/routine/shell>).\n\n=head2 X<syswrite|Other languages,syswrite - perlfunc>\n\n=item syswrite FILEHANDLE, SCALAR, LENGTH, OFFSET\n\n=item syswrite FILEHANDLE, SCALAR, LENGTH\n\n=item syswrite FILEHANDLE, SCALAR\n\nAs with C<sysopen> and friends, this has moved into the L<C<IO>|/type/IO> classes.\n\n=head2 X<tell|Other languages,tell - perlfunc>\n\n=item tell FILEHANDLE\n\nAs a method on L<C<IO::Handle>|/type/IO::Handle>.\n\n=head2 X<telldir|Other languages,telldir - perlfunc>\n\n=item telldir DIRHANDLE\n\nNot supported in Raku.\n\nThe Raku ecosystem has a module L<C<P5opendir>|https://raku.land/zef:lizmat/P5opendir>\nwhich exports a C<telldir> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<tie|Other languages,tie - perlfunc>\n\n=item tie VARIABLE, CLASSNAME, LIST\n\n=item tied VARIABLE\n\nThe Raku alternative to tying a scalar, is the L<C<Proxy>|/type/Proxy> container.  For\nexample:\n\n=for code :method\nsub lval() {\n  Proxy.new(\n    FETCH => method () { ...},\n    STORE => method ($new) { ... }\n  )\n}\n\nThis makes C<lval> a left-value sub.  Whenever the value is requested, the\nC<FETCH> method is called.  And whenever it is used in an assignment, the\nC<STORE> method is called.\n\nFor arrays and hashes (objects that do the L<C<Positional>|/type/Positional> and/or L<C<Associative>|/type/Associative>\nrole), one only needs to provide the methods that these roles require to get\nthe functionality that C<tie> provides in Perl.  These are documented in\nthe C<Subscripts> section.\n\nThe Raku ecosystem has a module L<C<P5tie>|https://raku.land/zef:lizmat/P5tie>\nwhich exports C<tie> / C<tied> functions that mimics the original Perl\nbehavior as much as possible.\n\n=head2 X<time|Other languages,time - perlfunc>\n\n=item time\n\nNumber of seconds since epoch (as an L<C<Int>|/type/Int>), same as in Perl.\n\n=head2 X<times|Other languages,times - perlfunc>\n\n=item times\n\nNot available in Raku.\n\nThe Raku ecosystem has a module L<C<P5times>|https://raku.land/zef:lizmat/P5times>\nwhich exports a C<times> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<tr///|Other languages,tr/// - perlfunc>\n\n=item tr///\n\nWorks similarly to how it does in Perl. The one caveat is that ranges are\nspecified differently. Instead of using a range \"a-z\", you would use \"a..z\",\ni.e. with Perl's range operator. In Raku, C<tr///> has a method version,\ncalled L<trans|/routine/trans>, which offers a few additional features.\n\nPerl's C</r> flag is instead implemented as C<TR///> operator.\nThe C<y///> equivalent does not exist.\n\n=head2 X<truncate|Other languages,truncate - perlfunc>\n\n=item truncate FILEHANDLE, LENGTH\n\n=item truncate EXPR, LENGTH\n\nNot currently implemented (2018.04).\n\n=head2 X<uc|Other languages,uc - perlfunc>\n\n=item uc EXPR\n\nWorks as a function and a method. C<uc(\"ha\")> and C<\"ha\".uc> both return \"HA\".\nThere is no support for the parameterless version.\n\nThe Raku ecosystem has a module L<C<P5lc>|https://raku.land/zef:lizmat/P5lc>\nwhich exports a C<uc> function that mimics the original Perl behavior as\nmuch as possible.\n\n=head2 X<ucfirst|Other languages,ucfirst - perlfunc>\n\n=item ucfirst EXPR\n\n=item ucfirst\n\nRaku has done away with C<ucfirst>. The titlecase function\nL<C<tc>|/routine/tc> or L<C<tclc>|/routine/tclc>\nprobably does what you need; in the first case, it does \"titlecase\", which\nmight correspond to different characters in different alphabets; it defaults\nto uppercase if there's no titlecase mapping. On the other hand, C<tclc>\napplies C<tc> and then puts the rest of the characters in lowercase.\n\nThe Raku ecosystem has a module\nL<C<P5lcfirst>|https://raku.land/zef:lizmat/P5lcfirst> which exports a\nC<ucfirst> function that mimics the original Perl behavior as much as possible.\n\n=head2 X<undef|Other languages,undef - perlfunc>\n\n=item undef EXPR\n\nThere is no C<undef> in Raku. You can't undefine a function, and the closest\nequivalent value is probably L<C<Nil>|/type/Nil>, but you'll likely have no use for that.\n\nIf you were using something like C<(undef, $file, $line) = caller;>, you would\njust get the filename and line number directly in Raku instead of discarding\nthe first result of C<caller>. C<caller> has been replaced by C<callframe> in\nRaku, so the equivalent statement would be C<($file, $line) =\ncallframe.annotations<file line>;>\n\nThe Raku ecosystem has a module L<C<P5defined>|https://raku.land/zef:lizmat/P5defined>\nwhich exports an C<undef> function that mimics the original Perl behavior\nas much as possible.\n\n=for comment\nAdd a note here about Type-based undefined values.\n\n=head2 X<unlink|Other languages,unlink - perlfunc>\n\n=item unlink LIST\n\nStill available. Usable as a method: C<\"filename\".IO.unlink>\n\n=item unlink\n\nThe zero argument (implicit C<$_>) version of unlink is not available in Raku.\n\n=head2 X<unpack|Other languages,unpack - perlfunc>\n\n=item unpack TEMPLATE, EXPR\n\n=item unpack TEMPLATE\n\nAvailable in Raku when C<use experimental :pack> has been specified in the\nscope where C<unpack> needs to be called. The template options are currently\nmore restricted than they are in Perl. The current documented list can be\nfound at L<unpack|/routine/unpack>.\n\nThe Raku ecosystem has a module L<C<P5pack>|https://raku.land/zef:lizmat/P5pack>\nwhich exports an C<unpack> function that mimics the original Perl behavior\nas much as possible and which has a bigger set of supported features than the\nexperimental Raku version.\n\n=head2 X<unshift|Other languages,unshift - perlfunc>\n\n=item unshift ARRAY, LIST\n\n=item unshift EXPR, LIST\n\nWorks as in Perl, as well as being available as a method:\nC<@a.unshift(\"foo\");>. I<Note:> the flattening behavior is different in Raku:\nC<@b.unshift: @a> will unshift C<@a> into C<@b> as a single element. See also the\nL<prepend method|/type/Array#routine_prepend>.\n\nAlso note that C<unshift> in Raku returns the array to which was pushed,\ncontrary to Perl where it returns the new number of elements.\n\nThe Raku ecosystem has a module L<C<P5shift>|https://raku.land/zef:lizmat/P5shift>\nwhich exports an C<unshift> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<untie|Other languages,untie - perlfunc>\n\n=item untie VARIABLE\n\nNot supported in Raku, but see L<tie|/language/perl-func#tie> for the\nwhole story.\n\nThe Raku ecosystem has a module L<C<P5tie>|https://raku.land/zef:lizmat/P5tie>\nwhich exports an C<untie> function that mimics the original Perl behavior\nas much as possible.\n\n=head2 X<use|Other languages,use - perlfunc>\n\n=item use Module VERSION LIST\n\n=item use Module VERSION\n\n=item use Module LIST\n\n=item use Module\n\n=item use VERSION\n\nIn Perl, this requires a minimum version of the perl executable in\norder to run. In Raku, this requires a version of the specification,\n(e.g. C<6.c>), which can be implemented by various Raku executables.\n\n=head2 X<utime|Other languages,utime - perlfunc>\n\n=item utime LIST\n\nNo equivalent.\n\n=head2 X<values|Other languages,values - perlfunc>\n\n=item values HASH\n\n=item values ARRAY\n\n=item values EXPR\n\nAvailable in Raku. Can also be used as a method. C<values %hash> is\nequivalent to C<%hash.values>.\n\n=head2 X<vec|Other languages,vec - perlfunc>\n\n=item vec EXPR, OFFSET, BITS\n\nThere is no support for vec() in Raku.\n\nS29 says \"Should replace C<vec> with declared buffer/array of C<bit>,\nC<uint2>, C<uint4>, etc.\"  Support for C<bit>, C<uint2>, C<uint4> has not\nlanded yet.  But support for C<uint8>, C<int8>, C<uint16>, C<int16>,\nC<uint32>, C<int32>, C<uint64>, C<int64> as well as the system sized\nC<uint> and C<int> B<have> landed.  In scalar forms, as well as in array\nand shaped array (aka matrix) forms.\n\n=head2 X<wait|Other languages,wait - perlfunc>\n\n=item wait\n\n[NEEDS FURTHER RESEARCH] Unclear where this has gone. There's a C<wait>\nmethod in L<C<Supply>|/type/Supply>, and an C<await> method in both L<C<Channel>|/type/Channel> and\nL<C<Promise>|/type/Promise>. Which, if any or all, of these is a direct equivalent of\nPerl's C<wait> is unclear.\n\n=head2 X<waitpid|Other languages,waitpid - perlfunc>\n\n=item waitpid PID, FLAGS\n\nAs with C<wait>, the disposition of this is unclear.\n\n=head2 X<wantarray|Other languages,wantarray - perlfunc>\n\n=item wantarray\n\nThere is no C<wantarray> in Raku; however, there are very easy ways to cover many of the use cases which wantarray filled.\n\nFirst, since Raku does not need special reference syntax to contain\na L<C<List>|/type/List> or L<C<Array>|/type/Array> in a L<C<Scalar>|/type/Scalar>, simply returning a list may be\nall that is needed:\n\n    sub listofstuff {\n        return 1, 2, 3;\n    }\n    my $a = listofstuff();\n    print $a;                      # OUTPUT: «1 2 3»\n    print join(\"<\", listofstuff()) # OUTPUT: «1<2<3»\n\nOne of the most common use cases is to provide either an array of lines\nor elements, or a prettier string than would be produced by simply\nprinting the array.  One can mix in a custom C<.Str> method for this\npurpose:\n\n    sub prettylist(*@origlist) {\n        @origlist but role {\n            method Str { self.join(\"<\") }\n        }\n    }\n    print prettylist(1, 2, 3);            # OUTPUT: «1<2<3»\n    print join(\">\", prettylist(3, 2, 1)); # OUTPUT: «3>2>1»\n\nIn the above example, the returned list may be lazy, and the C<.Str> method\nis not called until stringification happens, so no extra work is done\nto generate something which is not asked for.\n\nAnother use case is to create methods which are mutators when called\nin void context but produce copies during assignment.  It is generally\nconsidered better form in Raku not to do so, even more so because I<void> context does not exist in Raku, with the closest equivalent being I<sink> context, since users can quite\neasily turn any copy-producing method into a mutator using the C<.=>\noperator:\n\n    my $a = \"foo\\n\";\n    $a.ords.say; # OUTPUT: «(102 111 111 10)␤»\n    $a .= chomp;\n    $a.ords.say; # OUTPUT: «(102 111 111)␤»\n\nHowever if you have your heart set on using the same function\nname for both operations, you can get most of the way there by mixing in\na C<.sink> method, which will be called when the result finds itself\nin sink context.  There are some caveats however, so again, this is\nnot advised:\n\n    multi increment($b is rw) {\n        ($b + 1) does role { method sink { $b++ } }\n    }\n    multi increment($b) {\n        $b + 1\n    }\n    my $a = 1;\n    increment($a);\n    say $a;                 # OUTPUT: «2␤»\n    my $b = increment($a);\n    say \"$a $b\";            # OUTPUT: «2 3␤»\n    # ...users will just have to be aware that they should not accidentally\n    # sink a stored value later, though this requires some effort to\n    # actually do:\n    sub identity($c is rw) { $c };\n    $a = 1;\n    $b = increment($a);\n    identity($b);\n    $a.say;                 # OUTPUT: «2␤»\n\n=head2 X<warn|Other languages,warn - perlfunc>\n\n=item warn LIST\n\nC<warn> throws a resumable exception. To simply print a message to C<$*ERR>, you\nwould use the C<note> function. For more on exceptions, see\nL<Exceptions|/language/exceptions>.\n\n=head2 X<write|Other languages,write - perlfunc>\n\n=item write FILEHANDLE\n\n=item write EXPR\n\n=item write\n\nFormats are gone from Raku, so this no longer works.\n\n=head2 X<y///|Other languages,y/// - perlfunc>\n\n=item y///\n\nThis synonym for C<tr///> is gone. For functionality, see the entry for\nC<tr///>.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/perl-nutshell.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"migration\")\n\n=TITLE Perl to Raku guide - in a nutshell\n\n=SUBTITLE How do I do what I used to do? (Raku in a nutshell)\n\nThis page attempts to provide a fast-path to the changes in syntax and\nsemantics from Perl to Raku. Whatever worked in Perl and must be\nwritten differently in Raku, should be listed here (whereas many\nI<new> Raku features and idioms need not).\n\nHence this should not be mistaken for a beginner tutorial or a\npromotional overview of Raku; it is intended as a technical reference\nfor Raku learners with a strong Perl background and for anyone\nporting Perl code to Raku (though note that L<automated translation|#Automated\ntranslation> might be more convenient).\n\nA note on semantics; when we say \"now\" in this document, we mostly just\nmean \"now that you are trying out Raku.\"  We don't mean to imply that\nPerl is now suddenly obsolete.  Quite the contrary, most of us love\nPerl, and we expect Perl to continue in use for a good many years.\nIndeed, one of our more important goals has been to make interaction\nbetween Perl and Raku run smoothly.  However, we do also like the\ndesign decisions in Raku, which are certainly newer and arguably\nbetter integrated than many of the historical design decisions in Perl.\nSo many of us do hope that over the next decade or two, Raku will\nbecome the more dominant language.  If you want to take \"now\" in that\nfuture sense, that's okay too.  But we're not at all interested in the\neither/or thinking that leads to fights.\n\nI<Please note that some historic documents may refer to Raku by its\noriginal name, Perl 6, or to Perl as specifically Perl 5.>\n\n=head1 CPAN\n\nSee L<https://raku.land/>.\n\nIf the module that you were using has not been converted to Raku, and\nno alternative is listed in this document, then its use under Raku may\nnot have been addressed yet.\n\nThe L<C<Inline::Perl5>|https://raku.land/cpan:NINE/Inline::Perl5> project makes\nit possible to C<use> Perl modules directly from Raku code by using\nan embedded instance of the C<perl> interpreter to run Perl code.\n\nThis is as simple as:\n\n=for code :skip-test<needs ecosystem>\n# the :from<Perl5> makes Raku load Inline::Perl5 first (if installed)\n# and then load the Scalar::Util module from Perl\nuse Scalar::Util:from<Perl5> <looks_like_number>;\nsay looks_like_number \"foo\";   # OUTPUT: «0␤»\nsay looks_like_number \"42\";    # OUTPUT: «1␤»\n\nA number of Perl modules have been ported to Raku, trying to maintain\nthe API of these modules as much as possible, as part of the CPAN Butterfly\nPlan.  These can be found at L<https://raku.land/?q=CPAN5>.\n\nMany Perl built-in functions (about a 100 so far) have been ported to\nRaku with the same semantics.  Think about the C<shift> function in Perl\nhaving magic shifting from C<@_> or C<@ARGV> by default, depending on context.\nThese can be found at L<https://raku.land/zef:lizmat/P5built-ins> and\nits dependencies.\n\n=head1 Syntax\n\nThere are a few differences in syntax between the two languages, starting with\nhow identifiers are defined.\n\n=head2 Identifiers\n\nRaku allows the use of dashes (C<->), underscores (C<_>),\napostrophes (C<'>), and alphanumerics in identifiers:\n\n    sub test-doesn't-hang { ... }\n    my $ความสงบ = 42;\n    my \\Δ = 72; say 72 - Δ;\n\n=head2 C«->» Method calls\n\nIf you've read any Raku code at all, it's immediately obvious that\nmethod call syntax now uses a dot instead of an arrow:\n\n=for code :lang<perl>\n$person->name  # Perl\n=for code :preamble<no strict;>\n$person.name   # Raku\n\nThe dot notation is both easier to type and more of an industry standard.\nBut we also wanted to steal the arrow for something else.  (Concatenation\nis now done with the C<~> operator, if you were wondering.)\n\nTo call a method whose name is not known until runtime:\n\n=for code :lang<perl>\n$object->$methodname(@args);  # Perl\n=for code :preamble<no strict;>\n$object.\"$methodname\"(@args); # Raku\n\nIf you leave out the quotes, then Raku expects C<$methodname> to contain\na L<C<Method>|/type/Method> object rather than the simple string name of the method.  Yes,\nB<everything> in Raku can be considered an object.\n\n=head2 Whitespace\n\nPerl allows a surprising amount of flexibility in the use of whitespace,\neven with strict mode and warnings turned on:\n\n=for code :lang<perl>\n# unidiomatic but valid Perl\nsay\"Hello \".ucfirst  ($people\n    [$ i]\n    ->\n    name).\"!\"if$greeted[$i]<1;\n\nRaku also endorses programmer freedom and creativity, but balanced\nsyntactic flexibility against its design goal of having a consistent,\ndeterministic, extensible grammar that supports single-pass parsing and\nhelpful error messages, integrates features like custom operators cleanly,\nand doesn't lead programmers to accidentally misstate their intent.\nAlso, the practice of \"code golf\" is slightly de-emphasized; Raku is\ndesigned to be more concise in concepts than in keystrokes.\n\nAs a result, there are various places in the syntax where whitespace is\noptional in Perl, but is either mandatory or forbidden in Raku. Many of\nthose restrictions are unlikely to concern much real-life Perl code (e.g.,\nwhitespace being disallowed between the sigil and name of a variable), but\nthere are a few that will unfortunately conflict with some Perl hackers'\nhabitual coding styles:\n\n=begin item\nI<No space allowed before the opening parenthesis of an argument list.>\n\n=for code :lang<perl>\nsubstr ($s, 4, 1); # Perl (in Raku this would try to pass a single\n                       #         argument of type List to substr)\n=for code :preamble<no strict;>\nsubstr($s, 4, 1);  # Raku\nsubstr $s, 4, 1;   # Raku - alternative parentheses-less style\n\nShould this really be a problem for you, then you might want to have a look\nat the L<C<Slang::Tuxic>|https://raku.land/zef:raku-community-modules/Slang::Tuxic> module in the Raku ecosystem: it changes the grammar\nof Raku in such a way that you B<can> have a space before the opening\nparenthesis of an argument list.\n\n=end item\n\n=begin item\nI<Space is B<required> immediately after keywords>\n\n=for code :lang<perl>\nmy($alpha, $beta);          # Perl, tries to call my() sub in Raku\n=for code :preamble<no strict;>\nmy ($alpha, $beta);         # Raku\n\n=for code :lang<perl>\nif($a < 0) { ... }          # Perl, dies in Raku\n=for code :preamble<no strict;>\nif ($a < 0) { ... }         # Raku\nif $a < 0 { ... }           # Raku, more idiomatic\n\n=for code :lang<perl>\nwhile($x-- > 5) { ... }     # Perl, dies in Raku\n=for code :preamble<no strict;>\nwhile ($x-- > 5) { ... }    # Raku\nwhile $x-- > 5 { ... }      # Raku, more idiomatic\n\n=end item\n\n=begin item\nI<No space allowed after a prefix operator, or before a\npostfix/postcircumfix operator (including array/hash subscripts).>\n\n=for code :lang<perl>\n$seen {$_} ++; # Perl\n=for code :preamble<no strict;>\n%seen{$_}++;   # Raku\n=end item\n\n=begin item\nI<Space required before an infix operator if it would\nconflict with an existing postfix/postcircumfix operator.>\n\n=for code :lang<perl>\n$n<1;   # Perl (in Raku this would conflict with postcircumfix < >)\n=for code :preamble<no strict;>\n$n < 1; # Raku\n\n=end item\n\n=begin item\nI<However, whitespace B<is allowed> before the period of a method call!>\n\n=for code :lang<perl>\n# Perl\nmy @books = $xml\n  ->parse_file($file)          # some comment\n  ->findnodes(\"/library/book\");\n\n=for code :preamble<no strict;>\n# Raku\nmy @books = $xml\n  .parse-file($file)           # some comment\n  .findnodes(\"/library/book\");\n\n=end item\n\nHowever, note that you can use L<unspace|/language/syntax#Unspace>\nto add whitespace in Raku code in places where it is otherwise not\nallowed.\n\nSee also\nL<other lexical conventions in the syntax page|/language/syntax#Lexical_conventions>.\n\n=head2 Sigils\n\nIn Perl, arrays and hashes use changing sigils depending on how they are\nbeing accessed. In Raku the sigils are invariant, no matter how the\nvariable is being used - you can think of them as part of the variable's\nname.\n\n=head3 C<$> Scalar\n\nThe C<$> sigil is now always used with \"scalar\" variables (e.g. C<$name>),\nand no longer for L<array indexing|#[]_Array_indexing/slicing> and L<Hash\nindexing|#{}_Hash_indexing/slicing>.  That is, you can still use C<$x[1]>\nand C<$x{\"foo\"}>, but it will act on C<$x>, with no effect on a similarly\nnamed C<@x> or C<%x>. Those would now be accessed with C<@x[1]> and C<%x{\"foo\"}>.\n\n=head3 C<@> Array\n\nThe C<@> sigil is now always used with \"array\" variables (e.g. C<@months>,\nC<@months[2]>, C<@months[2, 4]>), and no longer for L<value-slicing\nhashes|#{}_Hash_indexing/slicing>.\n\n=head3 C<%> Hash\n\nThe C<%> sigil is now always used with \"hash\" variables (e.g. C<%calories>,\nC<%calories<apple>>, C<%calories<pear plum>>), and no longer for\nL<key/value-slicing arrays|#[]_Array_indexing/slicing>.\n\n=head3 C<&> Sub\n\nThe C<&> sigil is now used consistently (and without the help of a\nbackslash) to refer to the function object of a named subroutine/operator\nwithout invoking it, i.e. to use the name as a \"noun\" instead of a \"verb\":\n\n=for code :lang<perl>\nmy $sub = \\&foo; # Perl\n=for code :preamble<sub foo {};>\nmy $sub = &foo;  # Raku\n\n=for code :lang<perl>\ncallback => sub { say @_ }  # Perl - can't pass built-in sub directly\n=for code\ncallback => &say            # Raku - & gives \"noun\" form of any sub\n\nSince Raku does not allow adding/removing symbols in a lexical scope once\nit has finished compiling, there is no equivalent to Perl's\nC<undef &foo;>, and the closest equivalent to Perl's C<defined &foo>\nwould be C<defined ::('&foo')> (which uses the \"dynamic symbol lookup\"\nsyntax). However, you can declare a mutable named subroutine with\nC<my &foo;> and then change its meaning at runtime by assigning to C<&foo>.\n\nIn Perl, the ampersand sigil can additionally be used to call subroutines\nin special ways with subtly different behavior compared to normal sub\ncalls. In Raku those special forms are no longer available:\n\n=begin item\nC<&foo(...)> I<for circumventing a function prototype>\n\nIn Raku there are no prototypes, and it no longer\nmakes a difference whether you, say, pass a literal code block or a\nvariable holding a code object as an argument:\n\n=for code :lang<perl>\n# Perl:\nfirst_index { $_ > 5 } @values;\n&first_index($coderef, @values); # (disabling the prototype that parses a\n                                     # literal block as the first argument)\n=for code :preamble<my @values; my $coderef>\n# Raku:\nfirst { $_ > 5 }, @values, :k;   # the :k makes first return an index\nfirst $coderef, @values, :k;\n=end item\n\n=begin item\nC<&foo;> I<and> C<goto &foo;> I<for re-using the caller's argument\nlist / replacing the caller in the call stack>. Raku can use either\nL<C<callsame>|/language/functions#sub_callsame> for\nre-dispatching or\nL<C<nextsame>|/language/functions#sub_nextsame> and\nL<C<nextwith>|/language/functions#sub_nextwith>, which have no\nexact equivalent in Perl.\n\n=for code :lang<perl>\nsub foo { say \"before\"; &bar;     say \"after\" } # Perl\n\n=for code :preamble<sub bar() {...}>\nsub foo { say \"before\"; bar(|@_); say \"after\" } # Raku - have to be explicit\n\n\n=for code :lang<perl>\nsub foo { say \"before\"; goto &bar } # Perl\n=begin code\nproto foo (|) {*};\nmulti foo ( Any $n ) {\n    say \"Any\"; say $n;\n};\nmulti foo ( Int $n ) {\n    say \"Int\"; callsame;\n};\nfoo(3); # /language/functions#sub_callsame\n=end code\n\n=end item\n\n=head3 C<*> Glob\n\nIn Perl, the C<*> sigil referred to the GLOB structure that Perl uses to\nstore non-lexical variables, filehandles, subs, and formats.\n\nN<This should not be confused with the Perl built-in C<glob()> function,\nwhich reads filenames from a directory.>\n\nYou are most likely to encounter a GLOB in code written on an early Perl\nversion that does not support lexical filehandles, when a filehandle needed\nto be passed into a sub.\n\n=for code :lang<perl>\n# Perl - ancient method\nsub read_2 {\n    local (*H) = @_;\n    return scalar(<H>), scalar(<H>);\n}\nopen FILE, '<', $path or die;\nmy ($line1, $line2) = read_2(*FILE);\n\nYou should refactor your Perl code to remove the need for the GLOB,\nbefore translating into Raku.\n\n=for code :lang<perl>\n# Perl - modern use of lexical filehandles\nsub read_2 {\n    my ($fh) = @_;\n    return scalar(<$fh>), scalar(<$fh>);\n}\nopen my $in_file, '<', $path or die;\nmy ($line1, $line2) = read_2($in_file);\n\nAnd here's just one possible Raku translation:\n\n=for code :preamble<no strict;>\n# Raku\nsub read-n($fh, $n) {\n    return $fh.get xx $n;\n}\nmy $in-file = open $path or die;\nmy ($line1, $line2) = read-n($in-file, 2);\n\n=head2 [] Array indexing/slicing\n\nIndex and slice operations on arrays no longer inflect the variable's\nL<sigil|#@_Array>, and adverbs can be used to control the type of slice:\n\n=begin item\nI<Indexing>\n\n=for code :lang<perl>\nsay $months[2]; # Perl\n=for code :preamble<no strict;>\nsay @months[2]; # Raku - @ instead of $\n=end item\n\n=begin item\nI<Value-slicing>\n\n=for code :preamble<no strict;>\nsay join ',', @months[6, 8..11]; # Perl and Raku\n=end item\n\n=begin item\nI<Key/value-slicing>\n\n=for code :lang<perl>\nsay join ',', %months[6, 8..11];    # Perl\n=for code :preamble<no strict;>\nsay join ',', @months[6, 8..11]:kv; # Raku - @ instead of %; use :kv adverb\n=end item\n\nAlso note that the subscripting square brackets are now a normal postcircumfix\noperator rather than a special syntactic form, and thus L<checking for\nexistence of elements|#exists> and L<unsetting elements|#delete> is done\nwith adverbs.\n\nAn array's biggest index is now available with the C<.end> method:\n\n=for code :lang<perl>\nsay $#item;    # Perl\n=for code :preamble<no strict;>\nsay @item.end; # Raku\n\n=head2 {} Hash indexing/slicing\n\nIndex and slice operations on hashes no longer inflect the variable's\nL<sigil|#%_Hash>, and adverbs can be used to control the type of slice.\nAlso, single-word subscripts are no longer magically autoquoted inside the\ncurly braces; instead, the new angle brackets version is available which\nalways autoquotes its contents (using the same rules as the C<qw//> quoting\nconstruct):\n\n=begin item\nI<Indexing>\n\n=for code :lang<perl>\nsay $calories{\"apple\"}; # Perl\n=for code :preamble<no strict;>\nsay %calories{\"apple\"}; # Raku - % instead of $\n\n=for code :lang<perl>\nsay $calories{apple};   # Perl\n=for code :preamble<no strict;>\nsay %calories<apple>;   # Raku - angle brackets; % instead of $\nsay %calories«\"$key\"»;  # Raku - double angles interpolate as a list of Str\n=end item\n\n=begin item\nI<Value-slicing>\n\n=for code :lang<perl>\nsay join ',', @calories{'pear', 'plum'}; # Perl\n=for code :preamble<no strict;>\nsay join ',', %calories{'pear', 'plum'}; # Raku - % instead of @\nsay join ',', %calories<pear plum>;      # Raku (prettier version)\nmy $keys = 'pear plum';\nsay join ',', %calories«$keys»;          # Raku the split is done after interpolation\n=end item\n\n=begin item\nI<Key/value-slicing>\n\n=for code :lang<perl>\nsay join ',', %calories{'pear', 'plum'};    # Perl\n=for code :preamble<no strict;>\nsay join ',', %calories{'pear', 'plum'}:kv; # Raku - use :kv adverb\nsay join ',', %calories<pear plum>:kv;      # Raku (prettier version)\n=end item\n\nAlso note that the subscripting curly braces are now a normal postcircumfix\noperator rather than a special syntactic form, and thus L<checking for\nexistence of keys|#exists> and L<removing keys|#delete> is done with\nadverbs.\n\n=head2 Creating references and using them\n\nIn Perl, references to anonymous arrays and hashes and subs are returned\nduring their creation. References to existing named variables and subs were\ngenerated with the C<\\> operator. the \"referencing/dereferencing\"\nmetaphor does not map cleanly to the actual Raku container system,\nso we will have to focus on the intent of the reference operators\ninstead of the actual syntax.\n\n=for code :lang<perl>\nmy $aref = \\@aaa  ; # Perl\n\nThis might be used for passing a reference to a routine, for instance. But in\nRaku, the (single) underlying object is passed (which you could consider\nto be a sort of pass by reference).\n\n=begin code\nmy @array = 4,8,15;\n{ $_[0] = 66 }(@array);   # run the block with @array aliased to $_\nsay @array; #  OUTPUT: «[66 8 15]␤»\n=end code\n\nThe underlying L<C<Array>|/type/Array> object of C<@array> is passed, and its first value\nmodified inside the declared routine.\n\nIn Perl, the syntax for dereferencing an entire reference is the type-sigil\nand curly braces, with the reference inside the curly braces. In Raku, this\nconcept simply does not apply, since the I<reference> metaphor does not really\napply.\n\nIn Perl, the arrow operator, C«->» , is used for single access to a\ncomposite's reference or to call a sub through its reference. In Raku, the dot\noperator C<.> is always used for object methods, but the rest does not really\napply.\n\n=for code :lang<perl>\n# Perl\n    say $arrayref->[7];\n    say $hashref->{'fire bad'};\n    say $subref->($foo, $bar);\n\nIn relatively recent versions of Perl (5.20 and later), a new feature allows\nthe use of the arrow operator for dereferencing:  see L<Postfix Dereferencing|https://metacpan.org/pod/release/SHAY/perl-5.20.1/pod/perl5200delta.pod#Experimental_Postfix_Dereferencing>.\nThis can be used to create an array from a scalar. This operation is usually\ncalled I<decont>, as in decontainerization, and in Raku methods such as\nC<.list> and C<.hash> are used:\n\n=for code :lang<perl>\n# Perl 5.20\n    use experimental qw< postderef >;\n    my @a = $arrayref->@*;\n    my %h = $hashref->%*;\n    my @slice = $arrayref->@[3..7];\n\n=for code :preamble<no strict;>\n# Raku\n    my @a = $contains-an-array.list;        # or @($arrayref)\n    my %h = $contains-a-hash.hash;          # or %($hashref)\n\nThe \"Zen\" slice does the same thing:\n\n=for code :preamble<no strict;>\n# Raku\n    my @a = $contains-an-array[];\n    my %h = $contains-a-hash{};\n\nSee L<the \"Containers\" section of the documentation|/language/containers> for\nmore information.\n\n=head1 Operators\n\nSee L<the documentation for operators|/language/operators>\nfor full details on all operators.\n\nUnchanged:\n\n=item C<+> Numeric Addition\n=item C<-> Numeric Subtraction\n=item C<*> Numeric Multiplication\n=item C</> Numeric Division\n=item C<%> Numeric Modulus\n=item C<**> Numeric Exponentiation\n=item C<++> Numeric Increment\n=item C<--> Numeric Decrement\n=item C<! && || ^> Booleans, high-precedence\n=item C<not and or xor> Booleans, low-precedence\n=item C«== != < > <= >=»   Numeric comparisons\n=item C<eq ne lt gt le ge>  String comparisons\n\n=head2 C<,> (Comma) List separator\n\nUnchanged, but note that in order to flatten an array variable to a list (in\norder to append or prefix more items) one should use the C<|> operator\n(see also L<C<Slip>|/type/Slip>). For instance:\n\n=for code\nmy @numbers = 100, 200, 300;\nmy @more_numbers = 500, 600, 700;\nmy @all_numbers = |@numbers, 400, |@more_numbers;\n\nThat way one can concatenate arrays.\n\nNote that one does not need to have any parentheses on the right-hand side:\nthe list separator takes care of creating the list, B<not> the parentheses!\n\n=head2 C«<=> cmp» Three-way comparisons\n\nIn Perl, these operators returned -1, 0, or 1.\nIn Raku, they return C<Order::Less>, C<Order::Same>, or C<Order::More>.\n\nC«cmp» is now named C«leg»; it forces string context for the comparison.\n\nC«<=>» still forces numeric context.\n\nC«cmp» in Raku does either C«<=>» or C<leg>, depending on the existing\ntype of its arguments.\n\n=head2 C<~~> Smartmatch operator\n\nWhile the operator has not changed, the rules for what exactly is matched\ndepend on the types of both arguments, and those rules are far from\nidentical in Perl and Raku. See L<~~|/routine/~~> and\nL<the smartmatch operator|/language/operators#index-entry-smartmatch_operator>\n\n=head2 C<& | ^> String bitwise ops\n=head2 C<& | ^> Numeric bitwise ops\n=head2 C<& | ^> Boolean ops\n\nIn Perl, C<& | ^> were invoked according to the contents of their\narguments. For example, C<31 | 33> returns a different result than C<\"31\" |\n\"33\">.\n\nIn Raku, those single-character ops have been removed, and replaced by\ntwo-character ops which coerce their arguments to the needed context.\n\n=begin code :lang<text>\n# Infix ops (two arguments; one on each side of the op)\n+&  +|  +^  And Or Xor: Numeric\n~&  ~|  ~^  And Or Xor: String\n?&  ?|  ?^  And Or Xor: Boolean\n\n# Prefix ops (one argument, after the op)\n+^  Not: Numeric\n~^  Not: String\n?^  Not: Boolean (same as the ! op)\n=end code\n\n=head2 C«<< >>» Numeric shift left|right ops\n\nReplaced by C«+<» and C«+>» .\n\n=for code :lang<perl>\nsay 42 << 3; # Perl\n=for code\nsay 42 +< 3; # Raku\n\n=head2 C«=>» Fat comma\n\nIn Perl, C«=>» acted just like a comma, but also quoted its left-hand\nside.\n\nIn Raku, C«=>» is the L<C<Pair>|/type/Pair> operator, which is quite different in\nprinciple, but works the same in many situations.\n\nIf you were using C«=>» in hash initialization, or in passing arguments to\na sub that expects a hashref, then the usage is likely identical.\n\n    sub get_the_loot { ... }; # Raku stub\n    # Works in Perl and Raku\n    my %hash = ( AAA => 1, BBB => 2 );\n    get_the_loot( 'diamonds', { quiet_level => 'very', quantity => 9 }); # Note the curly braces\n\nIf you were using C«=>» as a convenient shortcut to not have to quote part\nof a list, or in passing arguments to a sub that expects a flat list of\nC<KEY, VALUE, KEY, VALUE>, then continuing to use C«=>» may break your code.\nThe easiest workaround is to change that I<fat arrow> to a regular comma, and\nmanually add quotes to its left-hand side. Or, you can change the sub's API\nto L<slurp a hash|/language/signatures#Slurpy_parameters>.\nA better long-term solution is to change the sub's API to\nexpect L<C<Pair>|/type/Pair>s; however, this requires you to change\nall sub calls at once.\n\n=begin code :lang<perl>\n# Perl\nsub get_the_loot {\n    my $loot = shift;\n    my %options = @_;\n    # ...\n}\n# Note: no curly braces in this sub call\nget_the_loot( 'diamonds', quiet_level => 'very', quantity => 9 );\n=end code\n\n=begin code\n# Raku, original API\nsub get_the_loot( $loot, *%options ) { # The * means to slurp everything\n    ...\n}\nget_the_loot( 'diamonds', quiet_level => 'very', quantity => 9 ); # Note: no curly braces in this API\n\n# Raku, API changed to specify valid options\n# The colon before the sigils means to expect a named variable,\n# with the key having the same name as the variable.\nsub get_the_loot( $loot, :$quiet_level?, :$quantity = 1 ) {\n    # This version will check for unexpected arguments!\n    ...\n}\nget_the_loot( 'diamonds', quietlevel => 'very' ); # Throws error for misspelled parameter name\n=end code\n\n=head2 C<? :> Ternary operator\n\nThe conditional operator C<? :> has been replaced\nby C<?? !!>:\n\n=for code :lang<perl>\nmy $result = $score > 60 ?  'Pass' :  'Fail'; # Perl\n\n=for code :preamble<my $score>\nmy $result = $score > 60 ?? 'Pass' !! 'Fail'; # Raku\n\n=head2 C<.> (Dot) String concatenation\n\nReplaced by the tilde.\n\nMnemonic: think of \"stitching\" together the two strings with needle and thread.\n\n=for code :lang<perl>\n$food = 'grape' . 'fruit'; # Perl\n=for code :preamble<no strict;>\n$food = 'grape' ~ 'fruit'; # Raku\n\n=head2 C<x> List repetition or string repetition operator\n\nIn Perl, C<x> is the repetition operator, which behaves differently in\nscalar or list contexts:\n=item in scalar context C<x> repeats a string;\n=item in list context C<x> repeats a list, but only if the left argument\nis parenthesized!\n\nRaku uses two different repetition operators to achieve the above:\n=item C<x> for string repetitions (in any context);\n=item C<xx> for list repetitions (in any context).\n\nMnemonic: C<x> is short and C<xx> is long, so C<xx> is the one used for lists.\n\n=for code :lang<perl>\n# Perl\n    print '-' x 80;             # Print row of dashes\n    @ones = (1) x 80;           # A list of 80 1's\n    @ones = (5) x @ones;        # Set all elements to 5\n=for code :preamble<no strict;>\n# Raku\n    print '-' x 80;             # Unchanged\n    @ones = 1 xx 80;            # Parentheses no longer needed\n    @ones = 5 xx @ones;         # Parentheses no longer needed\n\n\n=head2 C<..> C<...> Two dots or three dots, range op or flipflop op\n\nIn Perl, C<..> was one of two completely different operators, depending\non context.\n\nIn list context, C<..> is the familiar range operator. Ranges from Perl\ncode should B<not> require translation.\n\nIn scalar context, C<..> and C<...> were the little-known Flipflop\noperators. They have been replaced by C<ff> and C<fff>.\n\n=head2 String interpolation\n\nIn Perl, C<\"${foo}s\"> deliminates a variable name from regular text next to\nit. In Raku, simply extend the curly braces to include the sigil too:\nC<\"{$foo}s\">. This is in fact a very simple case of interpolating an expression.\n\n=head1 Compound statements\n\nThese statements include conditionals and loops.\n\n=head2 Conditionals\n\n=head3 C<if> C<elsif> C<else> C<unless>\n\nMostly unchanged; parentheses around the conditions are now optional, but if\nused, must not immediately follow the keyword, or it will be taken as a function\ncall instead.  Binding the conditional expression to a variable is also a little\ndifferent:\n\n=for code :lang<perl>\nif (my $x = dostuff()) {...}  # Perl\n=for code :preamble<sub dostuff {};>\nif dostuff() -> $x {...}      # Raku\n\n(You can still use the C<my> form in Raku, but it will scope to the\nouter block, not the inner.)\n\nThe C<unless> conditional only allows for a single block in Raku;\nit does not allow for an C<elsif> or C<else> clause.\n\n=head3 C<given>-C<when>\n\nThe C<given>-C<when> construct is like a chain of C<if>-C<elsif>-C<else>\nstatements or like the C<switch>-C<case> construct C, for example.  It has the\ngeneral structure:\n\n=for code :lang<pseudo>\ngiven EXPR {\n    when EXPR { ... }\n    when EXPR { ... }\n    default { ... }\n}\n\nIn its simplest form, the construct is as follows:\n\n=for code :preamble<no strict;>\ngiven $value {                   # assigns $_\n    when \"a match\" {             # if $_ ~~ \"a match\"\n        # do-something();\n    }\n    when \"another match\" {       # elsif $_ ~~ \"another match\"\n        # do-something-else();\n    }\n    default {                    # else\n        # do-default-thing();\n    }\n}\n\nThis is simple in the sense that a scalar value is matched in the C<when>\nstatements against C<$_>, which was set by the C<given>.  More generally,\nthe matches are actually smartmatches on C<$_> such that lookups using more\ncomplex entities such as regexps can be used instead of scalar values.\n\nSee also the warnings on the smartmatch op above.\n\n=head2 Loops\n\n=head3 C<while> C<until>\n\nMostly unchanged; parentheses around the conditions are now optional, but if\nused, must not immediately follow the keyword, or it will be taken as a function\ncall instead.  Binding the conditional expression to a variable is also a little\ndifferent:\n\n=for code :lang<perl>\nwhile (my $x = dostuff()) {...}  # Perl\n=for code :preamble<sub dostuff {};>\nwhile dostuff() -> $x {...}      # Raku\n\n(You can still use the C<my> form in Raku, but it will scope to the\nouter block, not the inner.)\n\nNote that reading line-by-line from a filehandle has changed.\n\nIn Perl, it was done in a C<while> loop using the diamond operator. Using\nC<for> instead of C<while> was a common bug, because the C<for> causes the\nwhole file to be sucked in at once, swamping the program's memory usage.\n\nIn Raku, C<for> statement is B<lazy>, so we read line-by-line in a C<for>\nloop using the C<.lines> method.\n\n=for code :lang<perl>\nwhile (<IN_FH>)  { } # Perl\n=for code :preamble<no strict;>\nfor $IN_FH.lines { } # Raku\n\nAlso note that in Raku, lines are C<chomp>ed by default.\n\n=head3 C<do> C<while>/C<until>\n\n=begin code :lang<perl>\n# Perl\ndo {\n    ...\n} while $x < 10;\n\ndo {\n    ...\n} until $x >= 10;\n=end code\n\nThe construct is still present, but C<do> was renamed to C<repeat>, to better\nrepresent what the construct does:\n\n=begin code :preamble<no strict;>\n# Raku\nrepeat {\n    ...\n} while $x < 10;\n\nrepeat {\n    ...\n} until $x >= 10;\n=end code\n\nNote that Perl's unadorned C<do> block ('C<do {...}>') behaves the same\nwhen used in Raku.\n\n=head3 C<for> C<foreach>\n\nNote first this common misunderstanding about the C<for> and C<foreach>\nkeywords: Many programmers think that they distinguish between the C-style\nthree-expression form and the list-iterator form; they do not! In fact,\nthe keywords are interchangeable; the Perl compiler looks for the\nsemicolons within the parentheses to determine which type of loop to parse.\n\nThe C-style three-factor form now uses the C<loop> keyword, and is\notherwise unchanged. The parentheses B<are> still required.\n\n=for code :lang<perl>\nfor  ( my $i = 1; $i <= 10; $i++ ) { ... } # Perl\n=for code\nloop ( my $i = 1; $i <= 10; $i++ ) { ... } # Raku\n\n\nThe loop-iterator form is named C<for> in Raku and C<foreach> is no longer a keyword.\nThe C<for> loop has the following rules:\n=item parentheses are optional;\n=item the iteration variable, if any, has been moved from appearing before the list, to\nappearing after the list and an added arrow operator;\n=item the iteration variable is now always lexical: C<my> is neither needed nor\nallowed;\n=item the iteration variable is a I<read-only> alias to the current list element (in Perl\nit is a I<read-write> alias!). If a read-write alias is required, change the C«->»  before the iteration\nvariable to a C«<->». When translating from Perl, inspect the use of the loop variable to decide if\nread-write is needed.\n\n=for code :lang<perl>\nfor my $car (@cars)  {...} # Perl; read-write\n=for code :preamble<no strict;>\nfor @cars  -> $car   {...} # Raku; read-only\nfor @cars <-> $car   {...} # Raku; read-write\n\nIn Raku and unlike Perl, the default topic C<$_> will behave in the same way,\nbecoming read-only when used as a topic variable.\n\n=for code :lang<perl>\nfor (@cars)      {...} # Perl; $_ is read-write\n=for code :preamble<no strict;>\nfor @cars        {...} # Raku; $_ is read-only\nfor @cars <-> $_ {...} # Raku; $_ is also read-write\n\nIt is possible to consume more than one element of the list in each iteration\nsimply specifying more than one variable after the arrow operator:\n\n=begin code\nmy @array = 1..10;\nfor @array -> $first, $second {\n    say \"First is $first, second is $second\";\n}\n=end code\n\nFor cases in which the number of elements iterated over isn't a multiple\nof the number of variables after the arrow operator, you can provide variables\nwith default values:\n\n=begin code\nmy @array = 1..9;\nfor @array -> $first, $second = 0 {\n    say \"First is $first, second is $second\";\n}\n=end code\n\n=head3 C<each>\n\nHere is the equivalent to Perl’s C<while…each(%hash)> or C<while…each(@array)>\n(i.e., iterating over both the keys/indices and values of a data structure) in\nRaku:\n\n=for code :lang<perl>\nwhile (my ($i, $v) = each(@array)) { ... } # Perl\n=for code :preamble<no strict;>\nfor @array.kv -> $i, $v { ... } # Raku\n\n=for code :lang<perl>\nwhile (my ($k, $v) = each(%hash)) { ... } # Perl\n=for code :preamble<no strict;>\nfor %hash.kv -> $k, $v { ... } # Raku\n\n=head2 Flow control statements\n\nUnchanged:\n\n=item C<next>\n=item C<last>\n=item C<redo>\n\n=head3 C<continue>\n\nThere is no longer a C<continue> block.\nInstead, use a C<NEXT> block (phaser) within the body of the loop.\n\n=for code :lang<perl>\n# Perl\n    my $str = '';\n    for (1..5) {\n        next if $_ % 2 == 1;\n        $str .= $_;\n    }\n    continue {\n        $str .= ':'\n    }\n\n=for code\n# Raku\n    my $str = '';\n    for 1..5 {\n        next if $_ % 2 == 1;\n        $str ~= $_;\n        NEXT {\n            $str ~= ':'\n        }\n    }\n\nPlease note that phasers don't really need a block.  This can be very handy\nwhen you don't want another scope:\n\n=for code\n# Raku\n    my $str = '';\n    for 1..5 {\n        next if $_ % 2 == 1;\n        $str ~= $_;\n        NEXT $str ~= ':';\n    }\n\n\n=head1 Functions\n\n=comment NOTE FOR EDITORS: When adding functions, please place them in\n                           alphabetical order.\n\n=head2 Built-ins with bare blocks\n\nBuiltins that previously accepted a bare block followed, without\na comma, by the remainder of the arguments will now\nrequire a comma between the block and the arguments e.g. C<map>, C<grep>,\netc.\n\n=for code :lang<perl>\nmy @results = grep { $_ eq \"bars\" } @foo; # Perl\n=for code :preamble<no strict;>\nmy @results = grep { $_ eq \"bars\" }, @foo; # Raku\n\n\n=head2 C<delete>\n\nTurned into an adverb of the\nL<C<{}> hash subscripting|#{}_Hash_indexing/slicing>\nand L<C<[]> array subscripting|#[]_Array_indexing/slicing> operators.\n\n=for code :lang<perl>\nmy $deleted_value = delete $hash{$key};  # Perl\n=for code :preamble<no strict;>\nmy $deleted_value = %hash{$key}:delete;  # Raku - use :delete adverb\n\n=for code :lang<perl>\nmy $deleted_value = delete $array[$i];  # Perl\n=for code :preamble<no strict;>\nmy $deleted_value = @array[$i]:delete;  # Raku - use :delete adverb\n\n=head2 C<exists>\n\nTurned into an adverb of the\nL<C<{}> hash subscripting|#{}_Hash_indexing/slicing>\nand L<C<[]> array subscripting|#[]_Array_indexing/slicing> operators.\n\n=for code :lang<perl>\nsay \"element exists\" if exists $hash{$key};  # Perl\n=for code :preamble<no strict;>\nsay \"element exists\" if %hash{$key}:exists;  # Raku - use :exists adverb\n\n=for code :lang<perl>\nsay \"element exists\" if exists $array[$i];  # Perl\n=for code :preamble<no strict;>\nsay \"element exists\" if @array[$i]:exists;  # Raku - use :exists adverb\n\n=head1 Regular expressions ( regex / regexp )\n\n=head2 Change C<=~> and C<!~> to C<~~> and C<!~~> .\n\nIn Perl, matches and substitutions are done against a variable using the\nC<=~> regexp-binding op.\n\nIn Raku, the C<~~> smartmatch op is used instead.\n\n=for code :lang<perl>\nnext if $line  =~ /static/  ; # Perl\n=for code :preamble<no strict;>\nnext if $line  ~~ /static/  ; # Raku\n\n=for code :lang<perl>\nnext if $line  !~ /dynamic/ ; # Perl\n=for code :preamble<no strict;>\nnext if $line !~~ /dynamic/ ; # Raku\n\n=for code :lang<perl>\n$line =~ s/abc/123/;          # Perl\n=for code :preamble<no strict;>\n$line ~~ s/abc/123/;          # Raku\n\nAlternately, the new C<.match> and C<.subst> methods can be used. Note that\nL<C<.subst> is non-mutating|/routine/subst>.\n\n=head2 Captures start with 0, not 1\n\n=for code :lang<perl>\n/(.+)/ and print $1; # Perl\n=for code\n/(.+)/ and print $0; # Raku\n\n=head2 Move modifiers\n\nMove any modifiers from the end of the regex to the beginning. This may\nrequire you to add the optional C<m> on a plain match like C«/abc/».\n\n=for code :lang<perl>\nnext if $line =~    /static/i ; # Perl\n=for code :preamble<no strict;>\nnext if $line ~~ m:i/static/  ; # Raku\n\n=head2 Add :P5 or :Perl5 adverb\n\nIf the actual regex is complex, you may want to use it as-is (with some exceptions),\nby adding the C<P5> modifier.\n\n=for code :lang<perl>\nnext if $line =~    m/[aeiou]/   ; # Perl\n=for code :preamble<no strict;>\nnext if $line ~~ m:P5/[aeiou]/   ; # Raku, using P5 modifier\nnext if $line ~~ m/  <[aeiou]> / ; # Raku, native new syntax\n\nIf the Perl regex has any modifiers, move them from the end and place them\nafter the C<P5> modifier. Each modifier will have to be separated from any\nothers by a colon. For example:\n\n=for code :lang<perl>\nmy $a = \"abcabc\";\nmy $b = $a;\n$a =~ s/abcaBc//gi;  # Perl 5\n$a ~~ s:P5:g:i/ab//; # Raku, using P5 modifier\n$b ~~ s:gi/ab//;     # Raku, native new syntax\nsay $a;\nsay $b;\n\nAnother accommodation required with the P5 syntax is to replace curly braces\nwith square brackets when specifying Unicode in the expression:\n\n=for code :lang<perl>\nnext if $line =~ m/\\x{2043};\nnext if $line ~~ m:P5/\\x[2043]/;\nnext if $line ~~ /\\x[2043]/;\n\nPlease note that the Perl regular expression syntax dates from many years\nago and may lack features that have been added since the beginning of the\nRaku project. Two such features not implemented in Raku for the P5\nsyntax are the Perl Unicode property matchers C<\\p{}> and C<\\P{}>.\n\n=head2 Special matchers generally fall under the C«<>» syntax\n\nThere are many cases of special matching syntax that Perl regexes\nsupport. They won't all be listed here but often, instead of being\nsurrounded by C<()>, the assertions will be surrounded by C«<>».\n\nFor character classes, this means that:\n\n=item C<[abc]> becomes C«<[abc]>»\n\n=item C<[^abc]> becomes C«<-[abc]>»\n\n=item C<[a-zA-Z]> becomes C«<[a..zA..Z]>»\n\n=item C<[[:upper:]]> becomes C«<:Upper>»\n\n=item C<[abc[:upper:]]> becomes C«<[abc]+:Upper>»\n\nFor lookaround assertions:\n\n=item C<(?=[abc])> becomes C«<?[abc]>»\n\n=item C<(?=ar?bitrary* pattern)> becomes C«<before ar?bitrary* pattern>»\n\n=item C<(?!=[abc])> becomes C«<![abc]>»\n\n=item C<(?!=ar?bitrary* pattern)> becomes C«<!before ar?bitrary* pattern>»\n\n=item C«(?<=ar?bitrary* pattern)» becomes C«<after ar?bitrary* pattern>»\n\n=item C«(?<!ar?bitrary* pattern)» becomes C«<!after ar?bitrary* pattern>»\n\nFor more info see L«lookahead assertions|/language/regexes#Lookahead_assertions».\n\n(Unrelated to C«<>» syntax, the \"lookaround\" C</foo\\Kbar/> becomes C«/foo <( bar )> /»\n\n=item C<(?(?{condition))yes-pattern|no-pattern)> becomes C«[ <?{condition}>\n      yes-pattern | no-pattern ]»\n\n=head2 Longest token matching (LTM) displaces alternation\n\nIn Raku regexes, C<|> does LTM, which decides which alternation wins\nan ambiguous match based off of a set of rules, rather than about which\nwas written first.\n\nThe simplest way to deal with this is just to change any C<|> in your\nPerl regex to a C<||>.\n\nHowever, if a regex written with C<||> is inherited or composed into a grammar\nthat uses C<|> either by design or typo, the result may not work as expected.\nSo when the matching process becomes complex, you finally need to have some\nunderstanding of both, especially how LTM strategy works. Besides, C<|> may be\na better choice for grammar reuse.\n\n=head2 Named captures\n\nThese work in a slightly different way; also they only work in the latest\nversions of Perl.\n\n=for code :lang<perl>\nuse v5.22;\n\"þor is mighty\" =~ /is (?<iswhat>\\w+)/n;\nsay $+{iswhat};\n\nThe C<iswhat> within a non-capturing group is used to actually capture what is\nbehind, and up to the end of the group (the C<)>). The capture goes to the C<%+>\nhash under the key with the name of the capture. In Raku\nL<named captures work this way|/language/regexes#Capturing_groups>\n\n=for code\n\"þor is mighty\" ~~ /is \\s+ $<iswhat>=(\\w+)/;\nsay $<iswhat>;\n\nAn actual assignment is made within the regular expression; that's the same\nsyntax used for the variable outside it.\n\n=begin comment\nTODO more rules. Use L<< C<translate_regex.pl> from Blue Tiger|https://github.com/Util/Blue_Tiger/>> in the meantime.\n=end comment\n\n=head3 Comments\n\nAs with Perl, comments work as usual in regexes.\n\n    / word #`(match lexical \"word\") /\n\n=head1 BEGIN, UNITCHECK, CHECK, INIT and END\n\nExcept for C<UNITCHECK>, all of these special blocks exist in Raku as well.\nIn Raku, these are called L<Phasers|/language/phasers>.   But there are some\ndifferences!\n\n=head2 UNITCHECK becomes CHECK\n\nThere is currently B<no> direct equivalent of C<CHECK> blocks in Raku. The\nC<CHECK> phaser in Raku has the same semantics as the C<UNITCHECK> block in\nPerl: it gets run whenever the compilation unit in which it occurs has\nfinished parsing.  This is considered a much saner semantic than the current\nsemantics of C<CHECK> blocks in Perl.  But for compatibility reasons, it was\nimpossible to change the semantics of C<CHECK> blocks in Perl, so a\nC<UNITCHECK> block was introduced in 5.10.  Consequently, it was decided that\nthe Raku C<CHECK> phaser would follow the saner Perl C<UNITCHECK> semantics.\n\n=head2 No block necessary\n\nIn Perl, these special blocks B<must> have curly braces, which implies a\nseparate scope.  In Raku this is not necessary, allowing these special\nblocks to share their scope with the surrounding lexical scope.\n\n=for code :lang<perl>\nmy $foo;             # Perl\nBEGIN { $foo = 42 }\n=for code\nBEGIN my $foo = 42;  # Raku\n\n=head2 Changed semantics with regards to precompilation\n\nIf you put C<BEGIN> and C<CHECK> phasers in a module that is being precompiled,\nthen these phasers will B<only> be executed during precompilation and B<not>\nwhen a precompiled module is being loaded.  So when porting module code from\nPerl, you may need to change C<BEGIN> and C<CHECK> blocks to C<INIT> blocks to\nensure that they're run when loading that module.\n\n=head1 Pragmas\n\n=head3 C<strict>\n\nStrict mode is now on by default.\n\n=head3 C<warnings>\n\nWarnings are now on by default.\n\nC<no warnings> can be achieved by wrapping code in a C<quietly> {} block.\n\n=head3 C<autodie>\n\nThe functions which were altered by C<autodie> to throw exceptions on\nerror, now generally return L<C<Failure>|/type/Failure>s by default.  You can test a L<C<Failure>|/type/Failure>\nfor definedness / truthiness without any problem.  If you use the L<C<Failure>|/type/Failure>\nin any other way, then the L<C<Exception>|/type/Exception> that was encapsulated by the L<C<Failure>|/type/Failure>\nwill be thrown.\n\n=for code :lang<perl>\n# Perl\nopen my $i_fh, '<', $input_path;  # Fails silently on error\nuse autodie;\nopen my $o_fh, '>', $output_path; # Throws exception on error\n\n=for code :preamble<no strict;>\n# Raku\nmy $i_fh = open $input_path,  :r; # Returns Failure on error\nmy $o_fh = open $output_path, :w; # Returns Failure on error\n\nBecause you can check for truthiness without any problem, you can use the\nresult of an C<open> in an C<if> statement:\n\n=for code :preamble<no strict;>\n# Raku\nif open($input_path,:r) -> $handle {\n    .say for $handle.lines;\n}\nelse {\n    # gracefully handle the fact that the open() failed\n}\n\n=head3 C<base>, C<parent>\n\nBoth C<use base> and C<use parent> have been replaced in Raku by the\nC<is> keyword, in the class declaration.\n\n=for code :lang<perl>\n# Perl\npackage Cat;\nuse base qw(Animal);\n\n=for code :preamble<class Animal {}>\n# Raku\nclass Cat is Animal {}\n\nNote that the C<Animal> class must be B<known> at compilation time prior to\nbe able to inherit from it.\n\n=head3 C<bigint> C<bignum> C<bigrat>\n\nNo longer relevant.\n\nL<C<Int>|/type/Int> is now arbitrary precision, as is the numerator of L<C<Rat>|/type/Rat> (the\ndenominator is limited to C<2**64>, after which it will automatically\nupgrade to L<C<Num>|/type/Num> to preserve performance).  If you want a L<C<Rat>|/type/Rat> with\nan arbitrary-precision denominator, L<C<FatRat>|/type/FatRat> is available.\n\n=head3 C<constant>\n\nIn Raku, C<constant> is a declarator for variables, just like C<my>, except\nthe variable is permanently locked to the result of its initialization\nexpression (evaluated at compile time).\n\nSo, change the C«=>» to C<=>.\n\n=for code :lang<perl>\nuse constant DEBUG => 0; # Perl\n=for code :preamble<no strict;>\nconstant DEBUG = 0;      # Raku\n\n=for code :lang<perl>\nuse constant pi => 4 * atan2(1, 1); # Perl\n=for code\ntau, pi, e, i; # built-in constants in Raku\nτ, π, 𝑒        # and their unicode equivalents\n\n=head3 C<encoding>\n\nAllows you to write your script in non-ascii or non-utf8. Raku uses, for the\ntime being, only utf8 for its scripts.\n\n=head3 C<use integer>\n\nPerl pragma to use integer arithmetic instead of floating point.  There is\nno such thing in Raku.  If you use native integers in your calculations,\nthen this will be the closest thing.\n\n=for code\n#Raku\nmy int $foo = 42;\nmy int $bar = 666;\nsay $foo * $bar;    # uses native integer multiplication\n\n=head3 C<use lib>\n\nManipulate where modules are looked up at compile time.  The underlying logic is\nB<very> different from Perl, but in the case you are using an equivalent\nsyntax, C<use lib> in Raku works the same as in Perl.\n\n=head3 C<use mro>\n\nNo longer relevant.\n\nIn Raku, method calls now always use the C3 method resolution order.\nIf you need to find out parent classes of a given class, you can invoke the\nC<mro> metamethod thusly:\n\n=for code :preamble<class Animal {}>\nsay Animal.^mro;    # .^ indicates calling a metamethod on the object\n\n=head3 C<use utf8>\n\nNo longer relevant: in Raku, source code is expected to be in utf8 encoding.\n\n=head3 C<use vars>\n\nDiscouraged in Perl. See L<https://perldoc.perl.org/vars.html>.\n\nYou should refactor your Perl code to remove the need for C<use vars>,\nbefore translating into Raku.\n\n\n\n=head1 Command-line flags\n\nUnchanged:\n\n-c -e -h -I -n -p -v -V\n\n=head3 C<-a>\n\nChange your code to use C<.split> manually.\n\n=head3 C<-F>\n\nChange your code to use C<.split> manually.\n\n=head3 C<-l>\n\nThis is now the default behavior.\n\n=head3 C<-M> C<-m>\n\nOnly C<-M> remains. And, as you can no longer use the \"no Module\" syntax, the\nuse of C<-> with C<-M> to \"no\" a module is no longer available.\n\n=head3 C<-E>\n\nSince all features are already enabled, just use lowercase C<-e> .\n\n=head3 C<-d>, C<-dt>, C<-d:foo>, C<-D>, etc.\n\nReplaced with the C<++BUG> metasyntactic option.\n\n=head3 -s\n\nSwitch parsing is now done by the parameter list of the C<MAIN> subroutine.\n\n=for code :lang<perl>\n# Perl\n    #!/usr/bin/perl -s\n    if ($xyz) { print \"$xyz\\n\" }\n./example.pl -xyz=5\n5\n\n=for code\n# Raku\n    sub MAIN( Int :$xyz ) {\n        say $xyz if $xyz.defined;\n    }\n\n=for code :lang<shell>\nraku example.raku --xyz=5\n5\nraku example.raku -xyz=5\n5\n\n=item C<-t>\n\nRemoved.\n\n=item C<-P> C<-u> C<-U> C<-W> C<-X>\n\nRemoved. See\nL<Removed Syntactic Features|https://github.com/Raku/old-design-docs/blob/master/S19-commandline.pod#Removed_Syntactic_Features>.\n\n=item C<-w>\n\nThis is now the default behavior.\n\n=item C<-S>, C<-T>.\n\nThis has been eliminated. Several ways to\nL<replicate \"taint\" mode are discussed in Reddit|https://www.reddit.com/r/perl6/comments/718z4o/taint_mode_for_perl_6/>.\n\n=head1 File-related operations\n\n=head2 Reading the lines of a text file into an array\n\nIn Perl, a common idiom for reading the lines of a text file goes\nsomething like this:\n\n=for code :lang<perl>\nopen my $fh, \"<\", \"file\" or die \"$!\";\nmy @lines = <$fh>;                # lines are NOT chomped\nclose $fh;\n\nIn Raku, this has been simplified to\n\n    my @lines = \"file\".IO.lines;  # auto-chomped\n\nDo I<not> be tempted to try slurping in a file and splitting the resulting\nstring on newlines as this will give an array with a trailing empty element,\nwhich is one more than you probably expect (it's also more complicated),\ne.g.:\n\n    # initialize the file to read\n    spurt \"test-file\", q:to/END/;\n    first line\n    second line\n    third line\n    END\n    # read the file\n    my @lines = \"test-file\".IO.slurp.split(/\\n/);\n    say @lines.elems;    #-> 4\n\nIf for some reason you do want to slurp the file first, then you can call\nthe C<lines> method on the result of C<slurp> instead:\n\n    my @lines = \"test-file\".IO.slurp.lines;  # also auto-chomps\n\nAlso, be aware that C<$!> is not really relevant for file IO operation failures\nin Raku. An IO operation that fails will return a L<C<Failure>|/type/Failure> instead of\nthrowing an exception. If you want to return the failure message, it is in the\nfailure itself, not in C<$!>. To do similar IO error checking and reporting as\nin Perl:\n\n    my $fh = open('./bad/path/to/file', :w) or die $fh;\n\nI<Note>: C<$fh> instead of C<$!>. Or, you can set C<$_> to the failure and die\nwith $_:\n\n    my $fh = open('./bad/path/to/file', :w) orelse .die; # Raku\n\nAny operation that tries to use the failure will cause the program to fault and\nterminate. Even just a call to the C<.self> method is sufficient.\n\n    my $fh = open('./bad/path/to/file', :w).self;\n\n=head2 Capturing the standard output of executables.\n\nWhereas in Perl you would do:\n\n=for code :lang<perl>\nmy $arg = 'Hello';\nmy $captured = `echo \\Q$arg\\E`;\nmy $captured = qx(echo \\Q$arg\\E);\n\nOr using C<String::ShellQuote> (because C<\\Q…\\E> is not completely right):\n\n=for code :lang<perl>\nmy $arg = shell_quote 'Hello';\nmy $captured = `echo $arg`;\nmy $captured = qx(echo $arg);\n\nIn Raku, you will probably want to run commands without using the shell:\n\n    my $arg = 'Hello';\n    my $captured = run('echo', $arg, :out).out.slurp;\n    my $captured = run(«echo \"$arg\"», :out).out.slurp;\n\nYou can also use the shell if you really want to:\n\n    my $arg = 'Hello';\n    my $captured = shell(\"echo $arg\", :out).out.slurp;\n    my $captured = qqx{echo $arg};\n\nBut beware that in this case there is B<no protection at all>! C<run> does\nnot use the shell, so there is no need to escape the arguments (arguments\nare passed directly). If you are using C<shell> or C<qqx>, then everything\nends up being one long string which is then passed to the shell. Unless you\nvalidate your arguments very carefully, there is a high chance of introducing\nshell injection vulnerabilities with such code.\n\n=head1 Environment variables\n\n=head2 Perl module library path\n\nPerl use C<PERLLIB> and C<PERL5LIB> to specify extra search paths for modules\nand Both of them are ignored by Raku. Instead, you need to use X<C<RAKULIB>|Reference,RAKULIB>.\nThe directory separator also changed from ':' to ','.\n\n=for code :lang<shell>\n$ export PERL5LIB=/module/dir1:/module/dir2;\n\nis\n\n=for code :lang<shell>\n$ export RAKULIB=/module/dir1,/module/dir2;\n\nAs with Perl, if you don't specify C<RAKULIB>, you need to specify the\nlibrary path within the program via the C<use lib> pragma:\n\n=for code :lang<perl>\nuse lib '/some/module/lib'\n\nNote that C<RAKULIB> is more of a developer convenience in Raku (as\nopposed to the equivalent usage of C<PERL5LIB> in Perl) and shouldn't be\nused by module consumers as it could be removed in the future.  This is\nbecause Raku's module loading isn't directly compatible with operating\nsystem paths.\n\n=head1 Misc.\n\n=head2 C<'0'> is True\n\nUnlike Perl, a string containing nothing but zero ('0') is C<True>. As Raku\nhas types in core, that makes more sense. This also means the common pattern:\n\n=for code :lang<perl>\n... if defined $x and length $x; # or just length() in modern perls\n\nIn Raku becomes a simple\n\n=for code :preamble<no strict;>\n... if $x;\n\n=head2 C<dump>\n\nGone.\n\nThe Raku design allows for automatic and transparent saving-and-loading of\ncompiled bytecode.\n\nRakudo supports this only for modules so far.\n\n=head2 AUTOLOAD\n\nThe L«C<FALLBACK> method|/language/typesystem#index-entry-FALLBACK_(method)»\nprovides similar functionality.\n\n=head2 Importing specific functions from a module\n\nIn Perl it is possible to selectively import functions from a given\nmodule like so:\n\n=for code :lang<perl>\nuse ModuleName qw{foo bar baz};\n\nIn Raku one specifies the functions which are to be exported by using\nthe C<is export> role on the relevant subs; I<all> subs with this role\nare then exported.  Hence, the following module C<Bar> exports the subs\nC<foo> and C<bar> but not C<baz>:\n\n=begin code :solo\nunit module Bar;\n\nsub foo($a) is export { say \"foo $a\" }\nsub bar($b) is export { say \"bar $b\" }\nsub baz($z) { say \"baz $z\" }\n=end code\n\nTo use this module, simply C<use Bar> and the functions C<foo> and\nC<bar> will be available\n\n=for code :skip-test<needs dummy module>\nuse Bar;\nfoo(1);    #=> \"foo 1\"\nbar(2);    #=> \"bar 2\"\n\nIf one tries to use C<baz> an \"Undeclared routine\" error is raised at\ncompile time.\n\nSo, how does one recreate the Perl behavior of being able to\nselectively import functions? By defining an C<EXPORT> sub inside the\nmodule which specifies the functions to be exported and removing the\nC<module Bar> statement.\n\nThe former module C<Bar> now is merely a file called C<Bar.rakumod> with the\nfollowing contents:\n\n=begin code :preamble<no strict;>\nsub EXPORT(*@import-list) {\n    my %exportable-subs =\n        '&foo' => &foo,\n        '&bar' => &bar,\n        ;\n    my %subs-to-export;\n    for @import-list -> $import {\n        if grep $sub-name, %exportable-subs.keys {\n            %subs-to-export{$sub-name} = %exportable-subs{$sub-name};\n        }\n    }\n    return %subs-to-export;\n}\n\nsub foo($a, $b, $c) { say \"foo, $a, $b, $c\" }\nsub bar($a) { say \"bar, $a\" }\nsub baz($z) { say \"baz, $z\" }\n=end code\n\nNote that the subs are no longer explicitly exported via the C<is\nexport> role, but by an C<EXPORT> sub which specifies the subs\nin the module we want to make available for export and then we are\npopulating a hash containing the subs which will actually be exported.\nThe C<@import-list> is set by the C<use> statement in the calling code\nthus allowing us to selectively import the subs made available by the\nmodule.\n\nSo, to import only the C<foo> routine, we do the following in the\ncalling code:\n\n=for code :skip-test<needs dummy module>\nuse Bar <foo>;\nfoo(1);       #=> \"foo 1\"\n\nHere we see that even though C<bar> is exportable, if we don't\nexplicitly import it, it's not available for use.  Hence this causes an\n\"Undeclared routine\" error at compile time:\n\n=for code :skip-test<needs dummy module>\nuse Bar <foo>;\nfoo(1);\nbar(5);       #!> \"Undeclared routine: bar used at line 3\"\n\nHowever, this will work\n\n=for code :skip-test<needs dummy module>\nuse Bar <foo bar>;\nfoo(1);       #=> \"foo 1\"\nbar(5);       #=> \"bar 5\"\n\nNote also that C<baz> remains unimportable even if specified in the\nC<use> statement:\n\n=for code :skip-test<needs dummy module>\nuse Bar <foo bar baz>;\nbaz(3);       #!> \"Undeclared routine: baz used at line 2\"\n\nIn order to get this to work, one obviously has to jump through many\nhoops. In the standard use-case where one specifies the functions to be\nexported via the C<is export> role, Raku automatically creates the\nC<EXPORT> sub in the correct manner for you, so one should consider very\ncarefully whether or not writing one's own C<EXPORT> routine is\nworthwhile.\n\n=head2 Importing groups of specific functions from a module\n\nIf you would like to export groups of functions from a module, you just\nneed to assign names to the groups, and the rest will work\nautomagically. When you specify C<is export> in a sub declaration, you\nare in fact adding this subroutine to the C<:DEFAULT> export group.  But\nyou can add a subroutine to another group, or to multiple groups:\n\n=for code :solo\nunit module Bar;\nsub foo() is export { }                   # added by default to :DEFAULT\nsub bar() is export(:FNORBL) { }          # added to the FNORBL export group\nsub baz() is export(:DEFAULT:FNORBL) { }  # added to both\n\nSo now you can use the C<Bar> module like this:\n\n=for code :skip-test<needs dummy module>\nuse Bar;                     # imports foo / baz\nuse Bar :FNORBL;             # imports bar / baz\nuse Bar :ALL;                # imports foo / bar / baz\n\nNote that C<:ALL> is an auto-generated group that encompasses B<all>\nsubroutines that have an C<is export> trait.\n\n=head1 Core modules\n\n=head3 C<Data::Dumper>\n\nIn Perl, the L<Data::Dumper|https://metacpan.org/pod/Data::Dumper>\nmodule was used for serialization, and for\ndebugging views of program data structures by the programmer.\n\nIn Raku, these tasks are accomplished with the C<.raku> method, which\nevery object has.\n\n=begin code :lang<perl>\n# Given:\n    my @array_of_hashes = (\n        { NAME => 'apple',   type => 'fruit' },\n        { NAME => 'cabbage', type => 'no, please no' },\n    );\n# Perl\n    use Data::Dumper;\n    $Data::Dumper::Useqq = 1;\n    print Dumper \\@array_of_hashes; # Note the backslash.\n=end code\n\n=for code :preamble<no strict;>\n# Raku\nsay @array_of_hashes.raku; # .raku on the array, not on its reference.\n\n\nIn Perl, Data::Dumper has a more complex optional calling convention,\nwhich allows for naming the VARs.\n\nIn Raku, placing a colon in front of the variable's sigil turns it into a\nPair, with a key of the var name, and a value of the var value.\n\n=begin code :lang<perl>\n# Given:\n    my ( $foo, $bar ) = ( 42, 44 );\n    my @baz = ( 16, 32, 64, 'Hike!' );\n# Perl\n    use Data::Dumper;\n    print Data::Dumper->Dump(\n        [     $foo, $bar, \\@baz   ],\n        [ qw(  foo   bar   *baz ) ],\n    );\n# Output\n#    $foo = 42;\n#    $bar = 44;\n#    @baz = (\n#             16,\n#             32,\n#             64,\n#             'Hike!'\n#           );\n=end code\n\n=begin code :preamble<no strict;>\n# Raku\nsay [ :$foo, :$bar, :@baz ].raku;\n# OUTPUT: «[\"foo\" => 42, \"bar\" => 44, \"baz\" => [16, 32, 64, \"Hike!\"]]␤»\n=end code\n\nThere is also a Rakudo-specific debugging aid for developers called C<dd> (Tiny\nData Dumper, so tiny it lost the \"t\").  This will print the C<.raku>\nrepresentation plus some extra information that could be introspected, of the\ngiven variables on STDERR:\n\n=begin code :preamble<no strict;> :ok-test<dd>\n# Raku\ndd $foo, $bar, @baz;\n# OUTPUT: «Int $foo = 42␤Int $bar = 44␤Array @baz = [16, 32, 64, \"Hike!\"]␤»\n=end code\n\n=head3 C<Getopt::Long>\n\nSwitch parsing is now done by the parameter list of the C<MAIN> subroutine.\n\n=begin code :lang<perl>\n# Perl\n    use 5.010;\n    use Getopt::Long;\n    GetOptions(\n        'length=i' => \\( my $length = 24       ), # numeric\n        'file=s'   => \\( my $data = 'file.dat' ), # string\n        'verbose'  => \\( my $verbose           ), # flag\n    ) or die;\n    say $length;\n    say $data;\n    say 'Verbosity ', ($verbose ? 'on' : 'off') if defined $verbose;\nperl example.pl\n    24\n    file.dat\nperl example.pl --file=foo --length=42 --verbose\n    42\n    foo\n    Verbosity on\n\nperl example.pl --length=abc\n    Value \"abc\" invalid for option length (number expected)\n    Died at c.pl line 3.\n=end code\n\n=begin code\n# Raku\n    sub MAIN( Int :$length = 24, :file($data) = 'file.dat', Bool :$verbose ) {\n        say $length if $length.defined;\n        say $data   if $data.defined;\n        say 'Verbosity ', ($verbose ?? 'on' !! 'off');\n    }\n=end code\n\n=begin code :lang<shell>\nraku example.raku\n    24\n    file.dat\n    Verbosity off\nraku example.raku --file=foo --length=42 --verbose\n    42\n    foo\n    Verbosity on\nraku example.raku --length=abc\n    Usage:\n      c.raku [--length=<Int>] [--file=<Any>] [--verbose]\n=end code\n\nNote that Raku auto-generates a full usage message on error in\ncommand-line parsing.\n\n\n=head1 Automated translation\n\nA quick way to find the Raku version of a Perl construct, is to run it\nthrough an automated translator.\n\nB<NOTE:> None of these translators are yet complete.\n\n=head2 Blue Tiger\n\nThis project is dedicated to automated modernization of Perl code. It does\nnot (yet) have a web front-end, and so must be locally installed to be\nuseful. It also contains a separate program to translate Perl regexes\ninto Raku.\n\nL<https://github.com/Util/Blue_Tiger/>\n\n=head2 Perlito\n\nOnline translator!\n\nThis project is a suite of Perl cross-compilers, including Perl to Raku\ntranslation. It has a web front-end, and so can be used without\ninstallation. It only supports a subset of Perl syntax so far.\n\nL<https://fglock.github.io/Perlito/perlito/perlito5.html>\n\n=head2 Perl-ToPerl6\n\nThe late Jeff Goff's\nL<Perl::ToPerl6|https://metacpan.org/release/JGOFF/Perl-ToPerl6-0.03> module for\nPerl is designed around Perl::Critic's framework. It aims to convert Perl to\ncompilable (if not necessarily running) Raku code with the bare minimum of\nchanges. Code transformers are configurable and pluggable, so you can create and\ncontribute your own transformers, and customize existing transformers to your\nown needs. You can install the latest release from CPAN, or follow the project\nlive on GitHub. An online converter may become available at some point.\n\n=head1 Other sources of translation knowledge\n\n=item L<https://perlgeek.de/en/article/5-to-6>\n=item L<https://github.com/Util/Blue_Tiger/>\n=item L<https://perl6advent.wordpress.com/2011/12/23/day-23-idiomatic-perl-6/>\n=item L</language/perl-overview|/language/perl-overview>\n\n=end pod\n"
  },
  {
    "path": "doc/Language/perl-op.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"migration\")\n\n=TITLE Perl to Raku guide - operators\n\n=SUBTITLE Operators in Perl to Raku: equivalencies and variations\n\n=head1 DESCRIPTION\n\nA (hopefully) comprehensive list of Perl operators with their Raku\nequivalents with notes on variations between them where necessary.\n\n=head1 NOTE\n\nThis document I<does not> explain the operators in detail. This document\nis an attempt to guide you from the operators in Perl's C<perlop>\ndocument to their equivalents in Raku. For full documentation on the\nRaku equivalents, please see the\nL<Raku documentation|/language/operators>.\n\n=head2 Operator precedence and associativity\n\nThe operator precedence table is somewhat different in Raku than it is\nin Perl, so it will not be detailed here. If you need to know the\nprecedence and associativity of a given operator in Raku, refer to\nL<Operator Precedence|/language/operators#Operator_precedence>.\n\n=head2 Terms and list operators\n\nThe things listed in Perl's C<perlop> document as unary and list\noperators in this section tend to be things that can also be thought of\nas functions, such as C<print> and C<chdir>. As such, you can find\ninformation about them in the L<functions|/language/perl-func>\nguide. Parentheses are still used for grouping.  There is one caveat: in\nRaku, it's the C<,> (comma) that creates lists, B<not> parentheses.\nSo:\n\n=begin code\nmy @foo = 1,2,3,4,5;   # no parentheses needed\n.say for 1,2,3,4,5;    # also no parentheses\n\nmy $scalar = (1);      # *not* a list, as there is no comma\nmy $list   = (1,);     # a List in a scalar container\n=end code\n\n=head2 The arrow operator\n\nFor the Perl C«=>» arrow, see the\nL<Comma operator|/language/perl-op#Comma_operator>.\n\nThe dereferencing operator, C«->», is replaced by the dot, which is\nalso used for method calls.  So Perl's C«$arrayref->[7]» becomes\nRaku's C<$arrayref.[7]> and C«$user->name» becomes C<$user.name>.\nNote that dereferencing is rare in Raku.\n\nRaku uses the C«->» to attach L<C<Signature>|/type/Signature>s to\nL<C<Block>|/type/Block>s.\n\n=head2 Auto-increment and auto-decrement\n\nWork as in Perl. The one possible caveat is that they function by\ncalling the C<succ> method for C<++> and the C<pred> method for C<-->.\nFor builtin numeric types, this is unlikely to do something unusual, but\ncustom types can define their own C<succ> and C<pred> methods, so in\nthose cases, you should probably take note of what C<++> and C<--> will\nI<actually> do.\n\n=head2 Exponentiation\n\nWorks as you would expect. The caveat in Perl's perlop about C<**>\nbinding more tightly than unary minus (i. e. \"-2**4\" evaluates as \"-(2**4)\"\nrather than \"(-2)**4)\") is also true for Raku.\n\n=head2 Symbolic unary operators\n\nAs in Perl, unary C<!> and C<-> do logical and arithmetic negation,\nrespectively. C<?^> is used for bitwise logical negation, which the\ndocumentation indicates is equivalent to C<!>. It may be relevant to\nnote that these coerce their arguments to L<C<Bool>|/type/Bool> and L<C<Numeric>|/type/Numeric>,\nrespectively.\n\nUnary C<~> is the string context operator in Raku, so use prefix C<+^>\nfor bitwise integer negation. Assumes two's complement.\n\nC<+> I<does> have an effect in Raku, coercing its argument to the\nNumeric type.\n\nUnary C<\\> is no more. If you really want to take a \"reference\" to an existing\nnamed variable, you can use item context, like so: C<$aref = item(@array)>, or\nmaybe more familiarly by prefixing with a C<$>: C<$aref = $@array>.  Please\nnote that you're not really getting a reference, but a scalar container with\nthe referenced object in it.\n\nYou can get a \"reference\" to a named subroutine by using the C<&> sigil:\nC<$sref = &foo>.  Anonymous arrays, hashes, and subs return the underlying\nobject during creation I<right away>: C<$sref = sub { }>.\n\n=head2 Binding operators\n\nC<=~> and C<!~> have been replaced by C<~~> and C<!~~>, respectively.\nThose of you who consider smartmatching broken in Perl will be happy\nto hear that it works much better in Raku, as the stronger typing\nmeans less guesswork. See\nL<the smartmatch documentation|/language/operators#index-entry-smartmatch_operator> for a\nmore extensive explanation of how smartmatch works in Raku.\n\n=head2 Multiplicative operators\n\nBinary C<*>, C</>, and C<%> do multiplication, division, and modulo,\nrespectively, as in Perl.\n\nBinary C<x> is slightly different in Raku, and has a companion.\nC<print '-' x 80;> gives you a string of 80 dashes, but for the Perl\nbehavior of C<@ones = (1) x 80;> giving you a list of 80 \"1\"s, you would\nuse C<@ones = 1 xx 80;>.\n\n=head2 Additive operators\n\nBinary C<+> and C<-> do addition and subtraction, respectively, as you would\nexpect.\n\nAs C<.> is the method call operator, so binary C<~> acts as the\nconcatenation operator in Raku.\n\n=head2 Shift operators\n\nC«<<» and C«>>» have been replaced by C«+<» and C«+>».\n\n=head2 Named unary operators\n\nAs noted above, you'll find these in the L<functions|/language/perl-func>\nguide.\n\n=head2 Relational operators\n\nThese all work as in Perl.\n\n=head2 Equality operators\n\nC<==> and C<!=> both work as in Perl.\n\nC«<=>» and C<cmp> have different behavior in Raku. C«<=>»\ndoes a numeric comparison, but returns C<Order::Less>, C<Order::Same>,\nor C<Order::More> instead of Perl's C<-1>, C<0>, or C<1>. To get the\nPerl behavior (with the change that it returns the L<C<Order>|/type/Order> objects,\nrather than integers) of C<cmp>, you would use the C<leg> operator.\n\nC<cmp> does either C«<=>» or C<leg>, depending on the existing type\nof its arguments.\n\nC<~~> is the smartmatch operator as in Perl, but it's also I<just>\nthe match operator in Raku, as noted above. For how smartmatching\nworks in Raku, see L<the smartmatch documentation|/language/operators#index-entry-smartmatch_operator>.\n\n=head2 Smartmatch operator\n\nSee L<the smartmatch documentation|/language/operators#index-entry-smartmatch_operator>\nfor a more extensive explanation of how smartmatch works in Raku.\n\n=head2 Bitwise And\n\nBinary C<&> is C<+&> in Raku.\n\n=head2 Bitwise Or and Exclusive Or\n\nBitwise OR has changed from C<|> in Perl to C<+|> in Raku.\nSimilarly, bitwise XOR C<^> is C<+^>, except this operates on integers.\n\n=head2 C-style Logical And\n\nUnchanged.\n\n=head2 C-style Logical Or\n\nUnchanged.\n\n=head2 Logical Defined-Or\n\nRemains in Raku as C<//>. Returns the first defined operand, or else\nthe last operand. Also, there is a low precedence version, called\nC<orelse>.\n\n=head2 Range operators\n\nIn list context, C<..> operates as the range operator and should not\nneed to be changed. That said, there are exclusionary range operators\nthat may be useful. These are:\n\n=item infix C<..^> which excludes the endpoint;\n=item infix ^.. which excludes the starting point;\n=item infix C<^..^> which excludes both the starting and ending points;\n=item prefix C<^> which starts from zero excluding the endpoint.\n\nThe following example shows the effects of all the above range operators\n(please note parentheses are used only to allow the method call):\n\n=begin code\n(1..^5).list;  # (1 2 3 4)\n(1^..5).list;  # (2 3 4 5)\n(1^..^5).list; # (2 3 4)\n(^5).list;     # (0 1 2 3 4)\n=end code\n\nIn Perl, in scalar context, the operators C<..> and C<...> work\nas flip-flop operators, even if they are little-known and probably\nless used. Those operators have been replaced in Raku\nby L<ff|/routine/ff> and L<fff|/routine/fff> respectively.\n\n=head2 Conditional operator\n\nThe conditional operator C<? :> has been replaced\nby C<?? !!>:\n\n=for code :lang<perl>\n$x = $ok  ? $yes  : $no;  # Perl\n=for code :preamble<my $x;my $ok;my $yes;my $no>\n$x = $ok ?? $yes !! $no;  # Raku\n\n=head2 Assignment operators\n\nAlthough not fully documented, S03 indicates that the mathematical and\nlogical assignment operators should work as you would expect. The one\nnoticeable change is that C<.=> calls a mutating method on the object on\nthe left (which can also be a type-object).  This allows for the following\nuseful idiom:\n\n=begin code\nclass LongClassName {\n    has $.frobnicate;\n}\nmy LongClassName $bar .= new( frobnicate => 42 ); # no need to repeat class name\n=end code\n\nThis ensures that C<$bar> will only be able to contain a C<LongClassName>\nobject, as well not having to repeat (and possibly misspell) the class name.\n\nC<~=> is the string concatenation assignment, as you might expect with the\nchanges in C<.> and C<~>. Also, the bitwise assignment operators are likely\nnot separated into numeric and string versions (C<&=>, etc., vs. C<&.=>, etc.),\nas that feature is currently experimental in Perl itself - although, again,\nthis is not specifically documented.\n\n=head2 Comma operator\n\nThe comma operator works mostly as expected, but technically it\ncreates L<Lists|/type/List>) or separates arguments in function\ncalls. Also, there is a C<:> variant that turns function calls into\nmethod calls - see L<this page|/language/operators#infix_%3A>.\n\nThe C«=>» operator, or I<fat arrow>, works similarly to the Perl \"fat\ncomma\" in that it allows an unquoted (ordinary) identifier on its left side, but\nin Raku constructs L<C<Pair>|/type/Pair> objects, rather than just functioning as a separator.\nIf you are trying to just literally translate a line of Perl code to Raku,\nit should behave as expected.  To read Raku, take a look at\nL<Adverbial Pair|/language/glossary#Adverbial_pair> which will explain a new syntax.\n\n\n=head2 List operators (rightward)\n\nLike the Named Unary Operators, you'll find these discussed under\nL<Functions|/language/perl-func>.\n\n=head2 Logical Not\n\nThe lower precedence version of C<!>. As with C<!>, coerces its argument\nto L<C<Bool>|/type/Bool>.\n\n=head2 Logical And\n\nLower precedence version of C<&&> as in Perl.\n\n=head2 Logical or and Exclusive Or\n\nC<or> is the low precedence version of C<||>, and C<xor> is the low precedence\nversion of C<^^>.\n\nAdditionally, there is a low precedence version of C<//>, called C<orelse>.\n\n=head2 Quote and quote-like operators\n\nFor all the gory details on quoting constructs, see\nL<quoting|/language/quoting>.\n\nThere is a quoting operator that allows absolute literal strings: C<Q> or\nC<｢…｣>, although the latter might be difficult to find on your keyboard,\ndepending on your keyboard... Backslash escapes do I<not> apply in C<Q> quoted\nstrings. E. g. C<Q{This is still a closing curly brace → \\}> renders \"This is still a\nclosing curly brace → \\\".\n\nC<q> does what you expect, allowing backslash escapes. E. g. C<q{This is\nnot a closing curly brace → \\}, but this is → }> returning \"This is\nnot a closing curly brace → }, but this is →\". As in Perl, you can\nget this behavior with single quotes.\n\nC<qq> allows interpolation of variables. However, by default, only\nscalar variables are interpolated. To get other variables to\ninterpolate, you need to put square brackets after them (the so-called\nL<zen-slice|/language/subscripts#Zen_slices>) to get them to\ninterpolate. E.g. C«@a = <1 2 3>; say qq/@a[] example@example.com/;»\nresults in \"1 2 3 example@example.com\". Hashes interpolate in the same\nmanner: C«%a = 1 => 2, 3 => 4;say \"%a{}\";» results in a space\nseparating the pairs and tabs separating the key from the value in each\npair (because that's the standard stringification of L<C<Pair>|/type/Pair>s, and a hash\nacts as list of L<C<Pair>|/type/Pair>s when stringified). You can also interpolate Raku\ncode in strings using curly braces. For all the details, see\nL<Interpolation|/language/quoting#Interpolation%3A_qq>.\n\nC<qw> works as in Perl, and can also be rendered as C«<...>». E.\ng. C<qw/a b c/> is equivalent to C«<a b c>».\n\nThere is also a version of C<qw> that interpolates, which is C<qqw>. So\nC<my $a = 42;say qqw/$a b c/;> gives you \"42 b c\".\n\nShell quoting is available through C<qx>, but you should note that\nbackticks do not do shell quoting as in Perl, and Perl variables are\nI<not> interpolated in C<qx> strings. If you need to interpolate Perl\nvariables in a shell command string, you can use C<qqx> instead.\n\nThe C<qr> operator is gone from Raku.\n\nC<tr///> works similarly to how it\ndoes in Perl. The one caveat is that ranges are specified differently.\nInstead of using a range \"a-z\", you would use \"a..z\", i. e. with Perl's\nrange operator. C<tr///> has a method version, which is better\ndocumented, called C<.trans>. C<.trans> uses a list of pairs, as\nfollows: C«$x.trans(['a'..'c'] => ['A'..'C'], ['d'..'q'] =>\n['D'..'Q'], ['r'..'z'] => ['R'..'Z']);». A much more extensive\ndescription of the uses of C<.trans> can be found at\nL<https://github.com/Raku/old-design-docs/blob/master/S05-regex.pod#Transliteration>. The C<y///>\nequivalent has been done away with.\n\nHeredocs are specified differently in Raku. You use C<:to> with your quoting\noperator, e. g. C<q:to/END/;> would start a heredoc ending with \"END\".\nSimilarly, you get escaping and interpolation based on your quoting operator,\ni. e. literals with C<Q>, backslash escapes with C<q>, and interpolation with\nC<qq>.\n\n=head2 I/O operators\n\nThe full details on Input/Output in Raku can be found at\nL<io|/language/io>.\n\nAs C«<...>» is the quote-words construct in Raku, C«<>» is not\nused for reading lines from a file. You can do that by either making an\nL<C<IO>|/type/IO> object from a file name or using an open filehandle and then, in\neither case, calling C<.lines> on it. I. e. either C<my @a =\n\"filename\".IO.lines;> or C<my $fh = open \"filename\", :r;my @a =\n$fh.lines;> (In the latter case, we are using C<:r> to specifically open\nthe file for reading). To do this in an iterative manner, you can use a\nC<for> loop this way:\n\n=begin code\nfor 'huge-csv'.IO.lines -> $line {\n    # Do something with $line\n}\n=end code\n\nNote the use of C«->» there. That's part of the Block syntax, and in\nRaku is needed for C<if>, C<for>, C<while>, etc.\n\nIf you want to slurp the entire file into a scalar, you would - surprise! -\nuse the C<.slurp> method. For instance\n\n=begin code\nmy $x = \"filename\".IO.slurp;\n# ... or ...\nmy $fh = open \"filename\", :r;\nmy $x = $fh.slurp;\n=end code\n\nAs noted in the L<Special Variables|/language/perl-var> guide,\nthe C<ARGV> magic input filehandle has\nbeen replaced by C<$*ARGFILES>, and the C<@ARGV> array of command line\narguments has been replaced by C<@*ARGS>.\n\n=head2 No-ops\n\nC<1 while foo();> works in the same way as it does in Perl, however it\ngenerates a warning. In Raku the idiom is now written as\nC<Nil while foo();> instead.\n\n=head2 Bitwise string operators\n\nDocumented individually above, but to summarize...\n\nBitwise integer negation is prefix C<+^>. Bitwise Boolean\nnegation is C<?^>.\n\nBitwise and is C<+&>.\n\nBitwise integer or is C<+|>. Bitwise integer xor is infix C<+^>. Bitwise\nBoolean or is C<?|>.\n\nLeft shift and right shift are C«+<» and C«+>».\n\n=end pod\n"
  },
  {
    "path": "doc/Language/perl-overview.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"migration\")\n\n=TITLE Perl to Raku guide - overview\n\n=SUBTITLE How do I do what I used to do?\n\nThese documents should not be mistaken for a beginner tutorial or a\npromotional overview of Raku (née Perl 6); it is intended as a technical\nreference for Raku learners with a strong Perl background and for anyone\nporting Perl code to Raku.\n\n=head1 Raku in a nutshell\n\nL<Raku in a Nutshell|/language/perl-nutshell> provides a quick overview of\nthings changed in syntax, operators, compound statements, regular expressions,\ncommand-line flags, and various other bits and pieces.\n\n=head1 Syntactic differences\n\nThe L<Syntax section|/language/perl-syn> provides an overview of the\nsyntactic differences between Perl and Raku: how it is still mostly\nfree form, additional ways to write comments, and how C<switch> is very\nmuch a Raku thing.\n\n=head1 Operators in Raku\n\nThe L<Operators section|/language/perl-op> guides you from the operators\nin L<Perl's perlop|https://metacpan.org/pod/distribution/perl/pod/perlop.pod>\nto the equivalent in Raku.\n\n=head1 Functions in Raku\n\nThe L<Functions section|/language/perl-func> describes all of the Perl\nfunctions and their Raku equivalent and any differences in behavior.  It\nalso provides references to ecosystem modules that provide the Perl behavior\nof functions, either existing in Raku with slightly different semantics\n(such as C<shift>), or non-existing in Raku (such as C<tie>).\n\n=head1 Special variables in Raku\n\nThe L<Special Variables section|/language/perl-var> describes if and how\na lot of Perl's special (punctuation) variables are supported in Raku.\n\n=begin comment\n\n### Guidelines for contributions:\n\nHeaders should contain the text that a Perl user might search for, since\nthose headings will be in the Table of Contents generated for the top of\nthe document.\n\nWe use POD =item instead of =head3 or =head4 for unchanged bits that need\nnot appear in the table of contents.\n\nThis article does not describe the additions to syntax, nor details of\npossible improvements. For example, C<0 + $string> still works, even though\nwe would write it as C<+$string> now. (Blue Tiger will offer a Perl\nModernization guide, with step-by-step procedures for translation, along\nwith details of new idioms and \"better ways to do it\")\n\nExample code and links to other documents should be favored over long\nexplanations of details better found elsewhere.\n\nFinally, if a real user asks a P5->P6 question not answered here, please\nadd it to the document, even if we don't have a good answer yet. That will\nbe better than losing the information about a real need.\n\n=end comment\n\n=end pod\n"
  },
  {
    "path": "doc/Language/perl-syn.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"migration\")\n\n=TITLE Perl to Raku guide - syntax\n\n=SUBTITLE Syntactic differences between Perl and Raku\n\nperlsyn - Perl syntax\n\n=head1 DESCRIPTION\n\nA (hopefully) comprehensive description of the differences between\nPerl and Raku with regards to the syntax elements described in the\nperlsyn document.\n\n=head1 NOTE\n\nThis document does I<not> explain Raku syntax in detail. This document is an\nattempt to guide you from how things work in Perl to the equivalents\nin Raku. For full documentation on the Raku syntax, please see the\nL<Raku documentation|/language/syntax>.\n\n=head1 Free form\n\nRaku is still I<largely> free form. However, there are a few instances\nwhere the presence or lack of whitespace is now significant. For\ninstance, in Perl, you can omit a space following a keyword (e. g.\nC<<while($x < 5)>> or C<my($x, $y)>). In Raku, that space is required,\nthus C<<while ($x < 5)>> or C<my ($x, $y)>. In Raku, however, you can\nomit the parentheses altogether: C«while $x < 5». This holds for\nC<if>, C<for>, etc.\n\nOddly, in Perl, you can leave spaces between an array or hash and its\nsubscript, and before a postfix operator. So C<$seen {$_} ++> is valid.\nNo more. That would now have to be C<%seen{$_}++>.\n\nIf it makes you feel better, you can use backslashes to \"unspace\" whitespace,\nso you can use whitespace where it would otherwise be forbidden.\n\nSee L<Whitespace|/language/perl-nutshell#Whitespace> for details.\n\n=head2 Declarations\n\nAs noted in the L<Functions|/language/perl-func> guide, there is no C<undef>\nin Raku. A declared, but\nuninitialized scalar variable will evaluate to its type. In other words, C<my\n$x;say $x;> will give you \"(Any)\". C<my Int $y;say $y;> will give you \"(Int)\".\n\n=head2 Comments\n\nC<#> starts a comment that runs to the end of the line as in Perl.\n\nEmbedded comments start with a hash character and a backtick (C<#`>), followed by an\nopening bracketing character, and continue to the matching closing bracketing\ncharacter. Like so:\n\n=begin code\n\nif #`( why would I ever write an inline comment here? ) True {\n    say \"something stupid\";\n}\n=end code\n\nAs in Perl, you can use pod directives to create multiline comments, with\nC<=begin comment> before and C<=end comment> after the comment.\n\n=head2 Truth and falsehood\n\nThe one difference between Perl truth and Raku truth is that,\nunlike Perl, Raku treats the string C<\"0\"> as true. Numeric C<0>\nis still false, and you can use prefix C<+> to coerce string C<\"0\"> to\nnumeric to get it to be false. Raku, additionally has an actual\nBoolean type, so, in many cases, True and False may be available to\nyou without having to worry about what values count as true and false.\n\n=head2 Statement modifiers\n\nMostly, statement modifiers still work, with a few exceptions.\n\nFirst, C<for> loops are exclusively what were known in Perl as\nC<foreach> loops and C<for> is not used for C-style C<for> loops in Raku. To get that behavior, you want C<loop>. C<loop> cannot be used as a\nstatement modifier.\n\nIn Raku, you cannot use the form C<do {...} while $x>. You will want\nto replace C<do> in that form with C<repeat>. Similarly for C<do {...}\nuntil $x>.\n\n=head2 Compound statements\n\nThe big change from Perl is that C<given> is not experimental or disabled by\ndefault in Raku. For the details on C<given> see\nL<this page|/language/control#given>.\n\n=head2 Loop control\n\nC<next>, C<last>, and C<redo> have not changed from Perl to Raku.\n\nC<continue>, however, does not exist in Raku. You would use a C<NEXT>\nblock in the body of the loop.\n\n=begin code :lang<perl>\n\n# Perl\nmy $str = '';\nfor (1..5) {\n    next if $_ % 2 == 1;\n    $str .= $_;\n}\ncontinue {\n    $str .= ':'\n}\n=end code\n\n=begin code\n# Raku\nmy $str = '';\nfor 1..5 {\n    next if $_ % 2 == 1;\n    $str ~= $_;\n    NEXT {\n        $str ~= ':'\n    }\n}\n=end code\n\n=head2 For loops\n\nAs noted above, C-style C<for> loops are not called C<for> loops in\nRaku. They are just C<loop> loops. To write an infinite loop, you do\nnot need to use the C idiom of C<loop (;;) {...}>, but may just omit\nthe spec completely: C<loop {...}>\n\n=head2 Foreach loops\n\nIn Perl, C<for>, in addition to being used for C-style C<for> loops, is a\nsynonym for C<foreach>. In Raku, C<for> is just used for C<foreach> style\nloops.\n\n=head2 Switch statements\n\nRaku has actual switch statements, provided by C<given> with the individual\ncases handled by C<when> and C<default>. The basic syntax is:\n\n=begin code :lang<pseudo>\ngiven EXPR {\n    when EXPR { ... }\n    when EXPR { ... }\n    default { ... }\n}\n=end code\n\nThe full details can be found\nL<here|/language/control#given>.\n\n=head2 Goto\n\nC<goto> is currently not implemented (yet).  Labels B<are> implemented, and\ncan be used as a target for C<next>, C<last> and C<redo>:\n\n=begin code\nFOO:                         # Labels end with colons, like in Perl\nfor ^10 {\n    say \"outer for before\";\n    for ^10 {\n        say \"inner for\";\n        last FOO;\n    }\n    say \"outer for after\";   # Will not show because of the \"last\"\n}\n# outer for before\n# inner for\n=end code\n\nFor what is planned for C<goto>, see L<https://github.com/Raku/old-design-docs/blob/master/S04-control.pod#The_goto_statement>.\n\n=head2 Ellipsis statement\n\nC<...> (along with C<!!!> and C<???>) are used to create stub\ndeclarations. This is a bit more complicated than the use of C<...> in\nPerl, so you'll probably want to look at\nL<https://github.com/Raku/old-design-docs/blob/master/S06-routines.pod#Stub_declarations> for the gory\ndetails. That said, there doesn't seem to be an I<obvious> reason why it\nshouldn't still fulfill the role it did in Perl, despite its role\nbeing expanded in Raku.\n\n=head2 PODs: embedded documentation\n\nPod has changed between Perl and Raku. Probably the biggest\ndifference is that you need to enclose your pod between C<=begin pod>\nand C<=end pod> directives. There are a few tweaks here and there as\nwell.\n\nFor debugging, your best bet may be to use\nthe Raku interpreter to check your pod. You can do this by using the\nC<--doc> switch. E. g. C<raku --doc Whatever.pod>. This will output any\nproblems to standard error.\n\nDetails on Raku-style pod are L<here|/language/pod>.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/perl-var.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"migration\")\n\n=TITLE Perl to Raku guide - special variables\n\n=SUBTITLE A comparison of special variables in Perl and Raku\n\n=head1 DESCRIPTION\n\nA (hopefully) comprehensive list of Perl Special Variables with their Raku\nequivalents with notes on variations between them where necessary.\n\n=head1 NOTE\n\nThis document is an attempt to guide the reader from the\nI<Special Variables> in Perl to their equivalents in Raku.\nFor full documentation on the Raku I<Special Variables>,\nplease see the Raku documentation for each of them.\n\n\n=head1 SPECIAL VARIABLES\n\nX<|Other languages,Special Variables (Perl)>\n\n=head2 General variables\n\n=head3 X<$ARG, $_|Other languages,$_ (Perl)>\n\nThankfully, C<$_> is the general default variable as in Perl. The\nmain difference in Raku is that you can now call methods on\nit. For instance, Perl's C<say $_> can be rendered in Raku as\nC<$_.say>. Furthermore, as it is the default variable, you don't even\nneed to use the variable name. The previous example can also be\nachieved by using C<.say>.\n\n=head3 X<@ARG, @_|Other languages,@_ (Perl)>\n\nAs Raku now has function signatures, your arguments can go there, rather\nthan depending on C<@_> for them. In fact, if you use a function signature, use\nof C<@_> will spit at you telling it cannot override an existing signature.\n\nIf, however, you do not use a function signature, C<@_> will contain the\narguments you pass to the function as it did in Perl. Again, as with C<$_>,\nyou can call methods on it. Unlike C<$_> you cannot assume C<@_> as the\ndefault variable for those methods to operate on (i. e. C<@_.shift> works,\nC<.shift> does not).\n\n=head3 X<$LIST_SEPARATOR, $\"|Other languages,$\" (Perl)>\n\nCurrently, there is no equivalent of the List Separator variable in Raku.\nDesign document L<S28|https://github.com/Raku/old-design-docs/blob/master/S28-special-names.pod> says there isn't one,\nso you probably don't want to hold your breath.\n\n=head3 X<$PROCESS_ID, $PID, $$|Other languages,$$ (Perl)>\n\nC<$$> is replaced in Raku by C<$*PID>\n\n=head3 X<$PROGRAM_NAME, $0|Other languages,$0 (Perl)>\n\nYou can access the program name in Raku via C<$*PROGRAM-NAME>.\n\nNote: C<$0> in Raku is the variable holding the first captured value from a\nregexp match (i. e. capture variables now start from C<$0> rather than C<$1>).\n\n=head3 $REAL_GROUP_ID, $GID, $(\n\nIn Raku the group information is handled by C<$*GROUP>,\nwhich holds an object of type L<C<IntStr>|/type/IntStr>\nand therefore can be used either within a string\nor a numeric context.\nThe group id is therefore obtained via C<+$*GROUP>, while the\ngroup name via C<~$*GROUP>.\n\n=head3 $EFFECTIVE_GROUP_ID, $EGID, $)\n\nThe effective group id does not appear to be currently provided by Raku.\n\n=head3 $REAL_USER_ID, $UID, $<\n\nIn Raku the user information is handled by C<$*USER>,\nwhich holds an object of type L<C<IntStr>|/type/IntStr>\nand therefore can be used either within a string\nor a numeric context (this is similar to how the group\ninformation is handled by the C<$*GROUP> object).\nThe user id is therefore obtained via C<+$*USER>, while the\nusername via C<~$*USER>.\n\n=head3 $EFFECTIVE_USER_ID, $EUID, $>\n\nThe effective user id is not provided by Raku.\n\n=head3 $SUBSCRIPT_SEPARATOR, $SUBSEP, $;\n\nThe subscript separator variable is not included in Raku. Frankly, if your\nPerl code is using this, it's almost certainly really, really old.\n\n=head3 $a, $b\n\nC<$a> and C<$b> have no special meaning in Raku. C<sort()> does not\nuse them for anything special. They're just regular old variables.\n\nThis feature has been extended by having blocks with placeholder\nparameters which are more versatile. Placeholder variables are created\nwith the C<^> twigil (e. g. C<$^z>. They can be used in a bare block or\nin a subroutine without an explicit parameter list. The arguments to\nthe block are assigned to the placeholder variables in their Unicode\norder. I. e. even if the variables appear in the block in the order\nC<($^q, $^z, $^a)>, they will be I<assigned> in the order C<($^a, $^q,\n$^z)>. Ergo:\n\n=begin code\nsort { $^a cmp $^z }, 1, 5, 6, 4, 2, 3;\n# OUTPUT: «(1 2 3 4 5 6)␤»\nsort { $^g cmp $^a }, 1, 5, 6, 4, 2, 3;\n# OUTPUT: «(6 5 4 3 2 1)␤»\nfor 1..9 { say $^c, $^a, $^b; last }\n# OUTPUT: «312␤»\n=end code\n\nFor more on placeholder variables, see\nL<this page|/language/variables#The_^_twigil>\n\n=head3 %ENV\n\n%ENV has been replaced by %*ENV in Raku. Note that the keys of this hash may\nnot be exactly the same between Perl and Raku. For example,\nC<OLDPWD> is missing from Raku's %ENV.\n\n=head3 $OLD_PERL_VERSION, $]\n\nThe running version of Raku is kept by C<$*RAKU> special variable, that is an object.\nThe running version is retrieved via C<$*RAKU.version>, which returns something\nlike C<v6.d>; the full stringified version of the Raku interpreter is obtained\nvia C<$*RAKU.gist>, which returns something like C<Raku (6.d)>.\n\n=head3 $SYSTEM_FD_MAX, $^F\n\nNo longer exists in Raku.\n\n=head3 @F\n\n[NEEDS FURTHER RESEARCH] A bit confusing at this point. Design doc S28\nindicates that C<@F> in Perl is replaced by C<@_> in Raku, but it's\nunclear just how that works. On the other hand, it's currently something of a\nmoot point, as the Perl to Raku Translation doc indicates that the C<-a>\nand C<-F> command-line switches are not yet implemented in rakudo.\n\n=head3 X<@INC|Other languages,@INC (Perl)>\n\nNo longer exists in Raku.  Please use \"use lib\" to manipulate the\nmodule repositories to be searched.  The closest thing to @INC is\nreally $*REPO.  But that works completely differently from @INC mostly\nbecause of the precompilation capabilities of Raku.\n\n     # Print out a list of compunit repositories\n     .say for $*REPO.repo-chain;\n\n=head3 X<%INC|Other languages,%INC (Perl)>\n\nNo longer exists in Raku.  Because each Repository is responsible for\nremembering which modules have been loaded already. You can get a list\nof all loaded modules (compilation units) like so:\n\n=for code :skip-test<needs dummy module>\nuse Test;\nuse MyModule;\nsay flat $*REPO.repo-chain.map(*.loaded); #-> (MyModule Test)\n\n=head3 $INPLACE_EDIT, $^I\n\nS28 suggests $*INPLACE_EDIT, but it does not yet exist.\n\n=head3 $^M\n\nS28 suggests $*EMERGENCY_MEMORY, but it does not yet exist.\n\n=head3 $OSNAME, $^O\n\nThis is somewhat unclear. It probably depends on what you mean by \"the name of\nthe operating system\" as design document L<S28|https://github.com/Raku/old-design-docs/blob/master/S28-special-names.pod>\nhas three different suggestions, all of which\ngive different answers.\n\nThere are currently three main objects containing information about the \"running\nenvironment\":\n\n=item C<$*KERNEL> provides information about the running Operating System kernel;\n=item C<$*DISTRO> provides information about the Operating System distribution;\n=item C<$*VM> provides information about the running backend machine for Raku.\n\nAll the above objects have methods in common:\n=item C<version> provides the version number for that component;\n=item C<name> provides the mnemonic name for that component;\n=item C<auth> provides the known author(s) for that component.\n\nAs a short example, the following piece of code prints information about\nall the above components:\n\n=begin code\nfor $*KERNEL, $*DISTRO, $*VM -> $what {\n    say $what.^name;\n    say 'release '  ~ $what.version\n        ~ ' named ' ~ $what.name\n        ~ ' by '    ~ $what.auth;\n}\n\n# Kernel\n# release 4.10.0.42.generic named linux by unknown\n# Distro\n# release 17.04.Zesty.Zapus named ubuntu by https://www.ubuntu.com/\n# VM\n# release 2017.11 named moar by The MoarVM Team\n=end code\n\nThe L<C<Str>|/routine/Str> method on all of the above produces the I<short> version of the information,\nat the current time the C<name>.\n\nAll the objects have other methods that can be useful when trying to identify the\nexact running instance, for more information use C<.^methods> to introspect all the above.\n\n=head3 %SIG\n\nNo equivalent variable. To have your code executed on the reception of a\nsignal, you can call the L<signal|/routine/signal#(Supply)_sub_signal>\nsubroutine, which returns a L<C<Supply>|/type/Supply> that can be tapped.\n\n=for code :lang<perl>\n$SIG{\"INT\"} = sub { say \"bye\"; exit }\n=for code\nsignal(SIGINT).tap: { say \"bye\"; exit }; loop {}\n\nOr, if you have a generic code that want to know which signal it got:\n\n=for code\nsignal(SIGINT).tap: -> $signal { say \"bye with $signal\"; exit }; loop {}\n\nA more idiomatic way of using signals in an event driven situation:\n\n=for code\nreact {\n    whenever signal(SIGINT) {\n        say \"goodbye\";\n        done\n    }\n}\n\n=head3 $BASETIME, $^T\n\nReplaced in Raku by C<$*INIT-INSTANT>. Unlike in Perl, this is not in\nseconds since epoch, but an L<C<Instant>|/type/Instant> object, which is measured in atomic\nseconds, with fractions.\n\n=head3 $PERL_VERSION, $^V\n\nAs with C<$]> this has been replaced with C<$*RAKU.version>.\n\n=head3 ${^WIN32_SLOPPY_STAT}\n\nThere is no analog to this in Raku.\n\n=head3 $EXECUTABLE_NAME, $^X\n\nThis has been replaced by C<$*EXECUTABLE-NAME>.\nNote that there is also C<$*EXECUTABLE>, which is an L<C<IO>|/type/IO> object in Raku.\n\n=head2 Variables related to regular expressions\n\n=head3 Performance issues\n\nAs shown below, C<$`>, C<$&>, and C<$'> are gone from Raku, primarily\nreplaced by variations on C<$/> and, with their elimination, the\nassociated performance issues in Perl do not apply.\n\n=head3 $<I<digits>> ($1, $2, ...)\n\nThese existing variables do the same thing in Raku as they do in Perl,\nexcept that they now start at C<$0> rather than C<$1>. Furthermore, they are\nsynonyms for indexed items in the match variable C<$/>. I. e. C<$0> is equivalent\nto C<$/[0]>, C<$1> is equivalent to C<$/[1]>, etc.\n\n=head3 $MATCH, $&\n\nC<$/> now contains the L<C<Match>|/type/Match> object, so the Perl behavior of C<$&> can\nbe obtained by stringifying it, i. e. C<~$/>.\n\nPlease note that while C<$/.Str> should also work,\nC<~$/> is currently the more common idiom.\n\n=head3 ${^MATCH}\n\nSince the former performance issues are done away with, this variable is\nnot of use in Raku.\n\n=head3 $PREMATCH, $`\n\nReplaced by C<$/.prematch>.\n\n=head3 ${^PREMATCH}\n\nSince the former performance issues are done away with, this variable is\nnot of use in Raku.\n\n=head3 $POSTMATCH, $'\n\nReplaced by C<$/.postmatch>.\n\n=head3 ${^POSTMATCH}\n\nSince the former performance issues are done away with, this variable is\nnot of use in Raku.\n\n=head3 $LAST_PAREN_MATCH, $+\n\nDoes not exist in Raku, but you can get the same information using C<$/[*-\n1].Str> (C<$/[*-1]> would be the match object, not the actual string).\n\nIf you want to I<understand> why that works, you can look at these documents:\n\nL<[ ] routine|/routine/[ ]>, L<C<Whatever>|/type/Whatever>,\nand the L<historical design document|https://github.com/Raku/old-design-docs/blob/master/S02-bits.pod#line_1126>\n\n=head3 $LAST_SUBMATCH_RESULT, $^N\n\nS28 suggests C<$*MOST_RECENT_CAPTURED_MATCH>, but there does not seem to be\nany implemented variable that matches C<$^N>.\n\n=head3 @LAST_MATCH_END, @+\n\nAs with most regular expression related variables, this functionality\nis, at least in part, moved to the C<$/> variable in Raku. Or, in this\ncase, the numbered variables that alias to the indexes of it. The offset\nis found by using the C<.to> method. I. e. the first offset is\nC<$/[0].to>, which is synonymous with C<$0.to>. The value Perl\nprovides as C<$+[0]> is provided by C<$/.to>.\n\n=head3 %LAST_PAREN_MATCH, %+\n\nOnce again, we move over to C<$/>. The former C<$+{$match}> is\nC<$/{$match}>.\n\n=head3 @LAST_MATCH_START, @-\n\nSimilarly to C<@+> being replaced by using the C<.to> method, C<@-> is\nreplaced by using the C<.from> method on C<$/> and its variations. The\nfirst offset is C<$/[0].from> or the equivalent C<$0.from>. Perl's C<$-\n[0]> is C<$/.from>.\n\n\n=head3 %LAST_MATCH_START, %-\n\nMuch like C<%+>, a use of C<%-{$match}> would be replaced with C<$/{$match}>.\n\n=head3 $LAST_REGEXP_CODE_RESULT, $^R\n\nNo equivalent.\n\n=head3 ${^RE_DEBUG_FLAGS}\n\nNo equivalent.\n\n=head3 ${^RE_TRIE_MAXBUF}\n\nNo equivalent.\n\n=head2 Variables related to filehandles\n\n=head3 $ARGV\n\nThe name of the current file when reading lines can be obtained through\nC<$*ARGFILES.path>.\n\n=head3 @ARGV\n\nC<@*ARGS> contains the command line arguments.\n\n=head3 ARGV\n\nThis has been replaced by C<$*ARGFILES>.\n\n=head3 ARGVOUT\n\nAs the C<-i> command line switch has not yet been implemented, there is not\nyet an equivalent of C<ARGVOUT>.\n\n=head3 $OUTPUT_FIELD_SEPARATOR, $OFS, $,\n\nCurrently no obvious equivalent.\n\n=head3 $INPUT_LINE_NUMBER\n\n=head3 $NR, $.\n\nNo direct replacement exists.\n\nWhen iterating using L<lines|/routine/lines> method from L<C<IO::Path>|/type/IO::Path> or L<C<IO::Handle>|/type/IO::Handle> types,\nyou can call the C<.kv> method on it to get an interleaved list of indexes and values (then iterate by 2 each loop):\n\n=begin code\nfor \"foo\".IO.lines.kv -> $n, $line {\n    say \"{$n + 1}: $line\"\n}\n# OUTPUT:\n# 1: a\n# 2: b\n# 3: c\n# 4: d\n=end code\n\nFor L<C<IO::CatHandle>|/type/IO::CatHandle> types\n(of which L«C<$*ARGFILES>|/language/variables#index-entry-%24%2AARGFILES» is\none), you can use L«C<on-switch>|/type/IO::CatHandle#method_on-switch» hook\nto reset line number on handle switch, and increment it manually.\nSee also L«C<IO::CatHandle::AutoLines>|https://raku.land/zef:raku-community-modules/IO::CatHandle::AutoLines»\nand L«C<LN>|https://raku.land/zef:raku-community-modules/LN» modules that simplify this\noperation.\n\n=head3 $INPUT_RECORD_SEPARATOR, $RS, $/\n\nThis is accessed through the C<.nl-in> method on the filehandle. E. g.\nC<$*IN.nl-in>.\n\n=head3 $OUTPUT_RECORD_SEPARATOR, $ORS, $\\\n\nThis is accessed through the C<.nl-out> method on the filehandle. E. g.\nC<$*OUT.nl-out>.\n\n=head3 $OUTPUT_AUTOFLUSH, $|\n\nNo global alternative available. TTY handles are unbuffered by default, for\nothers, set L<out-buffer|/routine/out-buffer> to zero or use C<:!out-buffer> with L<open|/routine/open> on a\nspecific L<C<IO::Handle>|/type/IO::Handle>.\n\n=head3 ${^LAST_FH}\n\nNot implemented in Raku.\n\n=head2 Variables related to formats\n\nThere are no built-in formats in Raku.\n\n=head2 Error variables\n\nBecause of how error variables have changed in Raku, they will not be detailed\nhere individually.\n\nTo quote the Raku L<docs|/language/variables#index-entry-%24!>, \"$! is the error variable.\" That's it.\nAll the error variables appear to have been eaten by $!. As with the rest of\nRaku, it's an object that will return various things depending on the type of error\nor L<C<Exception>|/type/Exception>.\n\nIn particular, when dealing with L<C<Exception>|/type/Exception>s the C<$!> provides information\nabout the thrown exception, assuming the program has not halted:\n\n=begin code\ntry {\n    fail \"Boooh\";\n    CATCH {\n        # within the catch block\n        # the exception is placed into $_\n        say 'within the catch:';\n        say $_.^name ~ ' : ' ~ $_.message;\n        $_.resume; # do not abort\n    }\n}\n\n# outside the catch block the exception is placed\n# into $!\nsay 'outside the catch:';\nsay $!.^name ~ ' : ' ~ $!.message;\n=end code\n\nand the above code produces the following output\n\n=for code :lang<shell>\nwithin the catch:\nX::AdHoc : Boooh\noutside the catch:\nX::AdHoc : Boooh\n\ntherefore, as stated before, the C<$!> variable holds the exception object.\n\n=head2 Variables related to the interpreter state\n\n=head3 $COMPILING, $^C, $^D, ${^ENCODING}, ${^GLOBAL_PHASE}\n=head3 $^H, %^H, ${^OPEN}\n=head3 $PERLDB, $^P\n=head3 ${^TAINT}\n=head3 ${^UNICODE}, ${^UTF8CACHE}, ${^UTF8LOCALE}\n\nNot implemented in Raku.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/phasers.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Phasers\n\n=SUBTITLE Program execution phases and corresponding phaser blocks\n\nThe lifetime (execution timeline) of a program is broken up into phases.\nA I<phaser> is a block of code called during a specific execution phase.\n\n=head1 Phasers\n\nA phaser block is just a trait of the closure containing it, and is\nautomatically called at the appropriate moment. These auto-called blocks\nare known as I<phasers>, since they generally mark the transition from\none phase of computing to another. For instance, a C<CHECK> block is\ncalled at the end of compiling a compilation unit. Other kinds of\nphasers can be installed as well; these are automatically called at\nvarious times as appropriate, and some of them respond to various\ncontrol exceptions and exit values. For instance, some phasers might be\ncalled if the exit from a block is successful or not, with I<success> in\nthis case defined by returning with a defined value or list without any\nL<C<Failure>|/type/Failure> or exception in the process.\n\nHere is a summary:\n\n=begin code :skip-test<listing>\n  BEGIN {...} #  * at compile time, as soon as possible, only ever runs once\n  CHECK {...} #  * at compile time, as late as possible, only ever runs once\n   INIT {...} #  * at runtime, as soon as possible, only ever runs once\n    END {...} #  at runtime, as late as possible, only ever runs once\n    DOC [BEGIN|CHECK|INIT] {...} # only in documentation mode\n\n  ENTER {...} #  * at every block entry time, repeats on loop blocks.\n  LEAVE {...} #  at every block exit time (even stack unwinds from exceptions)\n   KEEP {...} #  at every successful block exit, part of LEAVE queue\n   UNDO {...} #  at every unsuccessful block exit, part of LEAVE queue\n\n  FIRST {...} #  at loop initialization time, before any ENTER\n   NEXT {...} #  at loop continuation time, before any LEAVE\n   LAST {...} #  at loop termination time, after any LEAVE\n\n    PRE {...} #  assert precondition at every block entry, before ENTER\n   POST {...} #  assert postcondition at every block exit, after LEAVE\n\n  CATCH {...} #  catch exceptions, before LEAVE\nCONTROL {...} #  catch control exceptions, before LEAVE\n\n   LAST {...} #  supply tapped by whenever-block is done, runs very last\n   QUIT {...} #  catch async exceptions within a whenever-block, runs very last\n\n  CLOSE {...} #  appears in a supply block, called when the supply is closed\n=end code\n\nPhasers marked with a C<*> have a runtime value, and if evaluated\nearlier than their surrounding expression, they simply save their result\nfor use in the expression later when the rest of the expression is\nevaluated:\n\n    my $compiletime = BEGIN { now };\n    our $random = ENTER { rand };\n\nAs with other statement prefixes, these value-producing constructs may\nbe placed in front of either a block or a statement:\n\n    my $compiletime = BEGIN now;\n    our $random = ENTER rand;\n\nMost of these phasers will take either a block or a function reference.\nThe statement form can be particularly useful to expose a lexically\nscoped declaration to the surrounding lexical scope without \"trapping\"\nit inside a block.\n\nThese declare the same variables with the same scope as the preceding\nexample, but run the statements as a whole at the indicated time:\n\n    BEGIN my $compiletime = now;\n    ENTER our $random = rand;\n\n(Note, however, that the value of a variable calculated at compile time may not\npersist under runtime cloning of any surrounding closure.)\n\nMost of the non-value-producing phasers may also be so used:\n\n    END say my $accumulator;\n\nNote, however, that\n\n    END say my $accumulator = 0;\n\nsets the variable to 0 at C<END> time, since that is when the \"my\" declaration\nis actually executed. Only argumentless phasers may use the statement form.\nThis means that C<CATCH> and C<CONTROL> always require a block, since they take\nan argument that sets C<$_> to the current topic, so that the innards are able\nto behave as a switch statement. (If bare statements were allowed, the\ntemporary binding of C<$_> would leak out past the end of the C<CATCH> or\nC<CONTROL>, with unpredictable and quite possibly dire consequences. Exception\nhandlers are supposed to reduce uncertainty, not increase it.)\n\nX<|Phasers,will trait>\nSome of these phasers also have corresponding traits that can be set on\nvariables; they use C<will> followed by the name of the phaser in lowercase.\nThese have the advantage of passing the variable in question into the closure as\nits topic:\n\n    our $h will enter { .rememberit() } will undo { .forgetit() };\n\nOnly phasers that can occur multiple times within a block are eligible for this\nper-variable form; this excludes C<CATCH> and others like C<CLOSE> or C<QUIT>.\n\nThe topic of the block outside a phaser is still available as C«OUTER::<$_>».\nWhether the return value is modifiable may be a policy of the phaser in\nquestion. In particular, the return value should not be modified within a\nC<POST> phaser, but a C<LEAVE> phaser could be more liberal.\n\nAny phaser defined in the lexical scope of a method is a closure that closes\nover C<self> as well as normal lexicals. (Or equivalently, an implementation\nmay simply turn all such phasers into submethods whose primed invocant is the\ncurrent object.)\n\nWhen multiple phasers are scheduled to run at the same moment, the general\ntiebreaking principle is that initializing phasers execute in order declared,\nwhile finalizing phasers execute in the opposite order, because setup and\nteardown usually want to happen in the opposite order from each other.\n\n=head2 Execution order\n\nCompilation begins\n\n=for code :skip-test<listing>\n      BEGIN {...} #  at compile time, As soon as possible, only ever runs once\n      CHECK {...} #  at compile time, As late as possible, only ever runs once\n\nExecution begins\n\n=for code :skip-test<listing>\n       INIT {...} #  at runtime, as soon as possible, only ever runs once\n\nBefore block execution begins\n\n=for code :skip-test<listing>\n        PRE {...} #  assert precondition at every block entry, before ENTER\n\nLoop execution begins\n\n=for code :skip-test<listing>\n      FIRST {...} #  at loop initialization time, before any ENTER\n\nBlock execution begins\n\n=for code :skip-test<listing>\n      ENTER {...} #  at every block entry time, repeats on loop blocks.\n\nException maybe happens\n\n=for code :skip-test<listing>\n      CATCH {...} #  catch exceptions, before LEAVE\n    CONTROL {...} #  catch control exceptions, before LEAVE\n\nEnd of loop, either continuing or finished\n\n=for code :skip-test<listing>\n       NEXT {...} #  at loop continuation time, before any LEAVE\n       LAST {...} #  at loop termination time, after any LEAVE\n\nEnd of block\n\n=for code :skip-test<listing>\n      LEAVE {...} #  when blocks exits, even stack unwinds from exceptions\n       KEEP {...} #  at every successful block exit, part of LEAVE queue\n       UNDO {...} #  at every unsuccessful block exit, part of LEAVE queue\n\nPostcondition for block\n\n=for code :skip-test<listing>\n       POST {...} #  assert postcondition at every block exit, after LEAVE\n\nAsync whenever-block is complete\n\n=for code :skip-test<listing>\n       LAST {...} #  if ended normally with done, runs once after block\n       QUIT {...} #  catch async exceptions\n\nProgram terminating\n\n=for code :skip-test<listing>\n        END {...} #  at runtime, ALAP, only ever runs once\n\n=head1 Program execution phasers\n\n=head2 X<BEGIN|Phasers,BEGIN>\n\nRuns at compile time, as soon as the code in the phaser has compiled,\nonly runs once.\n\nThe return value is available for use in later phases:\n\n    say \"About to print 3 things\";\n    for ^3 {\n        say ^10 .pick ~ '-' ~ BEGIN { say  \"Generating BEGIN value\"; ^10 .pick }\n    }\n    # OUTPUT:\n    # Generating BEGIN value\n    # About to print 3 things\n    # 3-3\n    # 4-3\n    # 6-3\n\nThe C<^10 .pick> in the phaser is generated only once and is then re-used by the loop\nduring runtime. Note how the L<say|/routine/say> in the C<BEGIN> block is executed before\nthe L<say|/routine/say> that is above the loop.\n\n=head2 X<CHECK|Phasers,CHECK>\n\nRuns at compile time, as late as possible, only runs once.\n\nCan have a return value that is provided even in later phases.\n\nCode that is generated at runtime can still fire off C<CHECK> and C<INIT>\nphasers, though of course those phasers can't do things that would require\ntravel back in time. You need a wormhole for that.\n\n=head2 X<INIT|Phasers,INIT>\n\nRuns after compilation during main execution, as soon as possible, only\nruns once. It can have a return value that is provided even in later\nphases.\n\nWhen phasers are in different modules, the C<INIT> and C<END> phasers are\ntreated as if declared at C<use> time in the using module. (It is erroneous to\ndepend on this order if the module is used more than once, however, since the\nphasers are only installed the first time they're noticed.)\n\nCode that is generated at runtime can still fire off C<CHECK> and C<INIT>\nphasers, though of course those phasers can't do things that would require\ntravel back in time. You need a wormhole for that.\n\nAn C<INIT> only runs once for all copies of a cloned closure.\n\n=head2 X<END|Phasers,END>\n\nRuns after compilation during main execution, as late as possible, only runs\nonce. It will close any open handles automatically.\n\nWhen phasers are in different modules, the C<INIT> and C<END> phasers are\ntreated as if declared at C<use> time in the using module. (It is erroneous to\ndepend on this order if the module is used more than once, however, since the\nphasers are only installed the first time they're noticed.)\n\n=head1 Block phasers\n\nExecution in the context of a block has its own phases.\n\nBlock-leaving phasers wait until the call stack is actually unwound to run.\nUnwinding happens only after some exception handler decides to handle the\nexception that way. That is, just because an exception is thrown past a stack\nframe does not mean we have officially left the block yet, since the exception\nmight be resumable. In any case, exception handlers are specified to run within\nthe dynamic scope of the failing code, whether or not the exception is\nresumable. The stack is unwound and the phasers are called only if an exception\nis not resumed.\n\nThese can occur multiple times within the block. So they aren't really traits,\nexactly--they add themselves onto a list stored in the actual trait. If you\nexamine the C<ENTER> trait of a block, you'll find that it's really a list of\nphasers rather than a single phaser.\n\nAll of these phaser blocks can see any previously declared lexical variables,\neven if those variables have not been elaborated yet when the closure is\ninvoked (in which case the variables evaluate to an undefined value.)\n\n=head2 X<ENTER|Phasers,ENTER>\n\nRuns at every block entry time, repeats on loop blocks.\n\nCan have a return value that is provided even in later phases.\n\nAn exception thrown from an C<ENTER> phaser will abort the C<ENTER> queue, but\none thrown from a C<LEAVE> phaser will not.\n\n=head2 X<LEAVE|Phasers,LEAVE>\n\nRuns at every block exit time (even stack unwinds from exceptions),\nexcept when the program exits abruptly (e.g. with\nL«C<exit>|/routine/exit»).\n\nC<LEAVE> phasers for a given block are necessarily evaluated after any\nC<CATCH> and C<CONTROL> phasers. This includes the C<LEAVE> variants, C<KEEP>\nand C<UNDO>. C<POST> phasers are evaluated after everything else, to guarantee\nthat even C<LEAVE> phasers can't violate postconditions.\n\nAn exception thrown from an C<ENTER> phaser will abort the C<ENTER> queue, but\none thrown from a C<LEAVE> phaser will not.\n\nIf a C<POST> fails or any kind of C<LEAVE> block throws an exception while the\nstack is unwinding, the unwinding continues and collects exceptions to be\nhandled. When the unwinding is completed all new exceptions are thrown from\nthat point.\n\n    sub answer() {\n        LEAVE say „I say after the return value.“;\n\n        42 # this is the return value\n    }\n\nB<Note:> be mindful of C<LEAVE> phasers directly in blocks of routines, as\nthey will get executed even when an attempt to call the routine with wrong\narguments is made:\n\n    sub foo (Int) {\n        say \"Hello!\";\n        LEAVE say \"oh noes!\"\n    }\n    try foo rand; # OUTPUT: «oh noes!␤»\n\nAlthough the subroutine's body did not get run, because the sub expects\nan L<C<Int>|/type/Int> and L«C<rand>|/routine/rand» returned a L<C<Num>|/type/Num>, its block was\nentered and left (when param binding failed), and so the C<LEAVE> phaser\nI<was> run.\n\n=head2 X<KEEP|Phasers,KEEP>\n\nRuns at every successful block exit, as part of the C<LEAVE> queue (shares the\nsame order of execution).\n\n=head2 X<UNDO|Phasers,UNDO>\n\nRuns at every unsuccessful block exit, as part of the C<LEAVE> queue (shares the\nsame order of execution).\n\n=head2 X<PRE|Phasers,PRE>\n\nAsserts a precondition at every block entry. Runs before the C<ENTER> phase.\n\nC<PRE> phasers fire off before any C<ENTER> or C<FIRST>.\n\nThe exceptions thrown by failing C<PRE> and C<POST> phasers cannot be caught by\na C<CATCH> in the same block, which implies that C<POST> phaser are not run if\na C<PRE> phaser fails.\n\n=head2 X<POST|Phasers,POST>\n\nAsserts a postcondition at every block entry. Runs after the C<LEAVE> phase.\n\nFor phasers such as C<KEEP> and C<POST> that are run when exiting a scope\nnormally, the return value (if any) from that scope is available as the current\ntopic within the phaser.\n\nThe C<POST> block can be defined in one of two ways. Either the corresponding\nC<POST> is defined as a separate phaser, in which case C<PRE> and C<POST> share\nno lexical scope. Alternately, any C<PRE> phaser may define its corresponding\nC<POST> as an embedded phaser block that closes over the lexical scope of the\nC<PRE>.\n\nIf a C<POST> fails or any kind of C<LEAVE> block throws an exception while the\nstack is unwinding, the unwinding continues and collects exceptions to be\nhandled. When the unwinding is completed all new exceptions are thrown from\nthat point.\n\nThe exceptions thrown by failing C<PRE> and C<POST> phasers cannot be caught by\na C<CATCH> in the same block, which implies that C<POST> phaser are not run if\na C<PRE> phaser fails.\n\n=head1 Loop phasers\n\nC<FIRST>, C<NEXT>, and C<LAST> are meaningful only within the lexical scope of\na loop, and may occur only at the top level of such a loop block.\n\n=head2 X<FIRST|Phasers,FIRST>\n\nRuns at loop initialization, before C<ENTER>.\n\n=head2 X<NEXT|Phasers,NEXT>\n\nRuns when loop is continued (either through C<next> or because you got to the\nbottom of the loop and are looping back around), before C<LEAVE>.\n\nA C<NEXT> executes only if the end of the loop block is reached normally, or an\nexplicit C<next> is executed. In distinction to C<LEAVE> phasers, a C<NEXT>\nphaser is not executed if the loop block is exited via any exception other than\nthe control exception thrown by C<next>. In particular, a C<last> bypasses\nevaluation of C<NEXT> phasers.\n\n=head2 X<LAST|Phasers,LAST>\n\nRuns when a loop is finished because the condition is met, or when it exits\nusing C<last>; it is executed after C<LEAVE>.\n\n=head1 Exception handling phasers\n\n=head2 X<CATCH|Phasers,CATCH>\n\nRuns when an exception is raised by the current block, before the C<LEAVE> phase.\nAlso see L<Catching exceptions|/language/exceptions#Catching_exceptions>.\n\n=head2 X<CONTROL|Phasers,CONTROL>\n\nRuns when a control exception is raised by the current block, before the C<LEAVE>\nphase. It is raised by C<return>, C<fail>, C<redo>, C<next>, C<last>, C<done>, C<emit>,\nC<take>, C<warn>, C<proceed> and C<succeed>.\n\n    say elems gather {\n        CONTROL {\n            when CX::Warn { say \"WARNING!!! $_\"; .resume }\n            when CX::Take { say \"Don't take my stuff\"; .resume }\n            when CX::Done { say \"Done\"; .resume }\n        }\n        warn 'people take stuff here';\n        take 'keys';\n        done;\n    }\n    # OUTPUT:\n    # WARNING!!! people take stuff here\n    # Don't take my stuff\n    # Done\n    # 0\n\n\n=head1 Asynchronous phasers\n\n=head2 X<LAST|Asynchronous phasers,LAST>\n\nRuns when a L<C<Supply>|/type/Supply> finishes with a call to C<done> or when a\nC<supply> block exits normally. It runs completely after the C<whenever> block\nit is placed within finishes.\n\nThis phaser reuses the name C<LAST>, but works differently from the C<LAST> loop\nphaser. This phaser is similar to setting the C<done> routine while tapping a\nsupply with C<tap>.\n\n=head2 X<QUIT|Asynchronous phasers,QUIT>\n\nRuns when a L<C<Supply>|/type/Supply> terminates early with an exception. It runs\nafter the C<whenever> block it is placed within finishes.\n\nThis phaser is similar to setting the C<quit> routine while tapping a Supply\nwith C<tap>.\n\n=head2 X<CLOSE|Asynchronous phasers,CLOSE>\n\nAppears in a supply or a react block. Called when the supply is closed / react has exhausted all of its C<whenever>s.\n\n=head1 DOC phasers\n\n=head2 X<DOC|Asynchronous phasers,DOC>\n\nThe phasers C<BEGIN>, C<CHECK> and C<INIT> are run only in documentation mode\nwhen prefixed with the C<DOC> keyword. The compiler is in documentation mode when run\nwith C<--doc>.\n\n  DOC INIT { say 'init'  }  # prints 'init' at initialization time when in documentation mode.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/pod.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"reference\")\n\n=TITLE Rakudoc (aka Pod6)\n\n=SUBTITLE A markup language for documenting Raku code.\nPod6 is now known as RakuDoc V1,\nand a new L<RakuDoc V2 specification|https://raku.github.io/rakudoc> exists.\n\nRakudoc is an easy-to-use markup language. It can be used for\nwriting language documentation, for documenting programs and modules, as\nwell as for other types of document composition.\n\nEvery Rakudoc document has to begin with C<=begin pod> and end with C<=end pod>.\nEverything between these two delimiters will be processed and used to generate\ndocumentation.\n\n=begin code :lang<rakudoc>\n=begin pod\n\nA very simple Rakudoc document\n\n=end pod\n=end code\n\n=head1 Block structure\n\nA Rakudoc document may consist of multiple Rakudoc blocks. There are four ways to\ndefine a block: delimited, paragraph, abbreviated, and declarator; the first three\nyield the same result but the fourth differs. You can use whichever form is most\nconvenient for your particular documentation task.\n\n=head2 Delimited blocks\n\nDelimited blocks are bounded by C<=begin> and C<=end> markers, both of\nwhich are followed by a valid Raku identifier, which is the\nC<typename> of the block. Typenames that are entirely lowercase (for\nexample: C<=begin head1>) or entirely uppercase (for example: C<=begin\nSYNOPSIS>) are reserved. Indentation of the =begin/=end lines is\nrequired to be the same to create a valid block; otherwise, an error\nor unexpected results will occur.\n\n=begin code :lang<rakudoc>\n=begin head1\nTop Level Heading\n=end head1\n=end code\n\n=head3 Configuration information\n\nAfter the typename, the rest of the C<=begin> marker line is treated as\nconfiguration information for the block. This information is used in\ndifferent ways by different types of blocks, but is always specified using\nRaku-ish option pairs. That is, any of:\n\n=begin table\n Value is...       Specify with...           Or with...           Or with...\n ===============   ===================       ==============       ===========\n List              :key[$e1, $e2, ...]       :key($e1, $e2, ...)  :key<$e1 $e2 ...>\n Hash              :key{$k1=>$v1, $k2=>$v2}\n Boolean (true)    :key                      :key(True)           :key[True]\n Boolean (false)   :!key                     :key(False)          :key[False]\n String            :key<str>                 :key('str')          :key(\"str\")\n Int               :key(42)                  :key[42]             :42key\n Number            :key(2.3)                 :key[2.3]\n=end table\n\nWhere '$e1, $e2, ...' are list elements of type String, Int, Number, or\nBoolean. Lists may have mixed element types. Note that one-element\nlists are converted to the type of their element (String, Int, Number, or\nBoolean). Also note that big integers can be used if required.\n\nFor hashes, '$k1, $k2, ...' are keys of type Str and '$v1, $v2, ...'\nare values of type String, Int, Number, or Boolean.\n\nStrings are delimited by single or double quotes. Whitespace is not significant\noutside of strings. Hash keys need not be quote-delimited unless they contain\nsignificant whitespace. Strings entered inside angle brackets become lists if\nany whitespace is used inside the angle brackets.\n\nAll option keys and values must be constants since Rakudoc is a\nspecification language, not a programming language. Specifically, option\nvalues cannot be closures. See L<Synopsis 2|https://github.com/Raku/old-design-docs/blob/master/S02-bits.pod>\nfor details of the various\nRaku pair notations.\n\nThe configuration section may be extended over subsequent\nlines.\nEach subsequent line must start\nwith an C<=> in the first virtual column, meaning that it must vertically\nalign with the C<=> of the Rakudoc Block declaration,\nand it must be followed\nby at least one horizontal whitespace character.\n\nFor example:\n=begin code :lang<rakudoc>\n     =for head1 :a-first-line-key<firstvalue> :another-first-line-key<xyz>\n     =          :a-second-line-key(42)\n     = :a-third-line-key<third>\n     Content for the header block\n=end code\n\nSome of these options have a predetermined value; specifically, C<:numbered>\nis used to specify that the block item or lines will be numbered.\n\n=begin code :lang<rakudoc>\n=for defn :numbered\n               We\n               Need\n               Numbers\n\nsay $=pod[0].config<numbered>; # OUTPUT: «True␤»\n=end code\n\nThis configuration option can be abbreviated by a hash mark\n\n=begin code :lang<rakudoc>\n=para #\nWe\nNeed\nNumbers\n\nsay $=pod[0].config<numbered>; # OUTPUT: «1␤»\n=end code\n\n=head2 Paragraph blocks\n\nParagraph blocks begin by a C<=for> marker and end by\nthe next Pod6 directive or the first blank line.\nThe C<=for> marker is followed by the C<typename> of the block\nplus, optionally, any configuration data as in the delimited\nblocks described above.\n\n=begin code :lang<rakudoc>\n=for head1\nTop Level Heading\n=end code\n\n=head2 Abbreviated blocks\n\nAbbreviated blocks begin with an C<=> sign, which is followed immediately by the\nC<typename> of the block. All following data are part of the contents of the\nblock, thus configuration data B<cannot> be specified for an I<abbreviated>\nblock. The block ends at the next Rakudoc directive or the first blank line.\n\n=begin code :lang<rakudoc>\n=head1 Top level heading\n=end code\n\nX<|Syntax,#|>X<|Syntax,#=>\n=head2 Declarator blocks\n\nDeclarator blocks differ from the others by not having a specific type,\ninstead they are attached to some source code.\n\nDeclarator blocks are introduced by a special comment: either C<#|> or C<#=>,\nwhich must be immediately followed by either a space or an opening curly brace.\nIf followed by a space, the block is terminated by the end of line;\nif followed by one or more opening curly braces, the block is terminated by\nthe matching sequence of closing curly braces.\n\nBlocks starting with C<#|> are attached to the code after them,\nand blocks starting with C<#=> are attached to the code before them.\n\nSince declarator blocks are attached to source code, they can be used to\ndocument classes, roles, subroutines and in general any statement or block.\n\nThe C<WHY> method can be used on these classes, roles, subroutines etc. to\nreturn the attached Pod6 value.\n\n=begin code\n#| Base class for magicians\nclass Magician {\n  has Int $.level;\n  has Str @.spells;\n}\n\n#| Fight mechanics\nsub duel(Magician $a, Magician $b) {\n}\n#= Magicians only, no mortals.\n\nsay Magician.WHY; # OUTPUT: «Base class for magicians␤»\nsay &duel.WHY.leading; # OUTPUT: «Fight mechanics␤»\nsay &duel.WHY.trailing; # OUTPUT: «Magicians only, no mortals.␤»\n=end code\n\nThese declarations can extend multiple blocks:\n\n=begin code\n#|( This is an example of stringification:\n    * Numbers turn into strings\n    * Regexes operate on said strings\n    * C<with> topicalizes and places result into $_\n)\nsub search-in-seq( Int $end, Int $number ) {\n    with (^$end).grep( /^$number/ ) {\n        .say for $_<>;\n    }\n}\n#=« Uses\n    * topic\n    * decont operator\n»\n=end code\n\nBy using a matched pair of parenthesis constructs such as C<()> or C<«»> the\ncomments can extend multiple lines. This format will not normally translate to\na multi-line display by C<raku --doc>. However, since Rakudo release 2020.01,\nthere is a method to accomplish that, I<for leading declarator blocks only>,\nby defining a special environment variable: B<C<RAKUDO_POD_DECL_BLOCK_USER_FORMAT>>.\nWhen that value is set, running C<raku> with the C<--doc> option should show text\nfrom leading declarator blocks in its original format. See the test for the capability\nin the file\nL<S26-documentation/block-leading-user-format.t|https://github.com/Raku/roast/blob/master/S26-documentation/block-leading-user-format.t>.\n\n\n\n=head1 Block types\n\nRakudoc offers a wide range of standard block types.\n\n=head2 Headings\n\nHeadings can be defined using C<=headN>,\nwhere N is greater than zero (e.g., C<=head1>, C<=head2>, …).\n\n=begin code :lang<rakudoc>\n=head1 A top level heading\n\n=head2 A second level heading\n\n=head3 A third level heading\n=end code\n\n=head2 Ordinary paragraphs\n\nAn ordinary paragraph consists of text that is to be formatted into a document\nat the current level of nesting, with whitespace squeezed, lines filled, and any\nspecial inline mark-up applied.\n\nOrdinary paragraphs consist of one or more consecutive lines of text,\neach of which starts with a non-whitespace character.\nThe paragraph is terminated by the first blank line or block directive.\n\nFor example:\n\n=begin code :lang<rakudoc>\n=head1 This is a heading block\n\nThis is an ordinary paragraph.\nIts text  will   be     squeezed     and\nshort lines filled. It is terminated by\nthe first blank line.\n\nThis is another ordinary paragraph.\nIts     text    will  also be squeezed and\nshort lines filled. It is terminated by\nthe trailing directive on the next line.\n\n=head2 This is another heading block\n\nThis is yet another ordinary paragraph,\nat the first virtual column set by the\nprevious directive\n=end code\n\nOrdinary paragraphs do not require an explicit marker or delimiters.\n\nAlternatively, there is also an explicit C<=para> marker that can be used\nto explicitly mark a paragraph.\n\n=begin code :lang<rakudoc>\n=para\nThis is an ordinary paragraph.\nIts text  will   be     squeezed     and\nshort lines filled.\n=end code\n\nIn addition, the longer C<=begin para> and C<=end para> form can be used.\n\nFor example:\n\n=begin code :lang<rakudoc>\n\n=begin para\nThis is an ordinary paragraph.\nIts text  will   be     squeezed     and\nshort lines filled.\n\nThis is still part of the same paragraph,\nwhich continues until an...\n=end para\n=end code\n\nAs demonstrated by the previous example, within a delimited C<=begin para> and\nC<=end para> block, any blank lines are preserved.\n\n=head2 Code blocks\n\nCode blocks are used to specify source code, which should be rendered without\nre-justification, without whitespace-squeezing, and without recognizing any\ninline formatting codes. Typically these blocks are used to show examples of\ncode, mark-up, or other textual specifications, and are rendered using a\nfixed-width font.\n\nA code block may be implicitly specified as one or more lines of text,\neach of which starts with a whitespace character. The implicit code block\nis then terminated by a blank line.\n\nFor example:\n\n=begin code :lang<rakudoc>\nThis ordinary paragraph introduces a code block:\n\n    my $name = 'John Doe';\n    say $name;\n=end code\n\nCode blocks can also be explicitly defined by enclosing them in C<=begin code>\nand C<=end code>\n\n=begin code :lang<rakudoc>\n    =begin code\n    my $name = 'John Doe';\n    say $name;\n    =end code\n=end code\n\n=head2 I/O blocks\n\nRakudoc provides blocks for specifying the input and output of programs.\n\nThe C<=input> block is used to specify pre-formatted keyboard input,\nwhich should be rendered without re-justification or squeezing of whitespace.\n\nThe C<=output> block is used to specify pre-formatted terminal or file output,\nwhich should also be rendered without re-justification or whitespace-squeezing.\n\n=head2 Lists\n\n=head3 Unordered lists\n\nLists in Rakudoc are specified as a series of C<=item> blocks.\n\nFor example:\n\n=begin code :lang<rakudoc>\nThe three suspects are:\n\n=item  Happy\n=item  Sleepy\n=item  Grumpy\n=end code\n\nThe three suspects are:\n\n=item  Happy\n=item  Sleepy\n=item  Grumpy\n\n=head3 Definition lists\n\nLists that define terms or commands use C<=defn>, equivalent to the C<DL> lists\nin HTML\n\n=begin code :lang<rakudoc>\n=defn Happy\nWhen you're not blue.\n\n=defn Blue\nWhen you're not happy.\n=end code\n\nwill be rendered as\n\n=defn Happy\nWhen you're not blue.\n\n=defn Blue\nWhen you're not happy.\n\n=head3 Multi-level lists\n\nLists may be multi-level, with items at each level specified using the\nC<=item1>, C<=item2>, C<=item3>, etc. blocks.\n\nNote that C<=item> is just an abbreviation for C<=item1>.\n\nFor example:\n\n=begin code :lang<rakudoc>\n=item1  Animal\n=item2     Vertebrate\n=item2     Invertebrate\n\n=item1  Phase\n=item2     Solid\n=item2     Liquid\n=item2     Gas\n=end code\n\n=item1  Animal\n=item2     Vertebrate\n=item2     Invertebrate\n\n=item1  Phase\n=item2     Solid\n=item2     Liquid\n=item2     Gas\n\n=head3 Multi-paragraph lists\n\nUsing the delimited form of the C<=item> block (C<=begin item> and C<=end item>),\nwe can specify items that contain multiple paragraphs.\n\nFor example:\n\n=begin code :lang<rakudoc>\nLet's consider two common proverbs:\n\n=begin item\nI<The rain in Spain falls mainly on the plain.>\n\nThis is a common myth and an unconscionable slur on the Spanish\npeople, the majority of whom are extremely attractive.\n=end item\n\n=begin item\nI<The early bird gets the worm.>\n\nIn deciding whether to become an early riser, it is worth\nconsidering whether you would actually enjoy annelids\nfor breakfast.\n=end item\n\nAs you can see, folk wisdom is often of dubious value.\n=end code\nRenders as:\n\nLet's consider two common proverbs:\n\n=begin item\nI<The rain in Spain falls mainly on the plain.>\n\nThis is a common myth and an unconscionable slur on the Spanish\npeople, the majority of whom are extremely attractive.\n=end item\n\n=begin item\nI<The early bird gets the worm.>\n\nIn deciding whether to become an early riser, it is worth\nconsidering whether you would actually enjoy annelids\nfor breakfast.\n=end item\n\nAs you can see, folk wisdom is often of dubious value.\n\n=head2 Tables\n\nCheck out this page for documentation related to L<Tables|/language/tables>\nZ<Eventually copy everything from tables.rakudoc and put it here>\n\n=head2 Rakudoc comments\n\nRakudoc comments are comments that Rakudoc renderers ignore.\n\nComments are useful for I<meta>documentation (documenting the documentation).\nSingle-line comments use the C<=comment> marker:\n\n=begin code :lang<rakudoc>\n=comment Add more here about the algorithm\n=end code\n\nFor multi-line comments, use a delimited C<comment> block:\n\n=begin code :lang<rakudoc>\n=begin comment\nThis comment is\nmulti-line.\n=end comment\n=end code\n\nYou can also use implicit block:\n\n=begin code :lang<rakudoc>\n=comment\nThis comment is\nmulti-line.\n\nB<this> is visible\n=end code\n\n\n=head2 Semantic blocks\n\nAll uppercase block typenames are reserved for specifying standard\ndocumentation, publishing, source components, or meta-information.\n\n=begin code :lang<rakudoc>\n=NAME\n=AUTHOR\n=VERSION\n=TITLE\n=SUBTITLE\n=end code\n\n=head1 Formatting codes\n\nFormatting codes provide a way to add inline mark-up to a piece of text.\n\nAll Rakudoc formatting codes consist of a single capital letter followed immediately\nby a set of single or double angle brackets; Unicode double angle brackets may\nbe used.\n\nFormatting codes may nest other formatting codes.\n\nThe following codes are available: B<B>, B<C>, B<E>, B<I>, B<K>, B<L>, B<N>,\nB<P>, B<R>, B<T>, B<U>, B<V>, B<X>, and B<Z>.\n\n=head2 Bold\n\nTo format a text in bold enclose it in C<B< >>\n=for code :lang<rakudoc>\nRaku is B<awesome>\n\nRaku is B<awesome>\n\n=head2 Italic\n\nTo format a text in italic enclose it in C<I< >>\n=for code :lang<rakudoc>\nRaku is I<awesome>\n\nRaku is I<awesome>\n\n=head2 Underlined\n\nTo underline a text enclose it in C<U< >>\n=for code :lang<rakudoc>\nRaku is U<awesome>\n\nZ<If used will bust Pod::To::BigPage>\n\n=head2 Code\n\nTo flag text as code and treat it verbatim enclose it in C<C< >>\n=for code :lang<rakudoc>\nC<my $var = 1; say $var;>\n\nC<my $var = 1; say $var;>\n\nIf the enclosed code itself contains an unmatched C«>»,\nenclose it in C<C« »>\n=for code :lang<rakudoc>\nC«sub f(Int --> Int) {}»\n\nC«sub f(Int --> Int) {}»\n\n=head2 Links\n\nTo create a link enclose it in C<L< >>\n\n=for code :lang<rakudoc>\nRaku homepage L<https://raku.org>\n\nRaku homepage L<https://raku.org>\n\nAn optional vertical bar can be used to separate the label from the target.\n\n=for code :lang<rakudoc>\nL<Raku homepage|https://raku.org>\n\nL<Raku homepage|https://raku.org>\n\nRelative URLs are relative to the base of the project, so in this repository,\nfor example, we can link to another page in the C<language> folder. Here we\nuse an optional fragment to link to a heading:\n\n=for code :lang<rakudoc>\nL<Structure|/language/about#Structure>\n\nL<Structure|/language/about#Structure>\n\nOne can also specify a link to a fragment in the current document:\n\n=for code :lang<rakudoc>\nL<Comments|#Comments>\n\nL<Comments|#Comments>\n\nFinally, in addition to URL-style links (e.g. C«L<Some reference|path/to/filename>»),\nmodule-style notation (C«L<Some reference|path::to::filename>») also works.\n\n=head2 Placement links\n\nThis code is not implemented in C<Pod::To::HTML>, but is partially implemented\nin C<Pod::To::BigPage>.\n\nA second kind of link E<mdash> the C<P<>> or B<placement link> E<mdash> works\nin the opposite direction. Instead of directing focus out to another\ndocument, it allows you to assimilate the contents of another document\ninto your own.\n\nIn other words, the C<P<>> formatting code takes a URI and (where possible)\ninserts the contents of the corresponding document inline in place of the\ncode itself.\n\nC<P<>> codes are handy for breaking out standard elements of\nyour documentation set into reusable components that can then be\nincorporated directly into multiple documents. For example:\n\n=begin code :lang<rakudoc>\n=COPYRIGHT\nP<file:/shared/docs/std_copyright.pod>\n\n=DISCLAIMER\nP<http://www.MegaGigaTeraPetaCorp.com/std/disclaimer.txt>\n=end code\n\nmight produce:\n\n=begin nested\nB<Copyright>\n\nThis document is copyright (c) MegaGigaTeraPetaCorp, 2006. All rights reserved.\n\nB<Disclaimer>\n\nABSOLUTELY NO WARRANTY IS IMPLIED. NOT EVEN OF ANY KIND. WE HAVE SOLD\nYOU THIS SOFTWARE WITH NO HINT OF A SUGGESTION THAT IT IS EITHER USEFUL\nOR USABLE. AS FOR GUARANTEES OF CORRECTNESS...DON'T MAKE US LAUGH! AT\nSOME TIME IN THE FUTURE WE MIGHT DEIGN TO SELL YOU UPGRADES THAT PURPORT\nTO ADDRESS SOME OF THE APPLICATION'S MANY DEFICIENCIES, BUT NO PROMISES\nTHERE EITHER. WE HAVE MORE LAWYERS ON STAFF THAN YOU HAVE TOTAL\nEMPLOYEES, SO DON'T EVEN *THINK* ABOUT SUING US. HAVE A NICE DAY.\n=end nested\n\nIf a renderer cannot find or access the external data source for a\nplacement link, it must issue a warning and render the URI directly in\nsome form, possibly as an outwards link. For example:\n\n=begin nested\nB<Copyright>\n\nSee: C<file:/shared/docs/std_copyright.pod>\n\nB<Disclaimer>\n\nSee: L<http://www.MegaGigaTeraPetaCorp.com/std/disclaimer.txt>\n=end nested\n\nYou can use any of the following URI forms (see L<Links|#Links>) in a\nplacement link.\n\n=head2 Comments\n\nA comment is text that is never rendered.\n\nTo create a comment enclose it in C<Z< >>\n=for code :lang<rakudoc>\nRaku is awesome Z<Of course it is!>\n\nRaku is awesome Z<Of course it is!>\n\n=head2 Notes\n\nNotes are rendered as footnotes.\n\nTo create a note enclose it in C<N< >>\n=for code :lang<rakudoc>\nRaku is multi-paradigmatic N<Supporting Procedural, Object Oriented, and Functional programming>\n\nZ<Raku is multi-paradigmatic N<Supporting Procedural, Object Oriented, and Functional programming> >\n\n=head2 Keyboard input\n\nTo flag text as keyboard input enclose it in C<K< >>\n=for code :lang<rakudoc>\nEnter your name K<John Doe>\n\nZ<If used will bust Pod::To::BigPage>\n\n=head2 Replaceable\n\nThe C<R<>> formatting code specifies that the contained text is a\nB<replaceable item>, a placeholder, or a metasyntactic variable. It is\nused to indicate a component of a syntax or specification that should\neventually be replaced by an actual value. For example:\n\n=begin code :lang<rakudoc>\nThe basic C<ln> command is: C<ln> R<source_file> R<target_file>\n=end code\n\nor:\n\n=begin code :lang<rakudoc>\nThen enter your details at the prompt:\n\n=for input\n    Name: R<your surname>\n      ID: R<your employee number>\n    Pass: R<your 36-letter password>\n=end code\n\n=head2 Terminal output\n\nTo flag text as terminal output enclose it in C<T< >>\n=for code :lang<rakudoc>\nHello T<John Doe>\n\nZ<If used will bust Pod::To::BigPage>\n\n=head2 Unicode\n\nTo include Unicode code points or HTML5 character references in a Rakudoc document,\nenclose them in C<E< >>\n\nC<E< >> can enclose a number, which is treated as the decimal Unicode\nvalue for the desired code point. It can also enclose explicit binary, octal,\ndecimal, or hexadecimal numbers using the Raku notations for explicitly based\nnumbers.\n\nIt can also enclose a Unicode code point name.\n\n=begin code :lang<rakudoc>\nRaku makes considerable use of the E<laquo> and E<raquo> characters.\n\nRaku makes considerable use of the E<171> and E<187> characters.\n\nRaku makes considerable use of the E<0b10101011> and E<0b10111011> characters.\n\nRaku makes considerable use of the E<0o253> and E<0o273> characters.\n\nRaku makes considerable use of the E<0d171> and E<0d187> characters.\n\nRaku makes considerable use of the E<0xAB> and E<0xBB> characters.\n\nRaku makes considerable use of the E<LEFT-POINTING DOUBLE ANGLE QUOTATION MARK> and E<RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK> characters.\n=end code\n\nRaku makes considerable use of the « and » characters.\n\nYou can also provide multiple code points in a C<;> separated list, such as:\n\n=begin code :lang<rakudoc>\nRaku makes considerable use of E<171;nbsp;raquo>.\n=end code\n\nRaku makes considerable use of « ».\n\n=head2 Verbatim text\n\nThis code is not implemented by C<Pod::To::HTML>, but is implemented in\nC<Pod::To::BigPage>.\n\nThe C<V<>> formatting code treats its entire contents as being B<verbatim>,\ndisregarding every apparent formatting code within it. For example:\n\n=for code :lang<rakudoc>\nThe B<V<V<>>> formatting code disarms other codes\nsuch as V<I<>, C<>, B<>, and M<>.>\n\nNote, however that the C<V<>> code only changes the way its\ncontents are parsed, I<not> the way they are rendered. That is, the\ncontents are still wrapped and formatted like plain text, and the\neffects of any formatting codes surrounding the C<V<>> code\nare still applied to its contents. For example the previous example\nis rendered as:\n\n=nested\nThe B<V<V<>>> formatting code disarms other codes\nsuch as V<I<>, C<>, B<>, and M<>.>\n\n=head2 Indexing terms\n\nAnything enclosed in an C<X<>> code is an B<index entry>. The contents\nof the code are both formatted into the document and used as the\n(case-insensitive) index entry:\n\n=begin code :allow<B> :lang<rakudoc>\nAn B<X<array>> is an ordered list of scalars indexed by number,\nstarting with 0. A B<X<hash>> is an unordered collection of scalar\nvalues indexed by their associated string key.\n=end code\n\nYou can specify an index entry in which the indexed text and the index\nentry are different, by separating the two with a vertical bar:\n\n=begin code :allow<B> :lang<rakudoc>\nAn B<X<array|arrays>> is an ordered list of scalars indexed by number,\nstarting with 0. A B<X<hash|hashes>> is an unordered collection of\nscalar values indexed by their associated string key.\n=end code\n\nIn the two-part form, the index entry comes after the bar and is\ncase-sensitive.\n\nYou can specify hierarchical index entries by separating indexing levels\nwith commas:\n\n=begin code :allow<B> :lang<rakudoc>\nAn X<array|B<arrays, definition of>> is an ordered list of scalars\nindexed by number, starting with 0. A X<hash|B<hashes, definition of>>\nis an unordered collection of scalar values indexed by their\nassociated string key.\n=end code\n\nYou can specify two or more entries for a single indexed text, by separating\nthe entries with semicolons:\n\n=begin code :allow<B> :lang<rakudoc>\nA X<hash|B<hashes, definition of; associative arrays>>\nis an unordered collection of scalar values indexed by their\nassociated string key.\n=end code\n\nThe indexed text can be empty, creating a \"zero-width\" index entry:\n\n=begin code :allow<B> :lang<rakudoc>\nB<X<|puns, deliberate>>This is called the \"Orcish Maneuver\"\nbecause you \"OR\" the \"cache\".\n=end code\n\n=head1 Rendering Pod\n\n=head2 HTML\n\nIn order to generate HTML from Pod, you need the\nL<Pod::To::HTML module|https://github.com/Raku/Pod-To-HTML>.\n\nIf it is not already installed, install it by running the following command:\nC<zef install Pod::To::HTML>\n\nOnce installed, run the following command in the terminal:\n=begin code :lang<shell>\nraku --doc=HTML input.rakudoc > output.html\n=end code\n\n=head2 Markdown\n\nIn order to generate Markdown from Pod, you need\nthe L<Pod::To::Markdown module|https://github.com/softmoth/perl6-pod-to-markdown>.\n\nIf it is not already installed, install it by running the following command:\nC<zef install Pod::To::Markdown>\n\nOnce installed, run the following command in the terminal:\n=begin code :lang<shell>\nraku --doc=Markdown input.rakudoc > output.md\n=end code\n\n=head2 Text\n\nIn order to generate text from Pod, you can use the default\nC<Pod::To::Text> module.\n\nUsing the terminal, run the following command:\n=begin code :lang<shell>\nraku --doc=Text input.rakudoc > output.txt\n=end code\n\nYou can omit the C<=Text> portion:\n\n=begin code :lang<shell>\nraku --doc input.rakudoc > output.txt\n=end code\n\nYou can even embed Rakudoc directly in your program and add the\ntraditional Unix command line \"--man\" option to your program with a\nmulti MAIN subroutine like this:\n\n=begin code\n=begin pod\n\n=head1 OVERVIEW\n\nHello, world!\n\n=end pod\n\nuse Pod::To::Text;\n\nmulti MAIN(Bool :$man!) {\n    say pod2text $=pod;\n}\n\nmulti MAIN() {\n    say \"HELLO\";\n}\n=end code\n\nNow C<myprogram --man> will output your Rakudoc rendered as a man page.\n\n=head1 Accessing Pod\n\nIn order to access Rakudoc documentation from within a Raku program the\nspecial C<=> twigil, as documented\nin the L<variables section|/language/variables#The_=_twigil>, must be used.\n\nThe C<=> twigil provides the introspection over the Rakudoc structure,\nproviding a L<C<Pod::Block>|/type/Pod::Block> tree root from which it is possible\nto access the whole structure of the Rakudoc document.\n\nAs an example, the following piece of code introspects\nits own Rakudoc documentation:\n\n=begin code\n=begin pod\n\n=head1 This is a head1 title\n\nThis is a paragraph.\n\n=head2 Subsection\n\nHere some text for the subsection.\n\n=end pod\n\nfor $=pod -> $pod-item {\n    for $pod-item.contents -> $pod-block {\n      $pod-block.raku.say;\n    }\n}\n=end code\n\nproducing the following output:\n\n=for code\nPod::Heading.new(level => 1, config => {}, contents => [Pod::Block::Para.new(config => {}, contents => [\"This is a head1 title\"])]);\nPod::Block::Para.new(config => {}, contents => [\"This is a paragraph.\"]);\nPod::Heading.new(level => 2, config => {}, contents => [Pod::Block::Para.new(config => {}, contents => [\"Subsection\"])]);\nPod::Block::Para.new(config => {}, contents => [\"Here some text for the subsection.\"]);\n=end pod\n"
  },
  {
    "path": "doc/Language/pragmas.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Pragmas\n\n=SUBTITLE Special modules that define certain aspects of the behavior of the code\n\nIn Raku, B<pragmas> are directive used to either identify a specific\nversion of Raku to be used or to modify the compiler's normal behavior\nin some way. The C<use> keyword enables a pragma (similar to how you can\nC<use> a module). To disable a pragma, use the C<no> keyword:\n\n=begin code :solo\nuse v6.c;   # use 6.c language version\nno worries; # don't issue compile time warnings\n=end code\n\nFollowing is a list of pragmas with a short description of each\npragma's purpose or a link to more details about its use.\n\n=head2 X<v6.x|Pragmas,v6.x>\n\nThis pragma states the version of the compiler that is going to be used,\nand turns on its features if they are optional.\n\nSince these pragmas turn on the compiler version, they should be the\nfirst statement in the file (preceding comments and Pod are fine).\n\n=for code :solo\nuse v6;           # Load latest supported version (non-PREVIEW).\n\nHistorically, C<use v6;> was intended to signal to Perl interpreters to\nerror out and warn the user to use Perl 6. This is no longer a consideration,\nso this statement has therefore become meaningless.\n\n=for code :solo\nuse v6.c;         # Use the \"Christmas\" version of Raku\n\n=for code :solo\nuse v6.d;         # Use the \"Diwali\" version of Raku\n\nFrom 2018.11, which implemented 6.d, this pragma does not do anything.\n\n=for code :solo\nuse v6.d.PREVIEW; # On 6.d-capable compilers, enables 6.d features,\n                  # otherwise enables the available experimental\n                  # preview features for 6.d language\n\n=for code :solo\nuse v6.e.PREVIEW; # Enables the available experimental preview features\n                  # for 6.e language\n\n=for code :solo\nuse v6.*;         # Enables the available experimental preview features\n                  # for the language version currently in development\n\n=head2 X<MONKEY-GUTS|Pragmas,MONKEY-GUTS>\n\nC<use MONKEY-GUTS;>\n\nThis pragma is not currently part of any Raku specification, but is present\nin Rakudo as a synonym to C<use nqp> (see below).\n\n=head2 X<MONKEY-SEE-NO-EVAL|Pragmas,MONKEY-SEE-NO-EVAL>\nC<use EVAL;>\n\nEnables usage of the C<EVAL> routine,\nwhich due to its dangerousness would otherwise trigger a compiler error.\nFor details, see L<routine C<EVAL>|/type/independent-routines#routine_EVAL>.\n\nNote that, unlike the I<routine>, the C<EVAL> I<method> on an object\ncan be executed without this pragma,\ni.e. an absence of C<MONKEY> pragmas is no guarantee against C<EVAL> calls.\n\n=head2 X<MONKEY-TYPING|Pragmas,MONKEY-TYPING>\n\nC<use MONKEY-TYPING;>\n\nEnables C<augment> for adding methods (though not attributes) to existing classes and grammars. See L<augment|/syntax/augment>.\n\n=head2 X<MONKEY|Pragmas,MONKEY>\n\nC<use MONKEY;>\n\nTurns on all available C<MONKEY> pragmas, equivalent to\n\n    use MONKEY-TYPING;\n    use MONKEY-SEE-NO-EVAL;\n    use MONKEY-GUTS;\n\n=head2 X<dynamic-scope|Pragmas,dynamic-scope>\n\nApplies the L<is dynamic|/type/Variable#trait_is_dynamic> trait to variables\nin the pragma's lexical scope. The effect can be restricted to a subset of\nvariables by listing their names as arguments. By default applies to I<all>\nvariables.\n\n=begin code\n# Apply `is dynamic` only to $x, but not to $y\nuse dynamic-scope <$x>;\n\nsub poke {\n    say $CALLER::x;\n    say $CALLER::y;\n}\n\nmy $x = 23;\nmy $y = 34;\npoke;\n\n# OUTPUT:\n# 23\n# Cannot access '$y' through CALLER, because it is not declared as dynamic\n=end code\n\nThis pragma is not currently part of any Raku specification and was added\nin Rakudo 2019.03.\n\n=head2 X<experimental|Pragmas,experimental>\n\nAllows use of L<experimental features|/language/experimental>\n\n=head2 X<fatal|Pragmas,fatal>\n\nA lexical pragma that makes L<Failures|/type/Failure> returned from routines\nfatal. For example, prefix C<+> on a L<C<Str>|/type/Str> coerces it to\nL<C<Numeric>|/type/Numeric>, but will return a L<C<Failure>|/type/Failure> if the\nstring contains non-numeric characters. Saving that L<C<Failure>|/type/Failure> in\na variable prevents it from being sunk, and so the first code block below\nreaches the C<say $x.^name;> line and prints L<C<Failure>|/type/Failure> in output.\n\nIn the second block, the C<use fatal> pragma is enabled, so the C<say> line is\nnever reached because the L<C<Exception>|/type/Exception> contained in the L<C<Failure>|/type/Failure> returned from\nprefix C<+> gets thrown and the C<CATCH> block gets run, printing the\nC<Caught...> line. Note that both blocks are the same program and C<use fatal>\nonly affects the lexical block it was used in:\n\n    {\n        my $x = +\"a\";\n        say $x.^name;\n        CATCH { default { say \"Caught {.^name}\" } }\n    } # OUTPUT: «Failure␤»\n\n    {\n        use fatal;\n        my $x = +\"a\";\n        say $x.^name;\n        CATCH { default { say \"Caught {.^name}\" } }\n    } # OUTPUT: «Caught X::Str::Numeric␤»\n\nInside L«C<try> blocks|/language/exceptions#try_blocks», the\nC<fatal> pragma is enabled by default, and you can I<disable> it with C<no\nfatal>:\n\n    try {\n        my $x = +\"a\";\n        say $x.^name;\n        CATCH { default { say \"Caught {.^name}\" } }\n    } # OUTPUT: «Caught X::Str::Numeric␤»\n\n    try {\n        no fatal;\n        my $x = +\"a\";\n        say $x.^name;\n        CATCH { default { say \"Caught {.^name}\" } }\n    } # OUTPUT: «Failure␤»\n\n=head2 X<isms|Pragmas,isms>\n\nC<[2018.09 and later]>\n\nAllow for some other language constructs that were deemed to be a trap that\nwarranted a warning and/or an error in normal Raku programming.  Currently,\nC<Perl> and C<C++> are allowed.\n\n=begin code :skip-test<compile-time error>\nsub abs() { say \"foo\" }\nabs;\n# Unsupported use of bare \"abs\"; in Raku please use .abs if you meant\n# to call it as a method on $_, or use an explicit invocant or argument,\n# or use &abs to refer to the function as a noun\n=end code\n\nIn this case, providing an C<abs> sub that doesn't take any arguments, did\nnot make the compilation error go away.\n\n    use isms <Perl5>;\n    sub abs() { say \"foo\" }\n    abs;   # foo\n\nWith this, the compiler will allow the offending Perl construct, allowing\nthe code to actually be executed.\n\nIf you do not specify any language, all known language constructs are allowed.\n\n    use isms;   # allow for Perl and C++ isms\n\n=head2 X<lib|Pragmas,lib>\n\nThis pragma adds subdirectories to the library search\npath so that the interpreter can\nL<find the modules|/language/using-modules/finding-installing#Finding_installed_modules>.\n\n=begin code :solo\nuse lib <lib /opt/lib /usr/local/lib>;\n\n#or a mixed list of IO::Path and Str\nuse lib ('.', '.'.IO, './lib'.IO);\n=end code\n\nThis will search the directories passed in a list. Please check\nL<the modules documentation|/language/using-modules/code#use> for more examples.\n\n=head2 X<newline|Pragmas,newline>\n\nSet the value of the L<$?NL|/language/variables#Compile-time_variables> constant\nin the scope it is called.  Possible values are C<:lf> (which is the default,\nindicating Line Feed), C<:crlf> (indicating Carriage Return, Line Feed) and\nC<:cr> (indicating Carriage Return).\n\n=head2 X<nqp|Pragmas,nqp>\n\nUse at your own risk.\n\nThis is a Rakudo-specific pragma. With it, Rakudo provides access to the\nL<nqp opcodes|https://github.com/Raku/nqp/blob/master/docs/ops.markdown>\nin a top level namespace:\n\n    use nqp;\n    nqp::say(\"hello world\");\n\nThis uses the underlying nqp C<say> opcode instead of the Raku routine. This\npragma may make your code rely on a particular version of nqp, and since\nthat code is not part of the Raku specification, it's not guaranteed to\nbe stable. You may find a large number of usages in the Rakudo core,\nwhich are used to make the core functionality as fast as possible.\nFuture optimizations in the code generation of Rakudo may obsolete these\nusages.\n\n=head2 X<precompilation|Pragmas,precompilation>\n\nThe default allows precompilation of source code, specifically if used in a\nmodule.  If for whatever reason you do not want the code (of your module) to\nbe precompiled, you can use C<no precompilation>.  This will prevent the\nentire compilation unit (usually a file) from being precompiled.\n\n=head2 X<soft|Pragmas,soft>\n\nL<Re-dispatching|/language/functions#Re-dispatching>, L<inlining|/language/functions#index-entry-use_soft_(pragma)>\n\n=head2 X<strict|Pragmas,strict>\n\nC<strict> is the default behavior, and requires that you declare variables\nbefore using them. You can relax this restriction with C<no>.\n\n=for code\nno strict; $x = 42; # OK\n\n=head2 X<trace|Pragmas,trace>\n\nWhen C<use trace> is activated, any line of code executing will be written to\nSTDERR.  You can use C<no trace> to switch off the feature, so this only happens\nfor certain sections of code.\n\n=head2 X<v6|Pragmas,v6>\n\nL<Writing Tests|/language/testing#Writing_tests>\n\n=head2 X<variables|Pragmas,variables>\n\nL<Defined Variables Pragma|/language/variables#Default_defined_variables_pragma>\n\n=head2 X<worries|Pragmas,worries>\n\nLexically controls whether compile-time warnings generated by the\ncompiler get shown. Enabled by default.\n\n    =begin code :lang<text>\n    $ raku -e 'say :foo<>.Pair'\n    Potential difficulties:\n      Pair with <> really means an empty list, not null string; use :foo('') to represent the null string,\n        or :foo() to represent the empty list more accurately\n      at -e:1\n      ------> say :foo<>⏏.Pair\n    foo => Nil\n\n    $ raku -e 'no worries; say :foo<>.Pair'\n    foo => Nil\n    =end code\n\n=end pod\n"
  },
  {
    "path": "doc/Language/py-nutshell.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"migration\")\n\n=TITLE Python to Raku - nutshell\n\n=SUBTITLE Learning Raku from Python, in a nutshell\n\nThis page is an attempt to provide a way to learn Raku\nfor folks coming from a Python background. We discuss\nthe equivalent syntax in Raku for a number of Python\nconstructs and idioms.\n\n=head1 Basic syntax\n\n=head2 Hello, world\n\nLet's start with printing \"Hello, world!\". The L<put|/routine/put> keyword in\nRaku is the equivalent of L<print|/routine/print> in Python. Like Python 2,\nparentheses are optional. A newline is added to the end of the line.\n\nI<Python 2>\n\n=for code :lang<python>\nprint \"Hello, world!\"\n\nI<Python 3>\n\n=for code :lang<python>\nprint(\"Hello, world!\")\n\nRaku\n\n    put \"Hello, world!\"\n\nThere is also the L<say|/routine/say> keyword, which behaves similarly, but will\ncall the L<gist|/routine/gist> method of its argument.\n\nRaku\n\n   my $hello = \"Hello, world!\";\n   say $hello;  # also prints \"Hello, world!\"\n                # same as: put $hello.gist\n\nIn Python, C<'> and C<\"> are interchangeable.\nIn Raku, both may be used for quoting, but double\nquotes (C<\">) signify that interpolation should be performed.\nFor instance, variables that start with a C<$>, and expressions\ncontained in curly braces are interpolated.\n\nRaku\n\n    my $planet = 'earth';\n    say \"Hello, $planet\";                 # OUTPUT: «Hello, earth␤»\n    say 'Hello, $planet';                 # OUTPUT: «Hello, $planet␤»\n    say \"Hello, planet number { 1 + 2 }\"; # OUTPUT: «Hello, planet number 3␤»\n\n=head2 Statement separators\n\nIn Python, a newline signifies the end of a statement.\nThere are a few exceptions: A backslash before a newline\ncontinues a statement across lines. Also if there is\nan unmatched opening parentheses, square bracket, or curly\nbrace, the statement continues across lines, until the\nmatching curly braces are closed.\n\nIn Raku, a semicolon signifies the end of a statement.\nThe semicolon may be omitted if it is the last statement\nof a block. The semicolon may also be omitted if there\nis a closing curly brace followed by a newline.\n\nPython\n\n=for code :lang<python>\nprint 1 + 2 + \\\n    3 + 4\nprint ( 1 +\n    2 )\n\nRaku\n\n    say 1 + 2 +\n        3 + 4;\n    say 1 +\n        2;\n\n=head2 Blocks\n\nIn Python, indentation is used to indicate a block. Raku\nuses curly braces.\n\nPython\n\n=for code :lang<python>\nif 1 == 2:\n    print(\"Wait, what?\")\nelse:\n    print(\"1 is not 2.\")\n\nRaku\n\n    if 1 == 2 {\n        say \"Wait, what?\"\n    } else {\n        say \"1 is not 2.\"\n    }\n\nParentheses are optional in both languages for expressions in\nconditionals, as shown above.\n\n=head2 Variables\n\nIn Python, variables are declared and initialized at the same time:\n\n=for code :lang<python>\nfoo = 12\nbar = 19\n\nIn Raku, the C<my> declarator declares a lexical variable. A variable can be\ninitialized with C<=>. This variable can either be declared first and later\ninitialized or declared and initialized at once.\n\n\n    my $foo;       # declare\n    $foo = 12;     # initialize\n    my $bar = 19;  # both at once\n\nAlso, as you may have noticed, variables in Raku usually start with sigils --\nsymbols indicating the type of their container. Variables starting with a C<$>\nhold scalars. Variables starting with an C<@> hold arrays, and variables\nstarting with a C<%> hold a hash (dict). Sigilless variables, declared with a\nC<\\> but used without them, are bound to the value they are assigned to and are\nthus immutable.\n\nPlease note that, from now on, we are going to use sigilless variables in most\nexamples just to illustrate the similarity with Python. That is technically\ncorrect, but in general we are going to use sigilless variables in places where\ntheir immutability (or independence of type, when they are used in signatures)\nis needed or needs to be highlighted.\n\nPython\n\n=begin code :lang<python>\ns = 10\nl = [1, 2, 3]\nd = { 'a' : 12, 'b' : 99 }\n\nprint(s)\nprint(l[2])\nprint(d['a'])\n# 10, 3, 12\n=end code\n\nRaku\n\n    my $s = 10;\n    my @l = 1, 2, 3;\n    my %d = a => 12, b => 99;\n    my \\x = 99;\n\n    say $s;\n    say @l[1];\n    say %d<a>;  # or %d{'a'}\n    say x;\n    # 10, 2, 12, 99\n\n\n=head2 Scope\n\nIn Python, functions and classes create a new scope, but no other\nblock constructor (e.g. loops, conditionals) creates a scope. In\nPython 2, list comprehensions do not create a new scope, but in\nPython 3, they do.\n\nIn Raku, every block creates a lexical scope.\n\nPython\n\n=for code :lang<python>\nif True:\n    x = 10\nprint(x)\n# x is now 10\n\nRaku\n\n=for code :skip-test<compile time error>\nif True {\n    my $x = 10\n}\nsay $x\n# error, $x is not declared in this scope\n\n=for code\nmy $x;\nif True {\n    $x = 10\n}\nsay $x\n# ok, $x is 10\n\nPython\n\n=for code :lang<python>\nx = 10\nfor x in 1, 2, 3:\n   pass\nprint(x)\n# x is 3\n\nRaku\n\n    my \\x = 10;\n    for 1, 2, 3 -> \\x {\n        # do nothing\n    }\n    say x;\n    # x is 10\n\nLambdas in Python can be written as blocks or pointy blocks in Raku.\n\nPython\n\n=for code :lang<python>\nl = lambda i: i + 12\n\nRaku\n\n=for code :preamble<my $i>\nmy $l = -> $i { $i + 12 }\n\nAnother Raku idiom for constructing lambdas is the Whatever star, C<*>.\n\nRaku\n\n    my $l = * + 12    # same as above\n\nA C<*> in an expression will become a placeholder for the argument,\nand transform the expression into a lambda at compile time. Each\nC<*> in an expression is a separate positional parameter.\n\nSee the section below for more constructs regarding subroutines and blocks.\n\nAnother example (from the Python\nL<FAQ|https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result>):\n\nPython\n\n=for code :lang<python>\nsquares = []\nfor x in range(5):\n    squares.append(lambda: x ** 2)\nprint(squares[2]())\nprint(squares[4]())\n# both 16 since there is only one x\n\nRaku\n\n    my \\squares = [];\n    for ^5 -> \\x {\n        squares.append({ x² });\n    }\n    say squares[2]();\n    say squares[4]();\n    # 4, 16 since each loop iteration has a lexically scoped x,\n\nNote that C<^N> is like C<range(N)>. Similarly,\nC<N..^M> works like C<range(N, M)> (a list from N\nto M - 1). The range C<N..M> is a list from N to M. The\nC<^> before or after the C<..> indicates that the\nbeginning or ending endpoint of the list (or both)\nshould be excluded.\n\nAlso, C<x²> is a cute way of writing C<x ** 2> (which also\nworks fine); the unicode superscript 2 squares a number.\nMany of the other unicode operators work as you would expect\n(exponents, fractions, π), but every unicode operator\nor symbol that can be used in Raku has an ASCII equivalent.\n\n=head2 Control flow\n\nPython has C<for> loops and C<while> loops:\n\n=for code :lang<Python>\nfor i in 1, 2:\n    print(i)\nj = 1\nwhile j < 3:\n    print(j)\n    j += 1\n\n# 1, 2, 1, 2\n\nRaku also has C<for> loops and C<while> loops:\n\n    for 1, 2 -> $i {\n        say $i\n    }\n    my $j = 1;\n    while $j < 3 {\n        say $j;\n        $j += 1\n    }\n\n(Raku also has a few more looping constructs: C<repeat...until>,\nC<repeat...while>, C<until>, and C<loop>.)\n\nC<last> leaves a loop in Raku, and is analogous to\nC<break> in Python. C<continue> in Python is C<next>\nin Raku.\n\nPython\n\n=for code :lang<python>\nfor i in range(10):\n    if i == 3:\n        continue\n    if i == 5:\n        break\n    print(i)\n\nRaku\n\n    for ^10 -> $i {\n        next if $i == 3;\n        last if $i == 5;\n        say $i;\n    }\n\nUsing C<if> as a statement modifier (as above) is acceptable\nin Raku, even outside of a list comprehension.\n\nThe C<yield> statement within a C<for> loop in Python, which produces a\nC<generator>, is like a C<gather>/C<take> construct in Raku. These\nboth print 1, 2, 3.\n\nI<Python>\n\n=begin code :lang<python>\ndef count():\n    for i in 1, 2, 3:\n        yield i\n\nfor c in count():\n    print(c)\n=end code\n\nI<Raku>\n\n    sub count {\n        gather {\n            for 1, 2, 3 -> $i {\n                take $i\n            }\n        }\n    }\n\n    for count() -> $c {\n        say $c;\n    }\n\nUses of Python's C<enumerate()> and C<.items()> mechanisms for\niterating lists or dict/maps can both be achieved using the same\nL<kv|/routine/kv> method in Raku (because the \"key\" of a list is its\narray-like numeric index):\n\nI<Python>\n\n=begin code :lang<python>\nelems = [\"neutronium\", \"hydrogen\", \"helium\", \"lithium\"]\nfor i, e in enumerate(elems):\n    print(\"Elem no. %d is %s\" % (i, e))\nsymbols = [\"n\", \"H\", \"He\", \"Li\"]\nelem4Symbol = {s: e for s, e in zip(symbols, elems)}\nfor symbol, elem in elem4Symbol.items():\n    print(\"Symbol '%s' stands for %s\" % (symbol, elem))\n# Elem no. 0 is neutronium\n# Elem no. 1 is hydrogen\n# Elem no. 2 is helium\n# Elem no. 3 is lithium\n# Symbol 'H' stands for hydrogen\n# Symbol 'He' stands for helium\n# Symbol 'Li' stands for lithium\n# Symbol 'n' stands for neutronium\n=end code\n\nI<Raku>\n\n    my @elems = <neutronium hydrogen helium lithium>;\n    for @elems.kv -> $i, $e {\n        say \"Elem no. $i is $e\"\n    }\n\n    my @symbols = <n H He Li>;\n    my %elem-for-symbol;\n    %elem-for-symbol{@symbols} = @elems;\n\n    # Note that the iteration order will differ from Python\n    for %elem-for-symbol.kv -> $symbol, $element {\n        say \"Symbol '$symbol' stands for $element\";\n    }\n\n=head2 Lambdas, functions and subroutines>\n\nDeclaring a function (subroutine) with C<def> in Python is accomplished\nwith C<sub> in Raku.\n\n=begin code :lang<python>\ndef add(a, b):\n    return a + b\n\nsub add(\\a, \\b) {\n    return a + b\n}\n=end code\n\nThe C<return> is optional; the value of the last expression is used as\nthe return value:\n\n=begin code\nsub add(\\a, \\b) {\n    a + b\n}\n=end code\n\n=begin code\n# using variables with sigils\nsub add($a, $b) {\n    $a + $b\n}\n=end code\n\nPython 2 functions can be called with positional arguments\nor keyword arguments.  These are determined by the caller.\nIn Python 3, some arguments may be \"keyword only\".\nIn Raku, positional and named arguments are determined\nby the signature of the routine.\n\nPython\n\n=begin code :lang<python>\ndef speak(word, times):\n    for i in range(times):\n        print word\nspeak('hi', 2)\nspeak(word='hi', times=2)\n=end code\n\nRaku\n\nPositional parameters:\n\n    sub speak($word, $times) {\n      say $word for ^$times\n    }\n    speak('hi', 2);\n\nNamed parameters start with a colon:\n\n    sub speak(:$word, :$times) {\n      say $word for ^$times\n    }\n    speak(word => 'hi', times => 2);\n    speak(:word<hi>, :times<2>);      # Alternative, more idiomatic\n\nRaku supports multiple dispatch, so several signatures\ncould be made available by declaring a routine as a C<multi>.\n\n    multi speak($word, $times) {\n      say $word for ^$times\n    }\n    multi speak(:$word, :$times) {\n        speak($word, $times);\n    }\n    speak('hi', 2);\n    speak(:word<hi>, :times<2>);\n\nNamed parameters can be sent using a variety of formats:\n\n    sub hello {...};\n    # all the same\n    hello(name => 'world'); # fat arrow syntax\n    hello(:name('world'));  # pair constructor\n    hello :name<world>;     # <> quotes words and makes a list\n    my $name = 'world';\n    hello(:$name);          # lexical var with the same name\n\nCreating an anonymous function can be done with C<sub>, with a block or with\na pointy block.\n\nPython\n\n=for code :lang<python>\nsquare = lambda x: x ** 2\n\nRaku\n\n    my $square = sub ($x) { $x ** 2 };  # anonymous sub\n    my $square = -> $x { $x ** 2 };     # pointy block\n    my $square = { $^x ** 2 };          # placeholder variable\n    my $square = { $_ ** 2 };           # topic variable\n\nPlaceholder variables are lexicographically ordered to form positional\nparameters. Thus these are the same:\n\n    my $power = { $^x ** $^y };\n    my $power = -> $x, $y { $x ** $y };\n\n=head2 List comprehensions\n\nPostfix statement modifiers and blocks can be combined to\neasily create list comprehensions in Raku.\n\nPython\n\n=for code :lang<python>\nprint([ i * 2 for i in [3, 9]])                      # OUTPUT: «[6, 18]␤»\n\nRaku\n\n    say ( $_ * 2 for 3, 9 );                           # OUTPUT: «(6 18)␤»\n    say ( { $^i * 2 } for 3, 9 );                      # OUTPUT: «(6 18)␤»\n    say ( -> \\i { i * 2 } for 3, 9 );                  # OUTPUT: «(6 18)␤»\n\nConditionals can be applied, but the C<if> keyword comes first,\nunlike in Python where the if comes second.\n\n=for code :lang<python>\nprint [ x * 2 for x in [1, 2, 3] if x > 1 ]          # OUTPUT: «[4, 6]␤»\n\nvs\n\n    say ( $_ * 2 if $_ > 1 for 1, 2, 3 );              # OUTPUT: «(4 6)␤»\n\nFor nested loops, the cross product operator C<X>\nwill help:\n\n=for code :lang<python>\nprint([ i + j for i in [3,9] for j in [2,10] ])       # OUTPUT: «[5, 13, 11, 19]␤»\n\nbecomes either of these:\n\n    say ( { $_[0] + $_[1] } for (3,9) X (2,10) );      # OUTPUT: «(5 13 11 19)␤»\n    say ( -> (\\i, \\j) { i + j } for (3,9) X (2,10) );  # OUTPUT: «(5 13 11 19)␤»\n    say ( -> ($i, $j) { $i + $j } for (3,9) X (2,10) );# OUTPUT: «(5 13 11 19)␤»\n    say ( { $^a[0] + $^a[1] } for (3,9) X (2,10) );    # OUTPUT: «(5 13 11 19)␤»\n\nUsing C<map> (which is just like Python's C<map>) and C<grep> (which is like\nPython's C<filter>) is an alternative.\n\n=head2 Classes and objects\n\nHere's an example from the Python\nL<docs|https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables>.\nFirst let's go over \"instance variables\" which are known as attributes\nin Raku:\n\nPython:\n\n=for code :lang<python>\nclass Dog:\n    def __init__(self, name):\n        self.name = name\n\nRaku:\n\n    class Dog {\n        has $.name;\n    }\n\nFor each created class, Raku provides the constructor method C<new>\nby default which takes named arguments.\n\nPython:\n\n=for code :lang<python>\nd = Dog('Fido')\ne = Dog('Buddy')\nprint(d.name)\nprint(e.name)\n\nRaku\n\n=for code :preamble<class Dog {}>\nmy $d = Dog.new(:name<Fido>); # or: Dog.new(name => 'Fido')\nmy $e = Dog.new(:name<Buddy>);\nsay $d.name;\nsay $e.name;\n\nClass attributes in Raku can be declared in a few ways. One way\nis to just declare a lexical variable and a method for accessing it.\n\nPython:\n\n=for code :lang<python>\nclass Dog:\n    kind = 'canine'                # class attribute\n    def __init__(self, name):\n        self.name = name           # instance attribute\nd = Dog('Fido')\ne = Dog('Buddy')\nprint(d.kind)\nprint(e.kind)\nprint(d.name)\nprint(e.name)\n\nRaku:\n\n    class Dog {\n        my $kind = 'canine';           # class attribute\n        method kind { $kind }\n        has $.name;                    # instance attribute\n    }\n\n    my $d = Dog.new(:name<Fido>);\n    my $e = Dog.new(:name<Buddy>);\n    say $d.kind;\n    say $e.kind;\n    say $d.name;\n    say $e.name;\n\nIn order to mutate attributes in Raku, you must use\nthe C<is rw> trait on the attributes:\n\nPython:\n\n=for code :lang<python>\nclass Dog:\n    def __init__(self, name):\n        self.name = name\nd = Dog()\nd.name = 'rover'\n\nRaku:\n\n    class Dog {\n        has $.name is rw;\n    }\n    my $d = Dog.new;\n    $d.name = 'rover';\n\nInheritance is done using C<is>:\n\nPython\n\n=begin code :lang<python>\nclass Animal:\n    def jump(self):\n        print (\"I am jumping\")\n\nclass Dog(Animal):\n    pass\n\nd = Dog()\nd.jump()\n=end code\n\nRaku\n\n    class Animal {\n        method jump {\n            say \"I am jumping\"\n        }\n    }\n\n    class Dog is Animal {\n    }\n\n    my $d = Dog.new;\n    $d.jump;\n\nMultiple inheritance is possible by using the C<is> trait as many times\nas required. Alternatively, it can be used in conjunction with the\nC<also> keyword.\n\nPython\n\n=for code :lang<python>\nclass Dog(Animal, Friend, Pet):\n    pass\n\nRaku\n\n    class Animal {}; class Friend {}; class Pet {};\n    ...;\n    class Dog is Animal is Friend is Pet {};\n\nor\n\n    class Animal {}; class Friend {}; class Pet {};\n    ...;\n    class Dog is Animal {\n        also is Friend;\n        also is Pet;\n        ...\n    }\n\n=head2 Decorators\n\nDecorators in Python are a way of wrapping a function\nin another one. In Raku, this is done with C<wrap>.\n\nPython\n\n=begin code :lang<python>\ndef greeter(f):\n    def new():\n        print('hello')\n        f()\n    return new\n\n@greeter\ndef world():\n    print('world')\n\nworld();\n=end code\n\nRaku\n\n    sub world {\n        say 'world'\n    }\n\n    &world.wrap(sub () {\n        say 'hello';\n        callsame;\n    });\n\n    world;\n\nAn alternative would be to use a trait:\n\n    # declare the trait 'greeter'\n    multi trait_mod:<is>(Routine $r, :$greeter) {\n        $r.wrap(sub {\n            say 'hello';\n            callsame;\n        })\n    }\n\n    sub world is greeter {\n        say 'world';\n    }\n\n    world;\n\n=head2 Context managers\n\nContext managers in Python declare actions that happen when entering\nor exiting a scope.\n\nHere's a Python context manager that prints the strings\n'hello', 'world', and 'bye'.\n\n=begin code :lang<python>\nclass hello:\n    def __exit__(self, type, value, traceback):\n        print('bye')\n    def __enter__(self):\n        print('hello')\n\nwith hello():\n    print('world')\n=end code\n\nFor \"enter\" and \"exit\" events, passing a block as\nan argument would be one option:\n\n    sub hello(Block $b) {\n        say 'hello';\n        $b();\n        say 'bye';\n    }\n\n    hello {\n        say 'world';\n    }\n\nA related idea is 'L<Phasers|/language/phasers>' which may be set up to\nrun on entering or leaving a block.\n\n    {\n        LEAVE say 'bye';\n        ENTER say 'hello';\n        say 'world';\n    }\n\n=head2 C<input>\n\nIn Python 3, the C<input> keyword is used to prompt the user. This keyword\ncan be provided with an optional argument which is written to standard output\nwithout a trailing newline:\n\n=begin code :lang<python>\nuser_input = input(\"Say hi → \")\nprint(user_input)\n=end code\n\nWhen prompted, you can enter C<Hi> or any other string, which will be stored\nin the C<user_input> variable. This is similar to L<prompt|/routine/prompt> in Raku:\n\n    my $user_input = prompt(\"Say hi → \");\n    say $user_input; # OUTPUT: whatever you entered.\n\n=head2 Tuples\n\nPython tuples are immutable sequences.  The sequence elements do not need\nto be of the same types.\n\nPython\n\n=for code :lang<python>\ntuple1 = (1, \"two\", 3, \"hat\")\ntuple2 = (5, 6, \"seven\")\nprint(tuple1[1])                                   # OUTPUT: «two␤»\ntuple3 = tuple1 + tuple2\nprint(tuple3)                                      # OUTPUT: «(1, 'two', 3, 'hat', 5, 6, 'seven')␤»\n\nRaku\n\nRaku does not have a builtin Tuple type. You can get the same behavior from\nRaku using the List type, or from an external module.\n\n    my $list1 = (1, \"two\", 3, \"hat\");\n    my $list2 = (5, 6, \"seven\");\n    say $list1[1];                                 # OUTPUT: «two␤»\n    my $list3 = (slip($list1), slip($list2));\n    my $list4 = (|$list1, |$list2);                # equivalent to previous line\n    say $list3;                                    # OUTPUT: «(1, two, 3, hat, 5, 6, seven)␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Language/quoting.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Quoting constructs\n\n=SUBTITLE Writing strings and word lists, in Raku\n\n=head1 The Q lang\n\nStrings are usually represented in Raku code using some form of quoting\nconstruct. The most minimalistic of these is C<Q>, usable via the shortcut\nC<｢…｣>, or via C<Q> followed by any pair of delimiters surrounding your\ntext, including many\nL<Unicode pairs|https://github.com/Raku/roast/blob/aa4994a7f6b3f6b450a9d231bebd5fba172439b0/S02-literals/quoting-unicode.t#L49-L65>.\nMost of the time, though, the most you'll need is\nC<'…'>\n or C<\"…\">,\ndescribed in more detail in the following sections.\n\nFor information about quoting as applied in regexes, see the L<regular\nexpression documentation|/language/regexes>.\n\n=head2 X<Literal strings: Q|Syntax,Q>\n\nX<|Syntax,｢ ｣>\n\n=for code :skip-test<listing>\nQ[A literal string]\n｢More plainly.｣\nQ^Almost any non-word character can be a delimiter!^\nQ｢｢Delimiters can be repeated/nested if they are adjacent.｣｣\nQ｟Quoting with fancy unicode pairs｠\n\nDelimiters can be nested, but in the plain C<Q> form, backslash escapes\naren't allowed. In other words, basic C<Q> strings are as literal as\npossible.\n\nSome delimiters are not allowed immediately after C<Q>, C<q>, or C<qq>. Any\ncharacters that are allowed in L<identifiers|/language/syntax#Identifiers> are\nnot allowed to be used, since in such a case, the quoting construct together\nwith such characters are interpreted as an identifier. In addition, C<( )> is\nnot allowed because that is interpreted as a function call. If you still wish\nto use those characters as delimiters, separate them from C<Q>, C<q>, or C<qq>\nwith a space. Please note that some natural languages use a left delimiting\nquote on the right side of a string. C<Q> will not support those as it relies\non unicode properties to tell left and right delimiters apart.\n\n=for code :skip-test<listing>\nQ'this will not work!'\nQ(this won't work either!)\n\nThe examples above will produce an error. However, this will work\n\n=for code :skip-test<listing>\nQ (this is fine, because of space after Q)\nQ 'and so is this'\nQ<Make sure you <match> opening and closing delimiters>\nQ{This is still a closing curly brace → \\}\n\nThese examples produce:\n\n=begin code :solo\nthis is fine, because of space after Q\nand so is this\nMake sure you <match> opening and closing delimiters\nThis is still a closing curly brace → \\\n=end code\n\nX<|Adverbs,:x (quoting adverb)>X<|Adverbs,:exec (quoting adverb)>X<|Adverbs,:w (quoting adverb)>X<|Adverbs,:words (quoting adverb)>\nX<|Adverbs,:ww (quoting adverb)>X<|Adverbs,:quotewords (quoting adverb)>X<|Adverbs,:q (quoting adverb)>X<|Adverbs,:single (quoting adverb)>\nX<|Adverbs,:qq (quoting adverb)>X<|Adverbs,:double (quoting adverb)>X<|Adverbs,:s (quoting adverb)>\nX<|Adverbs,:scalar (quoting adverb)>X<|Adverbs,:a (quoting adverb)>X<|Adverbs,:array (quoting adverb)>X<|Adverbs,:h (quoting adverb)>\nX<|Adverbs,:hash (quoting adverb)>X<|Adverbs,:f (quoting adverb)>X<|Adverbs,:function (quoting adverb)>X<|Adverbs,:c (quoting adverb)>\nX<|Adverbs,:closure (quoting adverb)>X<|Adverbs,:b (quoting adverb)>X<|Adverbs,:backslash (quoting adverb)>X<|Adverbs,:to (quoting adverb)>\nX<|Adverbs,:heredoc (quoting adverb)>X<|Adverbs,:v (quoting adverb)>X<|Adverbs,:val (quoting adverb)>\n\nThe behavior of quoting constructs can be modified with adverbs, as explained\nin detail in later sections.\n\n=begin table\nShort       Long            Meaning\n\n:x          :exec           Execute as command and return results\n\n:w          :words          Split result on words (no quote protection)\n\n:ww         :quotewords     Split result on words (with quote protection)\n\n:q          :single         Interpolate \\\\, \\qq[...] and escaping the delimiter with \\\n\n:qq         :double         Interpolate with :s, :a, :h, :f, :c, :b\n\n:s          :scalar         Interpolate $ vars\n\n:a          :array          Interpolate @ vars (when followed by postcircumfix)\n\n:h          :hash           Interpolate % vars (when followed by postcircumfix)\n\n:f          :function       Interpolate & calls\n\n:c          :closure        Interpolate {...} expressions\n\n:b          :backslash      Enable backslash escapes (\\n, \\qq, \\$foo, etc)\n\n:to         :heredoc        Parse result as heredoc terminator\n\n:v          :val            Convert to allomorph if possible\n=end table\n\nThese adverbs can be used together with C<Q>, so that it will interpolate\neven if the quoting operator does not:\n\n=for code\nmy %þ = :is-mighty;\nsay Q \"Þor %þ<>\";                         # OUTPUT: «Þor %þ<>␤»\nsay Q:h\"Þor %þ<>\";                        # OUTPUT: «Þor is-mighty   True␤»\n%þ = :42foo, :33bar;\nsay Q:h:c \"Þor %þ<> →  { [+] %þ.values}\"; # OUTPUT: «Þor bar 33␤foo  42 →  75␤»\nmy @þ= <33 44>; say Q:a \"Array contains @þ[]\"; # OUTPUT: «Array contains 33 44␤»\nsay Q:v<33> + 3;                          # OUTPUT: «36␤»\n\nBy default, and as shown, C<Q> quotes directly without any kind of\ntransformation of the quoted string. The adverbs will modify its behavior,\nconverting, for instance, the string into an allomorph (with the C<:v> adverb)\nor allowing interpolation of hashes (via C<:h>) or C<{}> code sections (via\nC<:c>). Arrays and hashes must be I<followed by a postcircumfix>; that is, the\nsigiled identifier will not interpolate, but followed by an indexing, decont\noperator or a method call with parentheses, it will:\n\n=for code\nmy @þ= <33 44>;\nsay Q:a \"Array contains @þ.elems()\"; # OUTPUT: «Array contains 2␤»\n\nThe same code without the parentheses will simply not interpolate, absent the\npost-circumfix operator.\n\n=head2 X<Escaping: q|Syntax,q>\n\nX<|Syntax,escaping quote>\nX<|Syntax,' '>\n\n=begin code\n'Very plain';\nq[This back\\slash stays];\nq[This back\\\\slash stays]; # Identical output\nq{This is not a closing curly brace → \\}, but this is → };\nQ :q $There are no backslashes here, only lots of \\$\\$\\$!$;\n'(Just kidding. There\\'s no money in that string)';\n'No $interpolation {here}!';\nQ:q!Just a literal \"\\n\" here!;\n=end code\n\nThe C<q> form allows for escaping characters that would otherwise end the\nstring using a backslash. The backslash itself can be escaped, too, as in\nthe third example above. The usual form is C<'…'> or C<q> followed by a\ndelimiter, but it's also available as an adverb on C<Q>, as in the fifth and\nlast example above.\n\nThese examples produce:\n=for code :lang<text>\nVery plain\nThis back\\slash stays\nThis back\\slash stays\nThis is not a closing curly brace → } but this is →\nThere are no backslashes here, only lots of $$$!\n(Just kidding. There's no money in that string)\nNo $interpolation {here}!\nJust a literal \"\\n\" here\n\nThe C<\\qq[...]> escape sequence enables\nL«C<qq> interpolation|/language/quoting#Interpolation:_qq» for a portion\nof the string. Delimiters other than C<[]> can also be used.\nUsing a C<q>-quoted string in combination with this escape sequence is handy when\nHTML markup is involved, to avoid interpretation of angle brackets as hash keys:\n\n    my $var = 'foo';\n    say '<code>$var</code> is <var>\\qq[$var.uc()]</var>';\n    # OUTPUT: «<code>$var</code> is <var>FOO</var>␤»\n\n=head2 X<Interpolation: qq|Syntax,qq>\n\nX<|Syntax,\" \">\n\n=begin code\nmy $color = 'blue';\nsay \"My favorite color is $color!\"; # OUTPUT: «My favorite color is blue!␤»\n=end code\n\nX<|Syntax,\\ (quoting)>\n\nThe C<qq> form – usually written using double quotes – allows for\ninterpolation of backslash escape sequences (like C<q:backslash>), all sigiled\nvariables (like C<q:scalar:array:hash:function>), and any code inside C<{...}>\n(like C<q:closure>).\n\n=head3 Interpolating variables\n\nInside a C<qq>-quoted string, you can use variables with a sigil to trigger\ninterpolation of the variable's value.  Variables with the C<$> sigil are\ninterpolated whenever the occur (unless escaped); that's why, in the example\nabove, C<\"$color\"> became C<blue>.\n\nVariables with other sigils, however, only trigger interpolation when you follow\nthe variable with the appropriate postfix (C<[]> for Arrays, C«{}» or C«<>» or C<«»> for Hashes,\nC<()> for Subs). This allows you to write expressions like\nC<\"documentation@raku.org\"> without interpolating the C<@raku> variable.\n\nTo interpolate an Array (or other L<C<Positional>|/type/Positional> variable),\nappend a C<[]> to the variable name:\n\n=begin code\nmy @neighbors = \"Felix\", \"Danielle\", \"Lucinda\";\nsay \"@neighbors[] and I try our best to coexist peacefully.\"\n# OUTPUT: «Felix Danielle Lucinda and I try our best to coexist peacefully.␤»\n=end code\n\nAlternatively, rather than using C<[]>, you can interpolate the Array by\nfollowing it with a method call with parentheses after the method name. Thus the\nfollowing code will work:\n\n=begin code :preamble<my @neighbors = \"Felix\", \"Danielle\", \"Lucinda\">\nsay \"@neighbors.join(', ') and I try our best to coexist peacefully.\"\n# OUTPUT: «Felix, Danielle, Lucinda and I try our best to coexist peacefully.␤»\n=end code\n\nHowever, C<\"@example.com\"> produces C<@example.com>.\n\nTo call a subroutine, use the C<&>-sigil and follow the subroutine name with parentheses.\nX<|Syntax,& (interpolation)>\n\n    say \"uc  'word'\";  # OUTPUT: «uc  'word'»␤\n    say \"&uc 'word'\";  # OUTPUT: «&uc 'word'»␤\n    say \"&uc('word')\"; # OUTPUT: «WORD»␤\n    # OUTPUT: «abcDEFghi␤»\n\nTo interpolate a Hash (or other L<C<Associative>|/type/Associative> variable), use\nthe C«<>» postcircumfix operator.\n\n    my %h = :1st; say \"abc%h<st>ghi\";\n    # OUTPUT: «abc1ghi␤»\n\nThe way C<qq> interpolates variables is the same as\nC<q:scalar:array:hash:function>.  You can use these adverbs (or their short\nforms, C<q:s:a:h:f>) to interpolate variables without enabling other C<qq>\ninterpolations.\n\n=head3 Interpolating closures\n\nAnother feature of C<qq> is the ability to interpolate Raku code from\nwithin the string, using curly braces:\n\n=begin code\nmy ($x, $y, $z) = 4, 3.5, 3;\nsay \"This room is {$x}m by {$y}m by {$z}m.\";               # OUTPUT: «This room is 4m by 3.5m by 3m.␤»\nsay \"Therefore its volume should be { $x * $y * $z }m³!\";  # OUTPUT: «Therefore its volume should be 42m³!␤»\n=end code\n\nThis provides the same functionality as the C<q:closure>/C<q:c> quoting form.\n\n=head3 Interpolating escape codes\n\nThe C<qq> quoting form also interpolates backslash escape sequences.  Several of\nthese print invisible/whitespace ASCII control codes or whitespace characters:\n\n=begin table\nSequence    Hex Value       Character            Reference URL\n\\0          \\x0000          Nul                  https://util.unicode.org/UnicodeJsps/character.jsp?a=0000\n\\a          \\x0007          Bel                  https://util.unicode.org/UnicodeJsps/character.jsp?a=0007\n\\b          \\x0008          Backspace            https://util.unicode.org/UnicodeJsps/character.jsp?a=0008\n\\e          \\x001B          Esc                  https://util.unicode.org/UnicodeJsps/character.jsp?a=001B\n\\f          \\x000C          Form Feed            https://util.unicode.org/UnicodeJsps/character.jsp?a=000C\n\\n          \\x000A          Newline              https://util.unicode.org/UnicodeJsps/character.jsp?a=000A\n\\r          \\x000D          Carriage Return      https://util.unicode.org/UnicodeJsps/character.jsp?a=000D\n\\t          \\x0009          Tab                  https://util.unicode.org/UnicodeJsps/character.jsp?a=0009\n=end table\n\nC<qq> also supports two multi-character escape sequences: C<\\x> and C<\\c>. You\ncan use C<\\x> or C<\\x[]> with the hex-code of a Unicode character or a list of\ncharacters:\n\n    my $s = \"I \\x2665 Raku!\";\n    say $s;\n    # OUTPUT: «I ♥ Raku!␤»\n\n    $s = \"I really \\x[2661,2665,2764,1f495] Raku!\";\n    say $s;\n    # OUTPUT: «I really ♡♥❤💕 Raku!␤»\n\nYou can also create a Unicode character with C<\\c> and that character's\nL«unicode name|/language/unicode#Entering_unicode_codepoints_and_codepoint_sequences»\n, L<named sequences|/language/unicode#Named_sequences>\nor L<name alias|/language/unicode#Name_aliases>:\n\n    my $s = \"Camelia \\c[BROKEN HEART] my \\c[HEAVY BLACK HEART]!\";\n    say $s;\n    # OUTPUT: «Camelia 💔 my ❤!␤»\n\nSee the description of\nL«\\c[]|/language/unicode#Entering_unicode_codepoints_and_codepoint_sequences» on\nthe L<Unicode|/language/unicode> documentation page for more details.\n\nC<qq> provides the same interpolation of escape sequences as that\nprovided by C<q:backslash>/C<q:b>.\n\n=head3 preventing interpolation and handling missing values\n\nYou can prevent any undesired interpolation in a\nC<qq>-quoted string by escaping the sigil or other initial character:\n\n=begin code :preamble<my $color = 'blue'>\nsay \"The \\$color variable contains the value '$color'\"; # OUTPUT: «The $color variable contains the value 'blue'␤»\n=end code\n\nInterpolation of undefined values will raise a control exception that can be\ncaught in the current block with\nL<CONTROL|/language/phasers#CONTROL>.\n\n=begin code\nsub niler {Nil};\nmy Str $a = niler;\nsay(\"$a.html\", \"sometext\");\nsay \"alive\"; # this line is dead code\nCONTROL { .die };\n=end code\n\nX<|Syntax,qw word quote>\n=head2 Word quoting: qw\n\n=for code\nqw|! @ # $ % ^ & * \\| < > | eqv '! @ # $ % ^ & * | < >'.words.list;\nq:w { [ ] \\{ \\} }           eqv ('[', ']', '{', '}');\nQ:w | [ ] { } |             eqv ('[', ']', '{', '}');\n\nThe C<:w> form, usually written as C<qw>, splits the string into\n\"words\". In this context, words are defined as sequences of non-whitespace\ncharacters separated by whitespace. The C<q:w> and C<qw> forms inherit the\ninterpolation and escape semantics of the C<q> and single quote string\ndelimiters, whereas C<Qw> and C<Q:w> inherit the non-escaping semantics of\nthe C<Q> quoter.\n\nThis form is used in preference to using many quotation marks and commas for\nlists of strings. For example, where you could write:\n\n    my @directions = 'left', 'right,', 'up', 'down';\n\nIt's easier to write and to read this:\n\n    my @directions = qw|left right up down|;\n\n=head2 Word quoting: C«< >»\nX«|Syntax,< > word quote»\n\n=for code\nsay <a b c> eqv ('a', 'b', 'c');   # OUTPUT: «True␤»\nsay <a b 42> eqv ('a', 'b', '42'); # OUTPUT: «False␤», the 42 became an IntStr allomorph\nsay < 42 > ~~ Int; # OUTPUT: «True␤»\nsay < 42 > ~~ Str; # OUTPUT: «True␤»\n\nThe angle brackets quoting is like C<qw>, but with extra feature that lets you\nconstruct L<allomorphs|/language/glossary#Allomorph> or literals\nof certain numbers:\n\n    say <42 4/2 1e6 1+1i abc>.raku;\n    # OUTPUT: «(IntStr.new(42, \"42\"), RatStr.new(2.0, \"4/2\"), NumStr.new(1000000e0, \"1e6\"), ComplexStr.new(<1+1i>, \"1+1i\"), \"abc\")␤»\n\nTo construct a L«C<Rat>|/type/Rat» or L«C<Complex>|/type/Complex» literal, use\nangle brackets around the number, without any extra spaces:\n\n    say <42/10>.^name;   # OUTPUT: «Rat␤»\n    say <1+42i>.^name;   # OUTPUT: «Complex␤»\n    say < 42/10 >.^name; # OUTPUT: «RatStr␤»\n    say < 1+42i >.^name; # OUTPUT: «ComplexStr␤»\n\nCompared to C<42/10> and C<1+42i>, there's no division (or addition) operation\ninvolved. This is useful for literals in routine signatures, for example:\n\n=begin code\nsub close-enough-π (<355/113>) {\n    say \"Your π is close enough!\"\n}\nclose-enough-π 710/226; # OUTPUT: «Your π is close enough!␤»\n=end code\n\n=begin code :skip-test<illustrates error>\n# WRONG: can't do this, since it's a division operation\nsub compilation-failure (355/113) {}\n=end code\n\n=head2 X<Word quoting with quote protection: qww|Syntax,qww>\n\nThe C<qw> form of word quoting will treat quote characters literally, leaving\nthem in the resulting words:\n\n    say qw{\"a b\" c}.raku; # OUTPUT: «(\"\\\"a\", \"b\\\"\", \"c\")␤»\n\nUsing the C<qww> variant allows you to use quote characters for embedding strings\nin the word quoting structure:\n\n    say qww{\"a b\" c}.raku; # OUTPUT: «(\"a b\", \"c\")␤»\n\nOther kinds of quotes are also supported with their usual semantics:\n\n    my $one = 'here';\n    my $other = 'there';\n    say qww{ ’this and that’ “$one or $other” ｢infinity and beyond｣ }.raku;\n    # OUTPUT: «(\"this and that\", \"here or there\", \"infinity and beyond\")␤»\n\nThe delimiters of embedded strings are always considered word splitters:\n\n    say qww{'alpha'beta'gamma' 'delta'\"epsilon\"}.raku; # OUTPUT: «(\"alpha\", \"beta\", \"gamma\", \"delta\", \"epsilon\")␤»\n\n=head2 X<Word quoting with interpolation: qqw|Syntax,qqw>\n\nThe C<qw> form of word quoting doesn't interpolate variables:\n\n    my $a = 42; say qw{$a b c};  # OUTPUT: «$a b c␤»\n\nThus, if you wish for variables to be interpolated within the quoted string,\nyou need to use the C<qqw> variant:\n\n    my $a = 42;\n    my @list = qqw{$a b c};\n    say @list;                # OUTPUT: «[42 b c]␤»\n\nNote that variable interpolation happens before word splitting:\n\n    my $a = \"a b\";\n    my @list = qqw{$a c};\n    .say for @list; # OUTPUT: «a␤b␤c␤»\n\n=head2 X<<<Word quoting with interpolation and quote protection: qqww|Syntax,qqww>>>\n\nThe C<qqw> form of word quoting will treat quote characters literally,\nleaving them in the resulting words:\n\n    my $a = 42; say qqw{\"$a b\" c}.raku;  # OUTPUT: «(\"\\\"42\", \"b\\\"\", \"c\")␤»\n\nUsing the C<qqww> variant allows you to use quote characters for embedding strings\nin the word quoting structure:\n\n    my $a = 42; say qqww{\"$a b\" c}.raku; # OUTPUT: «(\"42 b\", \"c\")␤»\n\nThe delimiters of embedded strings are always considered word splitters:\n\n    say qqww{'alpha'beta'gamma' 'delta'\"epsilon\"}.raku; # OUTPUT: «(\"alpha\", \"beta\", \"gamma\", \"delta\", \"epsilon\")␤»\n\nUnlike the C<qqw> form, interpolation also always splits (except for interpolation that takes place in an embedded string):\n\n    my $time = \"now\";\n    $_ = 'ni';\n    my @list = qqww<$time$time {6*7}{7*6} \"$_$_\">;\n    .say for @list; # OUTPUT: «now␤now␤42␤42␤nini␤»\n\nQuote protection happens before interpolation, and interpolation happens\nbefore word splitting, so quotes coming from inside interpolated variables are\njust literal quote characters:\n\n    my $a = \"1 2\";\n    say qqww{\"$a\" $a}.raku; # OUTPUT: «(\"1 2\", \"1\", \"2\")␤»\n    my $b = \"1 \\\"2 3\\\"\";\n    say qqww{\"$b\" $b}.raku; # OUTPUT: «(\"1 \\\"2 3\\\"\", \"1\", \"\\\"2\", \"3\\\"\")␤»\n\n=head2 X<<<Word quoting with interpolation and quote protection: « »|Syntax,<< >>>>>\n\nX<<<|Syntax,« »>>>\nThis style of quoting is like C<qqww>, but with the added benefit of\nconstructing L<allomorphs|/language/glossary#Allomorph> (making it\nfunctionally equivalent to L<qq:ww:v|#index-entry-:val_(quoting_adverb)>). The\nASCII equivalent to C<« »> are double angle brackets C«<< >>».\n\n    # Allomorph Construction\n    my $a = 42; say «  $a b c    ».raku;  # OUTPUT: «(IntStr.new(42, \"42\"), \"b\", \"c\")␤»\n    my $a = 42; say << $a b c   >>.raku;  # OUTPUT: «(IntStr.new(42, \"42\"), \"b\", \"c\")␤»\n\n    # Quote Protection\n    my $a = 42; say «  \"$a b\" c  ».raku;  # OUTPUT: «(\"42 b\", \"c\")␤»\n    my $a = 42; say << \"$a b\" c >>.raku;  # OUTPUT: «(\"42 b\", \"c\")␤»\n\n=head2 X<Shell quoting: qx|Syntax,qx>\n\nTo run a string as an external program, not only is it possible to pass the\nstring to the C<shell> or C<run> functions but one can also perform shell\nquoting. There are some subtleties to consider, however. C<qx> quotes\nI<don't> interpolate variables. Thus\n\n    my $world = \"there\";\n    say qx{echo \"hello $world\"}\n\nprints simply C<hello>. Nevertheless, if you have declared an environment\nvariable before calling C<raku>, this will be available within C<qx>, for\ninstance\n\n=begin code :skip-test<REPL>\nWORLD=\"there\" raku\n> say qx{echo \"hello $WORLD\"}\n=end code\n\nwill now print C<hello there>.\n\nThe result of calling C<qx> is returned, so this information can be assigned\nto a variable for later use:\n\n    my $output = qx{echo \"hello!\"};\n    say $output;    # OUTPUT: «hello!␤»\n\nSee also L<shell|/routine/shell>, L<run|/routine/run> and\nL<C<Proc::Async>|/type/Proc::Async> for other ways to execute external commands.\n\n=head2 X<Shell quoting with interpolation: qqx|Syntax,qqx>\n\nIf one wishes to use the content of a Raku variable within an external\ncommand, then the C<qqx> shell quoting construct should be used:\n\n    my $world = \"there\";\n    say qqx{echo \"hello $world\"};  # OUTPUT: «hello there␤»\n\nAgain, the output of the external command can be kept in a variable:\n\n    my $word = \"cool\";\n    my $option = \"-i\";\n    my $file = \"/usr/share/dict/words\";\n    my $output = qqx{grep $option $word $file};\n    # runs the command: grep -i cool /usr/share/dict/words\n    say $output;      # OUTPUT: «Cooley␤Cooley's␤Coolidge␤Coolidge's␤cool␤...»\n\nBe aware of the content of the Raku variable used within an external command; malicious content can be used to execute arbitrary code. See L<C<qqx> traps|/language/traps#Beware_of_variables_used_within_qqx>\n\nSee also L<run|/routine/run> and L<C<Proc::Async>|/type/Proc::Async> for\nbetter ways to execute external commands.\n\n=head2 X<Heredocs: :to|Syntax,heredocs :to>\n\nA convenient way to write a multi-line string literal is by using a I<heredoc>, which\nlets you choose the delimiter yourself:\n\n=begin code\nsay q:to/END/;\nHere is\nsome multi-line\nstring\nEND\n=end code\n\nThe contents of the I<heredoc> always begin on the next line, so you can (and\nshould) finish the line.\n\n=begin code :preamble<sub my-escaping-function { $^x }>\nmy $escaped = my-escaping-function(q:to/TERMINATOR/, language => 'html');\nHere are the contents of the heredoc.\nPotentially multiple lines.\nTERMINATOR\n=end code\n\nIf the terminator is indented, that amount of indention is removed from the\nstring literals. Therefore this I<heredoc>\n\n=begin code\nsay q:to/END/;\n    Here is\n    some multi line\n        string\n    END\n=end code\n\nproduces this output:\n\n=begin code :lang<text>\nHere is\nsome multi line\n    string\n=end code\n\nI<Heredocs> include the newline from before the terminator.\nA common idiom to remove it is to put a L<C<chomp>|/type/Str#routine_chomp> at the beginning, for example:\n\n=begin code\nmy $s = chomp q:to/END/;\nThe result will have\nno final newline.\nEND\n=end code\n\nTo allow interpolation of variables use the L<C<qq>|/language/quoting#Interpolation:_qq> form. For example:\n\n  my $f = 'db.7.3.8';\n  my $s = qq:to/END/;\n  option \\{\n      file \"$f\";\n  };\n  END\n  say $s;\n\nwould produce:\n\n=begin code :lang<text>\noption {\n    file \"db.7.3.8\";\n};\n=end code\n\nSome other situations to pay attention to are innocent-looking ones\nwhere the text looks like a Raku expression. For example, the\nfollowing generates an error:\n\n=begin code :lang<text>\nmy $title = 'USAFA Class of 1965';\nsay qq:to/HERE/;\n<a href='https://usafa-1965.org'>$title</a>\nHERE\n# Output:\nType Str does not support associative indexing.\n  in block <unit> at here.raku line 2\n=end code\n\nThe angle bracket to the right of '$title' makes it look like a hash index\nto Raku when it is actually a L<C<Str>|/type/Str> variable, hence the error message.\nOne solution is to enclose the scalar with curly braces which is one\nway to enter an expression in any interpolating quoting construct:\n\n=begin code :lang<text>\nsay qq:to/HERE/;\n<a href='https://usafa-1965.org'>{$title}</a>\nHERE\n=end code\n\nAnother option is to escape the `<` character to avoid it being parsed\nas the beginning of an indexing operator:\n\n=begin code :lang<text>\nsay qq:to/HERE/;\n<a href='https://usafa-1965.org'>$title\\</a>\nHERE\n=end code\n\nBecause a I<heredoc> can be very long but is still interpreted by Raku\nas a single line, finding the source of an error can sometimes be\ndifficult. One crude way to debug the error is by starting with the\nfirst visible line in the code and treating is as a I<heredoc> with\nthat line only. Then, until you get an error, add each line in turn.\n(Creating a Raku program to do that is left as an exercise for the\nreader.)\n\nYou can begin multiple Heredocs in the same line. If you do so, the\nsecond heredoc will not start until after the first heredoc has\nended.\n\n=begin code\nmy ($first, $second) = qq:to/END1/, qq:to/END2/;\n  FIRST\n  MULTILINE\n  STRING\n  END1\n   SECOND\n   MULTILINE\n   STRING\n   END2\nsay $first;  # OUTPUT: «FIRST␤MULTILINE␤STRING␤»\nsay $second; # OUTPUT: «SECOND␤MULTILINE␤STRING␤»\n=end code\n\n=head2 X<Unquoting|Language,Unquoting>\n\nLiteral strings permit interpolation of embedded quoting constructs by using the\nescape sequences such as these:\n\n    my $animal=\"quaggas\";\n    say 'These animals look like \\qq[$animal]'; # OUTPUT: «These animals look like quaggas␤»\n    say 'These animals are \\qqw[$animal or zebras]'; # OUTPUT: «These animals are quaggas or zebras␤»\n\nIn this example, C<\\qq> will do double-quoting interpolation, and C<\\qqw> word\nquoting with interpolation. Escaping any other quoting construct as above will\nact in the same way, allowing interpolation in literal strings.\n\n\n=end pod\n"
  },
  {
    "path": "doc/Language/rb-nutshell.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"migration\")\n\n=TITLE Ruby to Raku - nutshell\n\n=SUBTITLE Learning Raku from Ruby, in a nutshell: what do I already know?\n\nThis page attempts to index the high-level differences in syntax and semantics\nbetween Ruby and Raku. Whatever works in Ruby and must be written differently\nin Raku should be listed here (whereas many Raku features and idioms won't\nbe).\n\nHence this should not be mistaken for a beginner tutorial or overview of Raku; it is intended as a technical reference for Raku learners with a strong\nRuby background.\n\n\n=head1 Basic syntax\n\n=head2 Statement ending semicolons\n\nRuby detects the end of most statements with a newline (and a few exceptions),\nas long as the expression is complete. It is common break up a long expression\nby leaving an operator dangling at the end of a line to ensure that the parsing\nwill continue:\n\n=for code :lang<ruby>\nfoo +     # In Ruby a trailing operator means parsing should continue\n  bar +\n  baz\n\nIn Raku you must explicitly terminate statements with a C<;>, which allows\nfor better feedback and more flexibility in breaking up long lines. Two\nexceptions not needing an explicit C<;> are the last statement in a block, and\nafter the closing curly brace of the block itself (if there is nothing else on\nthat line):\n\n    my $x;\n    ...;\n    if 5 < $x < 10 {\n      say \"Yep!\";\n      $x = 17         # No ; required before closing }\n    }                 # No ; required after closing } because of the newline\n    say \"Done!\";      # The ; is not required here if nothing follows\n\n=head2 Whitespace\n\nRuby allows a surprising amount of flexibility in the use of whitespace,\neven with strict mode and warnings turned on:\n\n=for code :lang<ruby>\n# unidiomatic but valid Ruby\nputs\"Hello \"+\n(people [ i]\n    . name\n    ) . upcase+\"!\"if$greeted[i]<1\n\nRaku also endorses programmer freedom and creativity, but balanced syntactic\nflexibility against its design goal of having a consistent, deterministic,\nextensible grammar that supports single-pass parsing and helpful error\nmessages, integrates features like custom operators cleanly, and doesn't lead\nprogrammers to accidentally misstate their intent. Also, the practice of \"code\ngolf\" is slightly de-emphasized; Raku is designed to be more concise in\nconcepts than in keystrokes.\n\nAs a result, there are various places in the syntax where whitespace is\noptional in Ruby, but is either mandatory or forbidden in Raku. Many of those\nrestrictions are unlikely to concern much real-life Perl code (e.g. whitespace\nbeing disallowed between an array variable and its square brackets), but there\nare a few that will unfortunately conflict with some Ruby hackers' habitual\ncoding styles:\n\n=begin item\nI<No space allowed before the opening parenthesis of an argument list.>\n\n=begin code :skip-test<illustrates error>\nfoo (3, 4, 1); # Not right in Ruby or Raku (in Raku this would\n               # try to pass a single argument of type List to foo)\n=end code\n\n=for code :preamble<sub foo($,$,$) {...}>\nfoo(3, 4, 1);  # Ruby and Raku\nfoo 3, 4, 1;   # Ruby and Raku - alternative parentheses-less style\n\n=end item\n\n=begin item\nI<Space is B<required> immediately after keywords>\n=end item\n\n=begin code :lang<ruby>\nif(a < 0); ...; end         # OK in Ruby\n=end code\n=begin code\nmy $a; ...;\nif ($a < 0) { ... }         # Raku\nif $a < 0 { ... }           # Raku, more idiomatic\n=end code\n\n=begin code :lang<ruby>\nwhile(x > 5); ...; end      # OK in Ruby\n=end code\n=begin code\nmy $x; ...;\nwhile ($x > 5) { ... }      # Raku\nwhile $x > 5 { ... }        # Raku, more idiomatic\n=end code\n\n\n=begin item\nI<No space allowed before a postfix/postcircumfix operator (including\narray/hash subscripts).>\n\n=for code :lang<ruby>\nseen [ :fish ] = 1    # Ruby, not idiomatic but allowed\n\n=for code :preamble<my %seen>\n%seen< fish > = 1;    # Raku, no space allowed after 'seen'\n=end item\n\n=begin item\nI<Space required before an infix operator if it would\nconflict with an existing postfix/postcircumfix operator.>\n\n=for code :lang<ruby>\nn<1     # Ruby (in Raku this would conflict with postcircumfix < >)\n=for code :preamble<my $n>\n$n < 1; # Raku\n\n=end item\n\n=head2 C«.» Method calls, C<.public_send>\n\nMethod call syntax uses a dot just like Ruby:\n\n=for code :lang<ruby>\nperson.name    # Ruby\n=for code\nmy $person; ...;\n$person.name   # Raku\n\nTo call a method whose name is not known until runtime:\n\n=for code :lang<ruby>\nobject.public_send(methodname, args);  # Ruby\n=for code\nmy $object; my Str $methodname; my @args; ...;\n$object.\"$methodname\"(@args);   # Raku\n\nIf you leave out the quotes, then Raku expects C<$methodname> to contain\na L<C<Method>|/type/Method> object, rather than the simple string name of the method.\n\n=head2 Variables, sigils, scope, and common types\n\nIn Ruby, variables use sigils primarily to indicate scope. C<$> for global\nscope, C<@@> for class scope, C<@> for instance scope, and no sigil for local\nvariables (including parameters). The C<&> sigil is also used to indicate\nmethod references. Symbols are prefixed with C<:>, but they are not variable\nand so not really sigils.\n\nIn Raku sigils are primarily used to indicate a role that the contained value\nimplements, indicating the type (or at least the interface) of the value. The\nsigils are invariant, no matter how the variable is being used - you can think\nof them as part of the variable's name.\n\nThe scope of a variable is instead indicated by the declaration itself (C<my>,\nC<has>, C<our>, etc).\n\n=head3 Variable scope\n\nFor local variables, Ruby uses implicit variable declaration upon assignment\nand limited to the current block. In Ruby the content of an C<if> or C<while>\nbuilt-in construct is not a block or scope.\n\nRaku uses explicit scope indicators, and never creates variables implicitly.\nEvery place you see C<{ ... }> is a scope, including the body of a conditional\nor loop. The commonly used scope declarations:\n\n=for code :lang<ruby>\nfoo = 7        # Ruby, variable scope is defined by first assignment and\n               # extends to the end of the current block\n\n=for code\nmy  $foo = 7;   # Raku, lexical scoped to the current block\nour $foo = 7;   # Raku, package scoped\nhas $!foo = 7;  # Raku, instance scoped (attribute)\n\n=head3 C<$> Scalar\n\nThe C<$> sigil is always used with \"scalar\" variables (e.g. C<$name>). These\nare single-value containers.\n\nThis is the most general-purpose variable type, with no restrictions on its\ncontents. Note that you can still address/use its contents, like C<$x[1]>,\nC<$x{\"foo\"}>, and C<$f(\"foo\")>.\n\n=head3 C<@> Array\n\nThe C<@> sigil is always used with \"array\" variables (e.g. C<@months>,\nC<@months[2]>, C<@months[2, 4]> for an array slice). Variables using the C<@>\nsigil can only contain things that do the L<C<Positional>|/type/Positional> role, indicating\npositional indexing and slicing capabilities.\n\n=begin item\nI<Indexing>\n\n=for code :lang<ruby>\nputs months[2]; # Ruby\n=for code :preamble<my @months>\nsay @months[2]; # Raku\n=end item\n\n=begin item\nI<Value-slicing>\n\n=for code :lang<ruby>\nputs months[8..11].join(',') # Ruby\n=for code :preamble<my @months>\nsay @months[8..11].join(',') # Raku\n=end item\n\n\n=head3 C<%> Hash\n\nThe C<%> sigil is always used with \"hash\" variables (e.g. C<%calories>,\nC<%calories<apple>>, C<%calories<pear plum>>). Variables using the C<%> sigil\ncan only contain things that do the L<C<Associative>|/type/Associative> role.\n\nRuby uses square brackets to access values for both Arrays and Hashes. Raku\nuses curly braces for hashes instead. The angle brackets version is available\nwhich always autoquotes its contents (strings without quotes):\n\nAdverbs can be used to control the type of slice.\n\n=begin item\nI<Indexing>\n\n=for code :lang<ruby>\nputs calories[\"apple\"]  # Ruby\n=for code :preamble<my %calories>\nsay %calories{\"apple\"}; # Raku\n\n=for code :lang<ruby>\nputs calories[\"apple\"]  # Ruby\nputs calories[:apple]   # Ruby, symbols for keys are common\n=for code :preamble<my %calories; my $key>\nsay %calories<apple>;   # Raku - angle brackets instead of single-quotes\nsay %calories«\"$key\"»;  # Raku - double angles interpolate as double-quotes\n=end item\n\n=begin item\nI<Value-slicing>\n\n=for code :lang<ruby>\nputs calories.values_at('pear', 'plum').join(',') # Ruby\nputs calories.values_at(%w(pear plum)).join(',')  # Ruby, pretty?\n=for code :preamble<my %calories; my $keys>\nsay %calories{'pear', 'plum'}.join(',');          # Raku\nsay %calories<pear plum>.join(',');               # Raku (prettier)\nmy $keys = 'pear plum';\nsay %calories« $keys ».join(','); # Raku, interpolated split\n=end item\n\n=begin item\nI<Key/value-slicing>\n\n=for code :lang<ruby>\nputs calories.slice('pear', 'plum')  # Ruby >= 2.5\n=for code :preamble<my %calories>\nsay %calories{'pear', 'plum'}:kv.Hash;   # Raku - use :kv adverb\nsay %calories<pear plum>:kv.Hash;        # Raku (prettier version)\n=end item\n\n=head3 C<&> Sub\n\nThe C<&> sigil is used very similarly to Ruby's C<&> to refer to the function\nobject of a named subroutine/operator without invoking it, i.e. to use the name\nas a \"noun\" instead of a \"verb\". Variables using the C<&> sigil can only\ncontain things that do the L<C<Callable>|/type/Callable> role.\n\n=begin code :lang<ruby>\nadd = -> n, m { n + m } # Ruby lambda for an addition function\nadd.(2, 3)              # => 5, Ruby invocation of a lambda\nadd.call(2, 3)          # => 5, Ruby invocation of a lambda\n=end code\n\n=begin code\nmy &add = -> $n, $m { $n + $m }; # Raku addition function\n&add(2, 3);                      # => 5, you can keep the sigil\nadd(2, 3);                       # => 5, and it works without it\n=end code\n\n=for code :lang<ruby>\ndef foo\n  ...\nend\nfoo_method = method(:foo);     # Ruby\n=for code\nsub foo { ... };\nmy &foo_method = &foo; # Raku\n\n=for code :lang<ruby>\nsome_func(&say) # Ruby pass a function reference\n=for code\nsub some_func { ... };\nsome_func(&say) # Raku passes function references the same way\n\nOften in Ruby we pass a block as the last parameter, which is especially used\nfor DSLs. This can be an implicit parameter called by C<yield>, or an explicit\nblock prefixed with C<&>. In Raku a L<C<Callable>|/type/Callable> parameter is always listed\nand called by the variable name (instead of yield), and there are a variety of\nways of invoking the function.\n\n=begin code :lang<ruby>\n# Ruby, declare a method and call the implicit block argument\ndef f\n  yield 2\nend\n\n# Ruby, invoke f, pass it a block with 1 argument\nf do |n|\n  puts \"Hi #{n}\"\nend\n=end code\n\n=begin code\n# Raku, declare a method with an explicit block argument\nsub f(&g:($)) {\n  g(2)\n}\n\n# Raku, invoke f, pass it a block with 1 argument\n# There are several other ways to do this\nf(-> $n { say \"Hi {$n}\" }); # Explicit argument\nf -> $n { say \"Hi {$n}\" };  # Explicit argument, no parenthesis\n\n# Additionally, if 'f' is a method on instance 'obj' you can use ':'\n# instead of parenthesis\nmy $obj; ...;\n$obj.f(-> $n { say \"Hi {$n}\" });  # Explicit argument\n$obj.f: -> $n { say \"Hi {$n}\" };  # Explicit argument, no parenthesis\n=end code\n\n=head3 C<*> Slurpy params / argument expansion\n\nIn Ruby you can declare an argument to slurp the remainder of the passed\nparameters into an array using a C<*> prefix. It works similarly in Raku:\n\n=for code :lang<ruby>\ndef foo(*args); puts \"I got #{args.length} args!\"; end # Ruby\n=for code\nsub foo(*@args) { say \"I got #{@args.elems} args!\" }   # Raku\n\nThe Raku version above is slightly different in that when it slurps in the\narguments into @args, one level of nesting, if any, is automatically removed:\n\n=for code\nsub foo(*@args) { say @args.raku }\nfoo([1, [2, 3], 4], 5, [6, 7]);   # [1, [2, 3], 4, 5, 6, 7]\n\nTo preserve the structure of the arguments, you can use C<**>:\n\n=for code\nsub foo(**@args) { say @args.raku }\nfoo([1, [2, 3], 4], 5, [6, 7]);  # [[1, [2, 3], 4], 5, [6, 7]]\n\nYou might want to expand an array into a set of arguments. In Raku this is\ndone using a L<C<Slip>|/type/Slip> C<|>:\n\n=for code :lang<ruby>\nargs = %w(a b c)         # Ruby\nfoo(*args)\n\n=for code\nsub foo($q, $r, $s) { ... };\nmy @args = <a b c>;       # Raku\nfoo(|@args);\n\nRaku has many more advanced ways of passing parameters and receiving\narguments, see L<Signatures|/language/functions#Signatures> and\nL<Captures|/type/Capture>.\n\n=head2 Twigils\n\nRaku additionally uses \"twigils\", which are further indicators about the\nvariable and go between the sigil and the rest of the variable name. Examples:\n\n=begin table\nVariable | Description\n=========|============\n$foo     | Scalar with no twigil\n$!foo    | Private instance variable\n$.foo    | Instance variable accessor\n$*foo    | Dynamically scoped variable\n$^foo    | A positional (placeholder) parameter to a block\n$:foo    | A named (placeholder) parameter to a block\n$=foo    | POD (documentation) variables\n$?FILE   | Current source filename. The ? twigil indicates a compile-time value\n$~foo    | Sublanguage seen by parser, uncommon\n=end table\n\nThough each of these examples use the C<$> sigil, most could use C<@>\n(Positional) or C<%> (Associative).\n\n=head2 C<:> Symbols\n\nRaku generally uses strings in the places where Ruby uses symbols. A primary\nexample of this is in hash keys.\n\n=for code :lang<ruby>\naddress[:joe][:street] # Typical Ruby nested hash with symbol keys\n=for code\nmy %address; ...;\n%address<joe><street>  # Typical Raku nested hash with string keys\n\nRaku has I<colon-pair> syntax, which can sometimes look like Ruby symbols.\n\n=for code :lang<ruby>\n:age            # Ruby symbol\n\n=begin code\n# All of these are equivalent for Raku\n:age            ;# Raku pair with implicit True value\n:age(True)      ;# Raku pair with explicit True value\nage => True     ;# Raku pair using arrow notation\n\"age\" => True   ;# Raku pair using arrow notation and explicit quotes\n=end code\n\nYou could probably get away with using a colon-pair without an explicit value\nand pretend that it is a Ruby symbol a lot of the time, but it isn't idiomatic\nRaku.\n\n=head1 Operators\n\nMany operators have a similar usage in both Ruby and Raku:\n\n=item C<,> List Separator\n=item C<+> Numeric Addition\n=item C<-> Numeric Subtraction\n=item C<*> Numeric Multiplication\n=item C</> Numeric Division\n=item C<%> Numeric Modulus\n=item C<**> Numeric Exponentiation\n=item C<! && ||> Booleans, high-precedence\n=item C<not and or> Booleans, low-precedence\n\nYou may use C<$x++> instead of C<x += 1> as a shortcut for incrementing a\nvariable. This can be used as a pre-increment C<++$x> (increment, return new\nvalue) or post-increment C<$x++> (increment, return old value).\n\nYou may use C<$x--> instead of C<x -= 1> as a shortcut for decrementing a\nvariable. This can be used as a pre-decrement C<--$x> (decrement, return new\nvalue) or post-decrement C<$x--> (decrement, return old value).\n\n=head2 C«== != < > <= >=» Comparisons\n\nComparisons in Raku are separated between numeric and string to avoid common\nerrors.\n\n=item C«== != < > <= >=» Comparisons\n=item C<eq ne lt gt le ge> String comparisons\n\nFor example, using C<==> tries to convert the values to numbers, and C<eq>\ntries to convert the values to strings.\n\n=head2 C«<=>» Three-way comparisons\n\nIn Ruby, the C«<=>» operator returns -1, 0, or 1.\nIn Raku, they return C<Order::Less>, C<Order::Same>, or C<Order::More>.\n\nC«<=>» forces numeric context for the comparison.\n\nC«leg» (\"Less, Equal, or Greater?\") forces string context for the comparison.\n\nC«cmp» does either C«<=>» or C<leg>, depending on the existing type of its\narguments.\n\n=head2 C<~~> Smartmatch operator\n\nThis is a very common matching operator which is similar to C<===> in Ruby. Here are\nsome examples:\n\n    my $foo; ...;\n    say \"match!\" if $foo ~~ /bar/;       # Regex match\n    say \"match!\" if $foo ~~ \"bar\";       # String match\n    say \"match!\" if $foo ~~ :(Int, Str); # Signature match (destructure)\n\nAn equivalent in Ruby would be\n\n=for code :lang<ruby>\nfoo = \"bar\"\nputs \"match 1!\" if /bar/ === foo       # Regex match\nputs \"match 2!\" if foo === \"bar\"       # String match\nputs \"match 3!\" if String === foo      # Class match\n\nPlease note that, in this case, C<===> is not symmetric; in the first\nand last case, the variable has to be in the right-hand side. There is\nno equivalent to the signature class in Ruby, either.\n\nSee L<S03/Smartmatching|https://github.com/Raku/old-design-docs/blob/master/S03-operators.pod#Smart_matching> for more information on this feature.\n\n=head2 C<& | ^> Numeric bitwise ops\n=head2 C<& | ^> Boolean ops\n\nIn Raku, these single-character ops have been removed, and replaced by\ntwo-character ops which coerce their arguments to the needed context.\n\n=begin code :lang<text>\n# Infix ops (two arguments; one on each side of the op)\n+&  +|  +^  And Or Xor: Numeric\n~&  ~|  ~^  And Or Xor: String\n?&  ?|  ?^  And Or Xor: Boolean\n\n# Prefix ops (one argument, after the op)\n+^  Not: Numeric\n~^  Not: String\n?^  Not: Boolean (same as the ! op)\n=end code\n\n=head2 C<&.> Conditional chaining operator\n\nRuby uses the C<&.> operator to chain methods without raising an error if one\ninvocation returns nil. In Raku use C<.?> for the same purpose.\n\n=head2 C«<< >>» Numeric shift left, right ops, shovel operator\n\nReplaced by C«+<» and C«+>» .\n\n=for code :lang<ruby>\nputs 42 << 3  # Ruby\n=for code\nsay  42 +< 3; # Raku\n\nNote that Ruby often uses the C«<<» operator as the \"shovel operator\", which is\nsimilar to C<.push>. This usage isn't common in Raku.\n\n=head2 C«=>» and C<:> Key-value separators\n\nIn Ruby, C«=>» is used in the context of key/value pairs for Hash literal\ndeclaration and parameter passing. C<:> is used as a shorthand when the left\nside is a symbol.\n\nIn Raku, C«=>» is the Pair operator, which is quite different in\nprinciple, but works the same in many situations.\n\nIf you are using C«=>» in a hash literal, then the usage is very similar:\n\n=for code :lang<ruby>\nhash = { \"AAA\" => 1, \"BBB\" => 2 }  # Ruby, though symbol keys are more common\n=for code\nmy %hash = ( AAA => 1, BBB => 2 ); # Raku, uses ()'s though {} usually work\n\n=head2 C<? :> Ternary operator\n\nIn Raku, this is spelled with two question marks instead of one question\nmark, and two exclamation points instead of one colon. This deviation from the\ncommon ternary operators disambiguates several situations and makes the\nfalse-case stand out more.\n\n=for code :lang<ruby>\nresult     = (  score > 60 )  ? 'Pass'  : 'Fail'; # Ruby\n=for code\nmy $score; ...;\nmy $result = ( $score > 60 ) ?? 'Pass' !! 'Fail'; # Raku\n\n=head2 C<+> String concatenation\n\nReplaced by the tilde. Mnemonic: think of \"stitching\" together the two strings with needle and thread.\n\n=for code :lang<ruby>\n$food = 'grape' + 'fruit'  # Ruby\n=for code\nmy $food = 'grape' ~ 'fruit'; # Raku\n\n=head2 String interpolation\n\nIn Ruby, C<\"#{foo}s\"> deliminates a block embedded in a double-quoted string.\nIn Raku drop the C<#> prefix: C<\"{$foo}s\">. As in Ruby, you can place\narbitrary code into the embedded block and it will be rendered in string\ncontext.\n\nSimple variables can be interpolated into a double-quoted string without using the block syntax:\n\n=begin code :lang<ruby>\n# Ruby\nname = \"Bob\"\nputs \"Hello! My name is #{name}!\"\n=end code\n\n=begin code :lang<ruby>\n# Raku\nmy $name = \"Bob\";\nsay \"Hello! My name is $name!\"\n=end code\n\nThe result of an embedded block in Ruby uses C<.to_s> to get string context.\nRaku uses C<.Str>, or C<.gist> for the same affect.\n\n=head1 Compound statements\n\n=head2 Conditionals\n\n=head3 C<if> C<elsif> C<else> C<unless>\n\nThis work very similarly between Ruby and Raku, but Raku uses C<{ }> to\nclearly delineate the blocks.\n\n=begin code :lang<ruby>\n# Ruby\nif x > 5\n    puts \"Bigger!\"\nelsif x == 5\n    puts \"The same!\"\nelse\n    puts \"Smaller!\"\nend\n=end code\n\n=begin code\n# Raku\nmy $x; ...;\nif $x > 5 {\n    say \"Bigger!\"\n} elsif $x == 5 {\n    say \"The same!\"\n} else {\n    say \"Smaller!\"\n}\n=end code\n\nBinding the conditional expression to a variable is a little different:\n\n=for code :lang<ruby>\nif x = dostuff(); ...; end   # Ruby\n=for code\nsub dostuff() {...};\nif dostuff() -> $x {...}     # Raku, block-assignment uses arrow\n\nThe C<unless> conditional only allows for a single block in Raku;\nit does not allow for an C<elsif> or C<else> clause.\n\n=head3 C<case>-C<when>\n\nThe Raku C<given>-C<when> construct is like a chain of C<if>-C<elsif>-C<else>\nstatements, and its direct analog is Ruby's C<case>-C<when> construct.\nJust as Ruby uses the C<===> (case equality) operator for each condition in a\nC<case>-C<when> expression, Raku, likewise, uses the smartmatch C<~~> operator\nwith C<given>-C<when>.\n\nIt has the\ngeneral structure:\n\n=begin code :lang<pseudo>\ngiven EXPR {\n    when EXPR { ... }\n    when EXPR { ... }\n    default { ... }\n}\n=end code\n\nIn its simplest form, the construct is as follows:\n\n    my $value; ...;\n    given $value {\n        when \"a match\" {\n            # do-something();\n        }\n        when \"another match\" {\n            # do-something-else();\n        }\n        default {\n            # do-default-thing();\n        }\n    }\n\nThis is simple in the sense that a scalar value is matched in the C<when>\nstatements. More generally, the matches are actually smartmatches on the\ninput value such that lookups using more complex entities such as regexps\ncan be used instead of scalar values.\n\n=head2 Loops\n\n=head3 C<while> C<until>\n\nMostly unchanged; parentheses around the conditions are optional, but if used, must\nnot immediately follow the keyword, or it will be taken as a function call\ninstead. Binding the conditional expression to a variable is also a little\ndifferent:\n\n=for code :lang<ruby>\nwhile x = dostuff(); ...; end    # Ruby\n=for code\nsub dostuff {...}; ...;\nwhile dostuff() -> $x {...}      # Raku\n\n=head3 C<for> C<.each>\n\nC<for> loops are rare in Ruby, instead we typically use C<.each> on an\nenumerable. The most direct translation to Raku would be to use C<.map> for\nboth C<.each> and C<.map>, but we typically use a C<for> loop directly.\n\n=begin code :lang<ruby>\n# Ruby for loop\nfor n in 0..5\n    puts \"n: #{n}\"\nend\n\n# Ruby, more common usage of .each\n(0..5).each do |n|\n    puts \"n: #{n}\"\nend\n=end code\n\n=begin code\n# Raku\nfor 0..5 -> $n {\n    say \"n: $n\";\n}\n\n# Raku, misusing .map\n(0..5).map: -> $n {\n    say \"n: $n\";\n}\n=end code\n\nIn Ruby, the iteration variable for C<.each> is a copy of the list element, and\nmodifying it does nothing to the original list. Note that it is a copy of the\nREFERENCE, so you can still change the values to which it refers.\n\nIn Raku, that alias is read-only (for safety) and thus behaves exactly like\nRuby, unless you change C«->» to C«<->».\n\n=for code :lang<ruby>\ncars.each { |car| ... }    # Ruby; read-only reference\n=for code\nmy @cars; ...;\nfor @cars  -> $car   {...} # Raku; read-only\nfor @cars <-> $car   {...} # Raku; read-write\n\n=head2 Flow interruption statements\n\nSame as Ruby:\n\n=item C<next>\n=item C<redo>\n\nRuby's C<break> is C<last> in Raku.\n\n=head1 Regular expressions ( regex / regexp )\n\nRegular expressions in Raku are significantly different, and more powerful,\nthan in Ruby. By default whitespace is ignored and all characters must be\nescaped, for example. Regexes can be easily combined and declared in ways to\nbuild efficient grammars.\n\nThere are many powerful features of Raku regexes, especially defining entire\ngrammars using the same syntax. See L<Regexes|/language/regexes> and\nL<Grammars|/language/grammars>.\n\n=head2 C<.match> method and C<=~> operator\n\nIn Ruby, regex matches can be done against a variable using the C<=~> regexp\nmatch operator or the C<.match> method. In Raku, the C<~~> smartmatch op is\nused instead, or the C<.match> method.\n\n=for code :lang<ruby>\nnext if line   =~ /static/   # Ruby\nnext if line  !~  /dynamic/; # Ruby\nnext if line.match(/static/) # Ruby\n\n=for code\nmy $line; ...;\nnext if $line  ~~ /static/;    # Raku\nnext if $line !~~ /dynamic/ ;  # Raku\nnext if $line.match(/static/); # Raku\n\nAlternately, the C<.match> and C<.subst> methods can be used. Note that\nC<.subst> is non-mutating. See\nL<S05/Substitution|https://github.com/Raku/old-design-docs/blob/master/S05-regex.pod#Substitution>.\n\n=head2 C<.sub> and C<.sub!>\n\nIn Raku you typically use the C<s///> operator to do regex substitution.\n\n=for code :lang<ruby>\nfixed = line.sub(/foo/, 'bar')        # Ruby, non-mutating\n=for code\nmy $line; ...;\nmy $fixed = $line.subst(/foo/, 'bar') # Raku, non-mutating\n\n=for code :lang<ruby>\nline.sub!(/foo/, 'bar')   # Ruby, mutating\n=for code\nmy $line; ...;\n$line ~~ s/foo/bar/;      # Raku, mutating\n\n=head2 Regex options\n\nMove any options from the end of the regex to the beginning. This may\nrequire you to add the optional C<m> on a plain match like C«/abc/».\n\n=for code :lang<ruby>\nnext if $line =~    /static/i # Ruby\n=for code\nmy $line; ...;\nnext if $line ~~ m:i/static/; # Raku\n\n=head2 Whitespace is ignored, most things must be quoted\n\nIn order to aid in readability and reusability, whitespace is not significant\nin Raku regexes.\n\n=for code :lang<ruby>\n/this is a test/ # Ruby, boring string\n/this.*/         # Ruby, possibly interesting string\n\n=for code\n/ this \" \" is \" \" a \" \" test /; # Raku, each space is quoted\n/ \"this is a test\" /;           # Raku, quoting the whole string\n/ this .* /;                    # Raku, possibly interesting string\n\n=head2 Special matchers generally fall under the C«<>» syntax\n\nThere are many cases of special matching syntax that Raku regexes support.\nThey won't all be listed here, but often instead of being surrounded by C<()>,\nthe assertions will be surrounded by C«<>».\n\nFor character classes, this means that:\n\n=item C<[abc]> becomes C«<[abc]>»\n\n=item C<[^abc]> becomes C«<-[abc]>»\n\n=item C<[a-zA-Z]> becomes C«<[a..zA..Z]>»\n\n=item C<[[:upper:]]> becomes C«<:upper>»\n\n=item C<[abc[:upper:]]> becomes C«<[abc]+:Upper>»\n\nFor look-around assertions:\n\n=item C<(?=[abc])> becomes C«<?[abc]>»\n\n=item C<(?=ar?bitrary* pattern)> becomes C«<before ar?bitrary* pattern>»\n\n=item C<(?!=[abc])> becomes C«<![abc]>»\n\n=item C<(?!=ar?bitrary* pattern)> becomes C«<!before ar?bitrary* pattern>»\n\n=item C«(?<=ar?bitrary* pattern)» becomes C«<after ar?bitrary* pattern>»\n\n=item C«(?<!ar?bitrary* pattern)» becomes C«<!after ar?bitrary* pattern>»\n\n(Unrelated to C«<>» syntax, the \"lookaround\" C</foo\\Kbar/> becomes C«/foo <( bar )> /»\n\n=item C<(?(?{condition))yes-pattern|no-pattern)> becomes C«[ <?{condition}>\n      yes-pattern | no-pattern ]»\n\n=head2 Longest token matching (LTM) displaces alternation\n\nIn Raku regexes, C<|> does Longest Token Match (LTM), which decides which\nalternation wins an ambiguous match based off of a set of rules, rather than\nabout which was written first in the regex.\n\nTo avoid the new logic, change any C<|> in your Ruby regex to a C<||>.\n\n=head1 File-related operations\n\n=head2 Reading the lines of a text file into an array\n\nBoth Ruby and Raku make it easy to read all of the lines in a file into a\nsingle variable, and in both cases each line has the newline removed.\n\n=for code :lang<ruby>\nlines = File.readlines(\"file\")   # Ruby\n=for code\nmy @lines = \"file\".IO.lines;     # Raku, create an IO object from a string\n\n=head2 Iterating over the lines of a text file\n\nReading the entire file into memory isn't recommended. The C<.lines> method in\nRaku returns a lazy sequence, but assigning to an array forces the file to be\nread. It is better to iterate over the results:\n\n=begin code :lang<ruby>\n# Ruby\nFile.foreach(\"file\") do |line|\n    puts line\nend\n=end code\n\n=begin code\n# Raku\nfor \"file\".IO.lines -> $line {\n    say $line\n}\n=end code\n\n=head1 Object orientation\n\n=head2 Basic classes, methods, attributes\n\nClasses are defined similarly between Ruby and Raku, using the C<class>\nkeyword. Ruby uses C<def> for methods, whereas Raku uses C<method>.\n\n=begin code :lang<ruby>\n# Ruby\nclass Foo\n    def greet(name)\n        puts \"Hi #{name}!\"\n    end\nend\n=end code\n\n=begin code\n# Raku\nclass Foo {\n    method greet($name) {\n        say \"Hi $name!\"\n    }\n}\n=end code\n\nIn Ruby you can use an attribute without declaring it beforehand, and you can\ntell it is an attribute because of the C<@> sigil. You can also easily create\naccessors using C<attr_accessor> and its variants. In Raku you use a C<has>\ndeclaration and a variety of sigils. You can use the C<!> twigil for private\nattributes or C<.> to create an accessor.\n\n=begin code :lang<ruby>\n# Ruby\nclass Person\n    attr_accessor :age    # Declare .age as an accessor method for @age\n    def initialize\n        @name = 'default' # Assign default value to private instance var\n    end\nend\n=end code\n\n=begin code\n# Raku\nclass Person {\n    has $.age;              # Declare $!age and accessor methods\n    has $!name = 'default'; # Assign default value to private instance var\n}\n=end code\n\nCreating a new instance of the class uses the C<.new> method. In Ruby you must\nmanually assign instance variables as needed inside C<initialize>. In Raku\nyou get a default constructor that accepts key/value pairs of accessor\nattributes, and can do further setup in the C<TWEAK> method. Like with Ruby,\nyou can override C<new> itself for more advanced functionality, but this is\nrare.\n\n=begin code :lang<ruby>\n# Ruby\nclass Person\n    attr_accessor :name, :age\n    def initialize(attrs)\n        @name = attrs[:name] || 'Jill'\n        @age  = attrs[:age] || 42\n        @birth_year = Time.now.year - @age\n    end\nend\np = Person.new( name: 'Jack', age: 23 )\n=end code\n\n=begin code\n# Raku\nclass Person {\n    has $.name = 'Jill';\n    has $.age  = 42;\n    has $.birth_year;\n    method TWEAK {\n        $!birth_year = now.Date.year - $!age;\n    }\n}\nmy $p = Person.new( name => 'Jack', age => 23 )\n=end code\n\n=head2 Private methods\n\nPrivate methods in Raku are declared with a C<!> prefixed in their name, and\nare invoked with a C<!> instead of a C<.>.\n\n=begin code :lang<ruby>\n# Ruby\nclass Foo\n    def visible\n        puts \"I can be seen!\"\n        hidden\n    end\n\n    private\n    def hidden\n        puts \"I cannot easily be called!\"\n    end\nend\n=end code\n\n=begin code\n# Raku\nclass Foo {\n    method visible {\n        say \"I can be seen!\";\n        self!hidden;\n    }\n\n    method !hidden {\n        say \"I cannot easily be called!\";\n    }\n}\n=end code\n\nAn important note is that in Ruby child objects can see parent private methods\n(so they are more like \"protected\" methods in other languages). In Raku child\nobjects cannot call parent private methods.\n\n=head2 Going I<meta>\n\nHere are a few examples of metaprogramming. Note that Raku separates the\nmetamethods from the regular methods with a caret.\n\n=for code :lang<ruby>\n# Ruby\nperson = Person.new\nperson.class\nperson.methods\nperson.instance_variables\n\n=for code\n# Raku\nclass Person {};\n...\nmy $person = Person.new;\n$person.^name;             # Raku, returns Person (class)\n$person.^methods;          # Raku, using .^ syntax to access metamethods\n$person.^attributes;\n\n\nLike Ruby, in Raku, everything is an object, but not all operations are\nequivalent to C<.public_send>. Many operators are global functions that use typed\nmulti-dispatch (function signatures with types) to decide which implementation\nto use.\n\n=for code :lang<ruby>\n5.public_send(:+, 3)    # => 8, Ruby\n=for code\n&[+](5, 3)       # => 8, Raku, reference to infix addition operator\n&[+].^candidates # Raku, lists all signatures for the + operator\n\nSee L<Metaobject Protocol|/language/mop> for lots of further details.\n\n=head1 Environment variables\n\n=head2 Raku module library path\n\nIn Ruby, one of the environment variables to specify extra search paths for\nmodules is C<RUBYLIB>.\n\n=for code :lang<shell>\n$ RUBYLIB=\"/some/module/lib\" ruby program.rb\n\nIn Raku this is similar, you merely needs to change the name. As you probably\nguessed, you just need to use C<RAKULIB>:\n\n=for code :lang<shell>\n$ RAKULIB=\"/some/module/lib\" raku program.raku\n\nAs with Ruby, if you don't specify C<RAKULIB>, you need to specify the\nlibrary path within the program via the C<use lib> pragma:\n\n=for code :solo\n# Ruby and Raku\nuse lib '/some/module/lib';\n\n=head1 Misc.\n\n=head2 Importing specific functions from a module\n\nIn Ruby there is no built-in way to selectively import/export methods from a\nmodule.\n\nIn Raku you specify the functions which are to be exported by using the\nC<is export> role on the relevant subs and I<all> subs with this role are\nthen exported. Hence, the following module C<Bar> exports the subs C<foo>\nand C<bar> but not C<baz>:\n\n=for code :solo\nunit module Bar; # remainder of the file is in module Bar { ... }\nsub foo($a) is export { say \"foo $a\" }\nsub bar($b) is export { say \"bar $b\" }\nsub baz($z) { say \"baz $z\" }\n\nTo use this module, simply C<use Bar> and the functions C<foo> and C<bar>\nwill be available:\n\n=for code :skip-test<needs dummy module>\nuse Bar;\nfoo(1);    #=> \"foo 1\"\nbar(2);    #=> \"bar 2\"\n\nIf you try to use C<baz> an \"Undeclared routine\" error is raised at compile time.\n\nSome modules allow for selectively importing functions, which would look like:\n\n=begin code :skip-test<needs dummy module>\nuse Bar <foo>; # Import only foo\nfoo(1);        #=> \"foo 1\"\nbar(2);        # Error!\n=end code\n\n=head2 C<OptionParser>, parsing command-line flags\n\nCommand line argument switch parsing in Raku is done by the parameter list of\nthe C<MAIN> subroutine.\n\n=begin code :lang<ruby>\n# Ruby\nrequire 'optparse'\noptions = {}\nOptionParser.new do |opts|\n    opts.banner = 'Usage: example.rb --length=abc'\n    opts.on(\"--length\", \"Set the file\") do |length|\n        raise \"Length must be > 0\" unless length.to_i > 0\n        options[:length] = length\n    end\n    opts.on(\"--filename\", \"Set the file\") do |filename|\n        options[:file] = filename\n    end\n    opts.on(\"--verbose\", \"Increase verbosity\") do |verbose|\n        options[:verbose] = true\n    end\nend.parse!\n\nputs options[:length]\nputs options[:filename]\nputs 'Verbosity ', (options[:verbose] ? 'on' : 'off')\n=end code\n\n=begin code :lang<shell>\nruby example.rb --filename=foo --length=42 --verbose\n    42\n    foo\n    Verbosity on\n\nruby example.rb --length=abc\n    Length must be > 0\n=end code\n\n=begin code\n# Raku\nsub MAIN ( Int :$length where * > 0, :$filename = 'file.dat', Bool :$verbose ) {\n    say $length;\n    say $filename;\n    say 'Verbosity ', ($verbose ?? 'on' !! 'off');\n}\n=end code\n\n=begin code :lang<shell>\nraku example.raku --file=foo --length=42 --verbose\n    42\n    foo\n    Verbosity on\nraku example.raku --length=abc\n    Usage:\n      example.raku [--length=<Int>] [--file=<Any>] [--verbose]\n=end code\n\nNote that Raku auto-generates a full usage message on error in\ncommand-line parsing.\n\n=head1 RubyGems, external libraries\n\nSee L<https://raku.land/>, where a growing number of Raku libraries\nare available along with the tools to manage them.\n\nIf the module that you were using has not been converted to Raku, and no\nalternative is listed in this document, then its use under Raku may not\nhave been addressed yet.\n\n=begin comment\n\n### Guidelines for contributions:\n\nHeaders should contain the text that a Ruby user might search for, since\nthose headings will be in the Table of Contents generated for the top of\nthe document.\n\nWe use POD =item instead of =head3 or =head4 for identical bits that need not\nappear in the table of contents.\n\nThis article does not describe in detail language features that Ruby doesn't\nhave at all, instead referring to other documents.\n\nExample code and links to other documents should be favored over long\nexplanations of details better found elsewhere.\n\nFinally, if a real user asks a Ruby to Raku question that is not being\nanswered here, please add it to the document. Even if we do not have a good\nanswer yet, that will be better than losing the information about a real need.\n\n=end comment\n\n=end pod\n"
  },
  {
    "path": "doc/Language/regexes-best-practices.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"tutorial\")\n\n=TITLE Regexes: best practices and gotchas\n\n=SUBTITLE Some tips on regexes and grammars\n\nTo help with robust regexes and grammars, here are some best practices\nfor code layout and readability, what to actually match, and avoiding common\npitfalls.\n\n=head1 Code layout\n\nWithout the C<:sigspace> adverb, whitespace is not significant in Raku\nregexes. Use that to your own advantage and insert whitespace where it\nincreases readability. Also, insert comments where necessary.\n\nCompare the very compact\n\n    my regex float { <[+-]>?\\d*'.'\\d+[e<[+-]>?\\d+]? }\n\nto the more readable\n\n    my regex float {\n         <[+-]>?        # optional sign\n         \\d*            # leading digits, optional\n         '.'\n         \\d+\n         [              # optional exponent\n            e <[+-]>?  \\d+\n         ]?\n    }\n\nAs a rule of thumb, use whitespace around atoms and inside groups; put\nquantifiers directly after the atom; and vertically align opening and closing\nsquare brackets and parentheses.\n\nWhen you use a list of alternations inside parentheses or square brackets, align\nthe vertical bars:\n\n    my regex example {\n        <preamble>\n        [\n        || <choice_1>\n        || <choice_2>\n        || <choice_3>\n        ]+\n        <postamble>\n    }\n\n=head1 Keep it small\n\nRegexes are often more compact than regular code. Because they do so much with\nso little, keep regexes short.\n\nWhen you can name a part of a regex, it's usually best to\nput it into a separate, named regex.\n\nFor example, you could take the float regex from earlier:\n\n    my regex float {\n         <[+-]>?        # optional sign\n         \\d*            # leading digits, optional\n         '.'\n         \\d+\n         [              # optional exponent\n            e <[+-]>?  \\d+\n         ]?\n    }\n\nAnd decompose it into parts:\n\n    my token sign { <[+-]> }\n    my token decimal { \\d+ }\n    my token exponent { 'e' <sign>? <decimal> }\n    my regex float {\n        <sign>?\n        <decimal>?\n        '.'\n        <decimal>\n        <exponent>?\n    }\n\nThat helps, especially when the regex becomes more complicated. For example,\nyou might want to make the decimal point optional in the presence of an exponent.\n\n    my regex float {\n        <sign>?\n        [\n        || <decimal>?  '.' <decimal> <exponent>?\n        || <decimal> <exponent>\n        ]\n    }\n\n=head1 What to match\n\nOften the input data format has no clear-cut specification, or the\nspecification is not known to the programmer. Then, it's good to be liberal\nin what you expect, but only so long as there are no possible ambiguities.\n\nFor example, in C<ini> files:\n\n    =begin code :lang<ini>\n    [section]\n    key=value\n    =end code\n\nWhat can be inside the section header? Allowing only a word might be too\nrestrictive. Somebody might write C<[two words]>, or use dashes, etc.\nInstead of asking what's allowed on the inside, it might be worth asking\ninstead: I<what's not allowed?>\n\nClearly, closing square brackets are not allowed, because C<[a]b]> would be\nambiguous. By the same argument, opening square brackets should be forbidden.\nThis leaves us with\n\n    token header { '[' <-[ \\[\\] ]>+ ']' }\n\nwhich is fine if you are only processing one line. But if you're processing\na whole file, suddenly the regex parses\n\n    =begin code :lang<text>\n    [with a\n    newline in between]\n    =end code\n\nwhich might not be a good idea.  A compromise would be\n\n    token header { '[' <-[ \\[\\] \\n ]>+ ']' }\n\nand then, in the post-processing, strip leading and trailing spaces and tabs\nfrom the section header.\n\n=head1 Matching whitespace\n\nThe C<:sigspace> adverb (or using the C<rule> declarator instead of C<token>\nor C<regex>) is very handy for implicitly parsing whitespace that can appear\nin many places.\n\nGoing back to the example of parsing C<ini> files, we have\n\n    my regex kvpair { \\s* <key=identifier> '=' <value=identifier> \\n+ }\n\nwhich is probably not as liberal as we want it to be, since the user might\nput spaces around the equals sign. So, then we may try this:\n\n    my regex kvpair { \\s* <key=identifier> \\s* '=' \\s* <value=identifier> \\n+ }\n\nBut that's looking unwieldy, so we try something else:\n\n    my rule kvpair { <key=identifier> '=' <value=identifier> \\n+ }\n\nBut wait! The implicit whitespace matching after the value uses up all\nwhitespace, including newline characters, so the C<\\n+> doesn't have\nanything left to match (and C<rule> also disables backtracking, so no luck\nthere).\n\nTherefore, it's important to redefine your definition of implicit whitespace\nto whitespace that is not significant in the input format.\n\nThis works by redefining the token C<ws>; however, it only works for\nL<grammars|/language/grammars>:\n\n    grammar IniFormat {\n        token ws { <!ww> \\h* }\n        rule header { \\s* '[' (\\w+) ']' \\n+ }\n        token identifier  { \\w+ }\n        rule kvpair { \\s* <key=identifier> '=' <value=identifier> \\n+ }\n        token section {\n            <header>\n            <kvpair>*\n        }\n\n        token TOP {\n            <section>*\n        }\n    }\n\n    my $contents = q:to/EOI/;\n        [passwords]\n            jack = password1\n            joy = muchmoresecure123\n        [quotas]\n            jack = 123\n            joy = 42\n    EOI\n    say so IniFormat.parse($contents);\n\nBesides putting all regexes into a grammar and turning them into tokens\n(because they don't need to backtrack anyway), the interesting new bit is\n\n        token ws { <!ww> \\h* }\n\nwhich gets called for implicit whitespace parsing. It matches when it's not\nbetween two word characters (C«<!ww>», negated \"within word\" assertion),\nand zero or more horizontal space characters. The limitation to horizontal\nwhitespace is important, because newlines (which are vertical whitespace)\ndelimit records and shouldn't be matched implicitly.\n\nStill, there's some whitespace-related trouble lurking. The regex C<\\n+>\nwon't match a string like C<\"\\n \\n\">, because there's a blank between the\ntwo newlines. To allow such input strings, replace C<\\n+> with C<\\n\\s*>.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/regexes.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Regexes\n\n=SUBTITLE Pattern matching against strings\n\nX<|Language,Regular Expressions>\n\nA I<regular expression> is a sequence of characters that defines a certain text\npattern, typically one that one wishes to find in some large body of text.\n\nIn theoretical computer science and formal language theory, regular expressions\nare used to describe so-called\nL<I<regular languages>|https://en.wikipedia.org/wiki/Regular_language>. Since\ntheir inception in the 1950's, practical implementations of regular expressions,\nfor instance in the text search and replace functions of text editors, have outgrown\ntheir strict scientific definition. In acknowledgement of this, and in an attempt\nto disambiguate, a regular expression in Raku is normally referred to as a\nL<C<Regex>|/type/Regex> (from: I<reg>ular I<ex>pression), a term that is also in common use in\nother programming languages.\n\nIn Raku, regexes are written in a\nL<I<domain-specific language>|https://en.wikipedia.org/wiki/Domain-specific_language>,\ni.e. a sublanguage or L<I<slang>|/language/slangs>. This page describes this language, and explains how\nregexes can be used to search for text patterns in strings in a process called\nI<pattern matching>.\n\nRaku regexes can L<interpolate|/language/regexes#Regex_interpolation>\nvariables or code blocks in several different ways, and can be modified\nby a variety of L<adverbs|/language/regexes#Adverbs>.\n\n=head1 X<Lexical conventions|Syntax,/ />\n\nX<|Syntax,rx>\nX<|Syntax,m>\n\nFundamentally, Raku regexes are very much like subroutines: both are code\nobjects, and just as you can have anonymous subs and named subs, you can have\nanonymous and named regexes.\n\nA regex, whether anonymous or named, is represented by a L<C<Regex>|/type/Regex>\nobject. Yet, the syntax for constructing anonymous and named L<C<Regex>|/type/Regex> objects\ndiffers. We will therefore discuss them in turn.\n\n=head2 Anonymous regex definition syntax\n\nAn anonymous regex may be constructed in one of the following ways:\n\n    rx/pattern/;          # an anonymous Regex object; 'rx' stands for 'regex'\n    /pattern/;            # an anonymous Regex object; shorthand for 'rx/.../'\n\n    regex { pattern };    # keyword-declared anonymous regex; this form is\n                          # intended for defining named regexes and is discussed\n                          # in that context in the next section\n\nThe C<rx/ /> form has two advantages over the bare shorthand form C</ />.\n\nFirstly, it enables the use of delimiters other than the slash, which may be\nused to improve the readability of the regex definition:\n\n    rx{ '/tmp/'.* };      # the use of curly braces as delimiters makes this first\n    rx/ '/tmp/'.* /;      # definition somewhat easier on the eyes than the second\n\nAlthough the choice is vast, not every character may be chosen as an alternative\nregex delimiter:\n\n=begin item\nYou cannot use whitespace or alphanumeric characters as delimiters. Whitespace\nin regex definition syntax is generally optional, except where it is required to\ndistinguish from function call syntax (discussed hereafter).\n=end item\n\n=begin item\nParentheses can be used as alternative regex delimiters, but only with a space\nbetween C<rx> and the opening delimiter. This is because identifiers that are\nimmediately followed by parentheses are always parsed as a subroutine call. For example,\nin C<rx()> the L<call operator|/language/operators#postcircumfix_(_)> C<()>\ninvokes the subroutine C<rx>. The form C<rx ( abc )>, however, I<does> define a\nL<C<Regex>|/type/Regex> object.\n=end item\n\n=begin item\nUse of a colon as a delimiter would clash with the use of\nL<adverbs|/language/regexes#Adverbs>, which take the form C<:adverb>;\naccordingly, such use of the colon is forbidden.\n=end item\n\n=begin item\nThe hash character C<#> is not available as a delimiter since it is parsed as the start\nof a L<comment|/language/syntax#Single-line_comments> that runs until the end of\nthe line.\n=end item\n\nSecondly, the C<rx> form allows you to insert\nL<regex adverbs|/language/regexes#Regex_adverbs> between C<rx> and the\nopening delimiter to modify the definition of the entire regex.  This is equivalent to\ninserting the adverb at the beginning of the regex, but may be clearer:\n\n    rx:r:s/pattern/;            # :r (:ratchet) and :s (:sigspace) adverbs, defining\n                                # a ratcheting regex in which whitespace is significant\n    rx/:r:s pattern/;           # Same, but possibly less readable\n\nAlthough anonymous regexes are not, as such, I<named>, they may effectively be\ngiven a name by putting them inside a named variable, after which they can be\nreferenced, both outside of an embedding regex and from within an embedding\nregex by means of L<interpolation|/language/regexes#Regex_interpolation>:\n\n  my $regex = / R \\w+ /;\n  say \"Zen Buddhists like Raku too\" ~~ $regex; # OUTPUT: «｢Raku｣␤»\n\n  my $regex = /pottery/;\n  \"Japanese pottery rocks!\" ~~ / <$regex> /;  # Interpolation of $regex into /.../\n  say $/;                                     # OUTPUT: «｢pottery｣␤»\n\n=head2 Named regex definition syntax\n\nA named regex may be constructed using the C<regex> declarator as follows:\n\n    regex R { pattern };        # a named Regex object, named 'R'\n\nUnlike with the C<rx> form, you cannot chose your preferred delimiter: curly\nbraces are mandatory. In this regard it should be noted that the definition of a\nnamed regex using the C<regex> form is syntactically similar to the definition\nof a subroutine:\n\n    my sub   S { /pattern/ };   # definition of Sub object (returning a Regex)\n    my regex R {  pattern  };   # definition of Regex object\n\nwhich emphasizes the fact that a L<C<Regex>|/type/Regex> object represents code\nrather than data:\n\n=begin code :preamble<my sub   S { /pattern/ }; my regex R {  pattern  };>\n&S ~~ Code;                 # OUTPUT: «True␤»\n\n&R ~~ Code;                 # OUTPUT: «True␤»\n&R ~~ Method;               # OUTPUT: «True␤»   (A Regex is really a Method!)\n=end code\n\nAlso unlike with the C<rx> form for defining an anonymous regex, the definition\nof a named regex using the C<regex> keyword does not allow for adverbs to be\ninserted before the opening delimiter. Instead, adverbs that are to modify the\nentire regex pattern may be included first thing within the curly braces:\n\n    regex R { :i pattern };     # :i (:ignorecase), renders pattern case insensitive\n\nAlternatively, by way of shorthand, it is also possible (and recommended) to use\nthe C<rule> and C<token> variants of the C<regex> declarator for defining a\nL<C<Regex>|/type/Regex> when the C<:ratchet> and C<:sigspace> adverbs are of interest:\n\n=for code\nregex R { :r pattern };     # apply :r (:ratchet) to entire pattern\n\nand, alternatively\n\n=for code\ntoken R { pattern };        # same thing: 'token' implies ':r'\n\nOr\n\n=for code\nregex R { :r :s pattern };  # apply :r (:ratchet) and :s (:sigspace) to pattern\n\nwith this alternative:\n\n=for code\nrule  R { pattern };        # same thing: 'rule' implies ':r:s'\n\nNamed regexes may be used as building blocks for other regexes, as they are\nmethods that may called from within other regexes using the C«<regex-name>»\nsyntax. When they are used this way, they are often referred to as I<subrules>;\nsee for more details on their use L<here|/language/regexes#Subrules>.\nL<C<Grammar>|/type/Grammar>s are the natural habitat of subrules, but many common\npredefined character classes are also implemented as named regexes.\n\n=head2 Regex readability: whitespace and comments\n\nWhitespace in regexes is ignored unless the\nL<C<:sigspace>|/language/regexes#Sigspace> adverb is used to make whitespace\nsyntactically significant.\n\nIn addition to whitespace, comments may be used inside of regexes to improve\ntheir comprehensibility just as in code in general. This is true for both\nL<single line comments|/language/syntax#Single-line_comments> and\nL<multi line/embedded comments|/language/syntax#Multi-line_/_embedded_comments>:\n\n    my $regex =  rx/ \\d ** 4            #`(match the year YYYY)\n                     '-'\n                     \\d ** 2            # ...the month MM\n                     '-'\n                     \\d ** 2 /;         # ...and the day DD\n\n    say '2015-12-25'.match($regex);     # OUTPUT: «｢2015-12-25｣␤»\n\n=head2 Match syntax\n\nThere are a variety of ways to match a string against a regex. Irrespective of\nthe syntax chosen, a successful match results in a L<C<Match>|/type/Match>\nobject. In case the match is unsuccessful, the result is L<C<Nil>|/type/Nil>. In\neither case, the result of the match operation is available via the special\nmatch variable L<C<$/>|/syntax/$$SOLIDUS>.\n\nThe most common ways to match a string against an anonymous regex C</pattern/> or\nagainst a named regex C<R> include the following:\n\n=begin item\nI«Smartmatch: \"string\" ~~ /pattern/, or \"string\" ~~ /<R>/»\n\nL<Smartmatching|/language/operators#index-entry-smartmatch_operator> a string\nagainst a L<C<Regex>|/type/Regex> performs a regex match of the string against the L<C<Regex>|/type/Regex>:\n\n    say \"Go ahead, make my day.\" ~~ / \\w+ /;   # OUTPUT: «｢Go｣␤»\n\n    my regex R { me|you };\n    say \"You talkin' to me?\" ~~ / <R> /;       # OUTPUT: «｢me｣␤ R => ｢me｣␤»\n    say \"May the force be with you.\" ~~ &R ;   # OUTPUT: «｢you｣␤»\n\nThe different outputs of the last two statements show that these two ways of\nsmartmatching against a named regex are not identical. The difference arises\nbecause the method call C«<R>» from within the anonymous regex C</ /> installs\na so-called L<'named capture'|/language/regexes#Named_captures> in the L<C<Match>|/type/Match>\nobject, while the smartmatch against the named L<C<Regex>|/type/Regex> as such does not.\n=end item\n\n=begin item\nI«Explicit topic match: m/pattern/, or m/<R>/»\n\nThe match operator C<m/ /> immediately matches the topic variable\nL<C<$_>|/language/variables#index-entry-topic_variable> against the regex\nfollowing the C<m>.\n\nAs with the C<rx/ /> syntax for regex definitions, the match operator may be\nused with adverbs in between C<m> and the opening regex delimiter, and with\ndelimiters other than the slash. However, while the C<rx/ /> syntax may only be\nused with L<I<regex adverbs>|/language/regexes#Regex_adverbs> that affect the\ncompilation of the regex, the C<m/ /> syntax may additionally be used with\nL<I<matching adverbs>|/language/regexes#Matching_adverbs> that determine how the\nregex engine is to perform pattern matching.\n\nHere's an example that illustrates the primary difference between the C<m/ />\nand C</ /> syntax:\n\n    my $match;\n    $_ = \"abc\";\n    $match = m/.+/; say $match; say $match.^name; # OUTPUT: «｢abc｣␤Match␤»\n    $match =  /.+/; say $match; say $match.^name; # OUTPUT: «/.+/␤Regex␤»\n=end item\n\n=begin item\nI«Implicit topic match in sink and Boolean contexts»\n\nIn case a L<C<Regex>|/type/Regex> object is used in sink context, or in a context in which it\nis coerced to L<C<Bool>|/type/Bool>, the topic variable\nL<C<$_>|/language/variables#index-entry-topic_variable> is automatically matched\nagainst it:\n\n  $_ = \"dummy string\";        # Set the topic explicitly\n\n  rx/ s.* /;                  # Regex object in sink context matches automatically\n  say $/;                     # OUTPUT: «｢string｣␤»\n\n  say $/ if rx/ d.* /;        # Regex object in Boolean context matches automatically\n                              # OUTPUT: «｢dummy string｣␤»\n=end item\n\n=begin item\nI«Match method: \"string\".match: /pattern/, or \"string\".match: /<R>/»\n\nThe L<C<match>|/type/Str#method_match> method is analogous to the C<m/ />\noperator discussed above. Invoking it on a string, with a L<C<Regex>|/type/Regex> as an\nargument, matches the string against the L<C<Regex>|/type/Regex>.\n=end item\n\n=begin item\nI«Parsing grammars: grammar-name.parse($string)»\n\nAlthough parsing a L<grammar|/language/grammars> involves more than just\nmatching a string against a regex, this powerful regex-based text destructuring\ntool can't be left out from this overview of common pattern matching methods.\n\nIf you feel that your needs exceed what simple regexes have to offer, check out this\nL<grammar tutorial|/language/grammar_tutorial> to take regexes to the next level.\n=end item\n\n\n=head1 Literals and metacharacters\n\nA regex describes a pattern to be matched in terms of literals and\nmetacharacters. Alphanumeric characters and the underscore C<_> constitute the\nliterals: these characters match themselves and nothing else. Other characters\nact as metacharacters and may, as such, have a special meaning, either by\nthemselves (such as the dot C<.>, which serves as a wildcard) or together with\nother characters in larger metasyntactic constructs (such as C«<?before ...>»,\nwhich defines a lookahead assertion).\n\nIn its simplest form a regex comprises only literals:\n\n    /Cześć/;           # \"Hello\" in Polish\n    /こんばんは/;        # \"Good afternoon\" in Japanese\n    /Καλησπέρα/;       # \"Good evening\" in Greek\n\nIf you want a regex to literally match one or more characters that normally act\nas metacharacters, those characters must either be escaped using a backslash, or\nbe quoted using single or double quotes.\n\nThe backslash serves as a switch. It switches a single metacharacter into a\nliteral, and vice versa:\n\n    / \\# /;             # matches the hash metacharacter literally\n    / \\w /;             # turns literal 'w' into a character class (see below)\n    /Hallelujah\\!/;     # matches string 'Hallelujah!' incl. exclamation mark\n\nEven if a metacharacter does not (yet) have a special meaning in Raku,\nescaping (or quoting) it is required to ensure that the regex compiles and\nmatches the character literally. This allows the clear distinction between\nliterals and metacharacters to be maintained. So, for instance, to match a\ncomma this will work:\n\n    / \\, /;             # matches a literal comma ','\n\nwhile this will fail:\n=for code :skip-test<deliberate error>\n/ ,  /;             # !! error: an as-yet meaningless/unrecognized metacharacter\n                    # does not automatically match literally\n\nWhile an escaping backslash exerts its effect on the next individual character,\nboth a single metacharacter and a sequence of metacharacters may be turned into\nliterally matching strings by quoting them in single or double quotes:\n\n    / \"abc\" /;          # quoting literals does not make them more literal\n    / \"Hallelujah!\" /;  # yet, this form is generally preferred over /Hallelujah\\!/\n\n    / \"two words\" /;    # quoting a space renders it significant, so this matches\n                        # the string 'two words' including the intermediate space\n\n    / '#!:@' /;         # this regex matches the string of metacharacters '#!:@'\n\nQuoting does not necessarily turn every metacharacter into a literal, however.\nThis is because quotes follow Raku's normal L<rules for\ninterpolation|/language/quoting#The_Q_lang>. In particular, C<｢…｣> quotes do not\nallow any interpolation; single quotes (either C<'…'> or C<‘…’>) allow the\nbackslash to escape single quotes and the backslash itself; and double quotes\n(either C<\"…\"> or C<“…”>) enable the interpolation of variables and code blocks\nof the form C<{…}>. Hence all of this works:\n\n\n    / '\\\\\\'' /;          # matches a backslash followed by a single quote: \\'\n    / ｢\\'｣ /;       # also matches a backslash followed by a single quote\n    my $x = 'Hi';\n    / \"$x there!\" /;     # matches the string 'Hi there!'\n\n    / \"1 + 1 = {1+1}\" /; # matches the string '1 + 1 = 2'\n\nwhile these examples illustrate mistakes that you will want to avoid:\n=begin code :skip-test<deliberate error>\n/ '\\' /;             # !! error: this is NOT the way to literally match a\n                     # backslash because now it escapes the second quote\n\n/\"Price tag $0.50\"/; # !! error: \"$0\" is interpreted as the first positional\n                     # capture (which is Nil), not as '$0'\n=end code\n\nStrings are searched left to right, so it is enough if only part of the string\nmatches the regex:\n\n    if 'Life, the Universe and Everything' ~~ / and / {\n        say ~$/;            # OUTPUT: «and␤»\n        say $/.prematch;    # OUTPUT: «Life, the Universe ␤»\n        say $/.postmatch;   # OUTPUT: « Everything␤»\n        say $/.from;        # OUTPUT: «19␤»\n        say $/.to;          # OUTPUT: «22␤»\n    };\n\n\nMatch results are always stored in the C<$/> variable and are also returned from\nthe match. They are both of type L<C<Match>|/type/Match> if the match was\nsuccessful; otherwise both are of type L<C<Nil>|/type/Nil>.\n\n\n=head1 X<Wildcards|Regexes,.>\n\nAn unescaped dot C<.> in a regex matches any single character.\n\nSo, these all match:\n\n    'raku' ~~ /rak./;       # matches the whole string\n    'raku' ~~ / rak . /;    # the same; whitespace is ignored\n    'raku' ~~ / ra.u /;     # the . matches the k\n    'raker' ~~ / rak. /;    # the . matches the e\n\nwhile this doesn't match:\n\n    'raku' ~~ / . rak /;\n\nbecause there's no character to match before C<rak> in the target string.\n\nNotably C<.> also matches a logical newline C<\\n>:\n\n    my $text = qq:to/END/\n      Although I am a\n      multi-line text,\n      I can be matched\n      with /.*/.\n      END\n      ;\n\n    say $text ~~ / .* /;\n    # OUTPUT: «｢Although I am a␤multi-line text,␤I can be matched␤with /.*/.␤｣»\n\n=head1 Character classes\n\n=head2 Backslashed character classes\n\nThere are predefined character classes of the form C<\\w>. Its negation is\nwritten with an uppercase letter, C<\\W>.\n\n=head3 X<C<\\n> and C<\\N>|Regexes,\\n>\n\nX<|Regexes,\\N>\nC<\\n> matches a logical newline. C<\\N> matches a single character that's not a\nlogical newline.\n\nThe definition of what constitutes a logical newline follows the\nL<Unicode definition of a line boundary|https://unicode.org/reports/tr18/#Line_Boundaries>\nand includes in particular all of: a line feed (LF) C<\\U+000A>, a vertical tab\n(VT) C<\\U+000B>, a form feed (FF) C<\\U+000C>, a carriage return (CR) C<\\U+000D>,\nand the Microsoft Windows style newline sequence CRLF.\n\nThe interpretation of C<\\n> in regexes is independent of the value of the\nvariable C<$?NL> controlled by the L<newline pragma|/language/pragmas#newline>.\n\n\n=head3 X<C<\\t> and C<\\T>|Regexes,\\t>\n\nX<|Regexes,\\T>\nC<\\t> matches a single tab/tabulation character, C<U+0009>. C<\\T> matches a\nsingle character that is not a tab.\n\nNote that exotic tabs like the C<U+000B VERTICAL TABULATION> character are not\nincluded here.\n\n=head3 X<C<\\h> and C<\\H>|Regexes,\\h>\n\nX<|Regexes,\\H>\nC<\\h> matches a single horizontal whitespace character. C<\\H> matches a\nsingle character that is not a horizontal whitespace character.\n\nExamples of horizontal whitespace characters are\n\n    =begin code :lang<text>\n    U+0020 SPACE\n    U+00A0 NO-BREAK SPACE\n    U+0009 CHARACTER TABULATION\n    U+2001 EM QUAD\n    =end code\n\nVertical whitespace such as newline characters are explicitly excluded; those\ncan be matched with C<\\v>; C<\\s> matches any kind of whitespace.\n\n=head3 X<C<\\v> and C<\\V>|Regexes,\\v>\n\nX<|Regexes,\\V>\nC<\\v> matches a single vertical whitespace character. C<\\V> matches a single\ncharacter that is not vertical whitespace.\n\nExamples of vertical whitespace characters:\n\n    =begin code :lang<text>\n    U+000A LINE FEED\n    U+000B VERTICAL TABULATION\n    U+000C FORM FEED\n    U+000D CARRIAGE RETURN\n    U+0085 NEXT LINE\n    U+2028 LINE SEPARATOR\n    U+2029 PARAGRAPH SEPARATOR\n    =end code\n\nUse C<\\s> to match any kind of whitespace, not just vertical whitespace.\n\n=head3 X<C<\\s> and C<\\S>|Regexes,\\s>\n\nX<|Regexes,\\S>\nC<\\s> matches a single whitespace character. C<\\S> matches a single\ncharacter that is not whitespace.\n\n    say $/.prematch if 'Match the first word.' ~~ / \\s+ /;\n    # OUTPUT: «Match␤»\n\n=head3 X<C<\\d> and C<\\D>|Regexes,\\d>\n\nX<|Regexes,\\D>\nC<\\d> matches a single decimal digit (Unicode General Category I<Number, Decimal\nDigit>, C<Nd>); conversely, C<\\D> matches a\nsingle character that is I<not> a decimal digit.\n\n    'ab42' ~~ /\\d/ and say ~$/;     # OUTPUT: «4␤»\n    'ab42' ~~ /\\D/ and say ~$/;     # OUTPUT: «a␤»\n\nNote that not only the Arabic digits (commonly used in the Latin\nalphabet) match C<\\d>, but also decimal digits from other scripts.\n\nExamples of decimal digits include:\n\n=begin code :lang<text>\nU+0035 5 DIGIT FIVE\nU+0BEB ௫ TAMIL DIGIT FIVE\nU+0E53 ๓ THAI DIGIT THREE\nU+17E5 ៥ KHMER DIGIT FIVE\n=end code\n\nAlso note that \"decimal digit\" is a narrower category than \"Number\" because (Unicode) numbers include\nnot only decimal numbers (C<Nd>) but also letter numbers (C<Nl>) and other numbers (C<No>)\nExamples of Unicode numbers that are not decimal digits include:\n\n=begin code :lang<text>\nU+2464 ⑤ CIRCLED DIGIT FIVE\nU+2476 ⑶ PARENTHESIZED DIGIT THREE\nU+2083 ₃ SUBSCRIPT THREE\n=end code\n\nTo match against all numbers, you can use the L<Unicode property|#Unicode_properties> C<N>:\n\n    say '⑤' ~~ /<:N>/ # OUTPUT: «｢⑤｣␤»\n\n\n=head3 X<C<\\w> and C<\\W>|Regexes,\\w>\n\nX<|Regexes,\\W>\nC<\\w> matches a single word character, i.e. a letter (Unicode category\nL), a digit or an underscore. C<\\W> matches a single character that is\nnot a word character.\n\nExamples of word characters:\n\n    =begin code :lang<text>\n    0041 A LATIN CAPITAL LETTER A\n    0031 1 DIGIT ONE\n    03B4 δ GREEK SMALL LETTER DELTA\n    03F3 ϳ GREEK LETTER YOT\n    0409 Љ CYRILLIC CAPITAL LETTER LJE\n    99F1 駱 CJK UNIFIED IDEOGRAPH-99F1\n    =end code\n\n=head3 X<C<\\c> and C<\\C>|Regexes,\\c>\n\nX<|Regexes,\\C>\nC<\\c> takes a parameter delimited by square-brackets which is the name\nof a Unicode character as it appears in the\nL<Unicode Character Database (UCD)|https://unicode.org/ucd/> and matches\nthat specific character. For example:\n\n    'a.b' ~~ /\\c[FULL STOP]/ and say ~$/;    # OUTPUT: «.␤»\n\nC<\\C> matches a single character that is not the named Unicode character.\n\nNote that the word \"character\" is used, here, in the sense that the UCD\ndoes, but because Raku uses L<NFG|/language/glossary#NFG>, combining\ncode points and the base characters to which they are attached,\nwill generally not match individually. For example if you compose\nC<\"ü\"> as C<\"u\\x[0308]\">, that works just fine, but matching may surprise\nyou:\n\n     say \"u\\x[0308]\" ~~ /\\c[LATIN SMALL LETTER U]/;    # OUTPUT: «Nil␤»\n\nTo match the unmodified character, you can use the\nL<C<:ignoremark>|#Ignoremark> adverb.\n\n=head3 X<C<\\x> and C<\\X>|Regexes,\\x>\n\nX<|Regexes,\\X>\nC<\\x> takes a parameter delimited by square-brackets which is the\nhexadecimal representation of the Unicode codepoint representing the\ncharacter to be matched. For example:\n\n    'a.b' ~~ /\\x[2E]/ and say ~$/;    # OUTPUT: «.␤»\n\nC<\\X> matches a single character that is not the given Unicode codepoint.\n\nIn addition, C<\\x> and C<\\X> can be used without square brackets, in which case, any\ncharacters that follow the C<x> or C<X> that are valid hexadecimal digits will\nbe consumed. This means that all of these are equivalent:\n\n    /\\x2e/ and /\\x002e/ and /\\x00002e/\n\nBut this format can be ambiguous, so the use of surrounding whitespace is\nhighly recommended in non-trivial expressions.\n\nFor additional provisos with respect to combining codepoints, see\nL<C<\\c> and C<\\C>|#\\c_and_\\C>.\n\n=head2 Predefined character classes\n\n=begin table\n\n    Class    | Shorthand | Description\n    =========+===========+=============\n    <alpha>  |           | Alphabetic characters plus underscore (_)\n    <digit>  | \\d        | Decimal digits\n    <xdigit> |           | Hexadecimal digit [0-9A-Fa-f]\n    <alnum>  | \\w        | <alpha> plus <digit>\n    <punct>  |           | Punctuation and Symbols (ASCII and non-ASCII)\n    <graph>  |           | <alnum> plus <punct>\n    <space>  | \\s        | Whitespace\n    <cntrl>  |           | Control characters\n    <print>  |           | <graph> plus <space>, but no <cntrl>\n    <blank>  | \\h        | Horizontal whitespace\n    <lower>  | <:Ll>     | Lowercase characters\n    <upper>  | <:Lu>     | Uppercase characters\n\n=end table\n\nThe predefined character classes in the leftmost column are all of the form\nC«<name>», a hint to the fact that they are implemented as built-in\nL<named regexes|/language/regexes#Subrules>.\nAs such they are subject to the usual capturing semantics. This means that if\na character class is called with the syntax C«<name>» (i.e. as indicated in\nthe leftmost column), it will not only match, but also capture, installing a\ncorrespondingly named L<'named capture'|/language/regexes#Named_captures> in the\nresulting L<C<Match>|/type/Match>. In case just a match and no capture is\ndesired, the capture may be suppressed through the use of call syntax that\nincludes a leading dot: C«<.name>».\n\n=head2 Predefined Regexes\n\nBesides the built-in character classes, Raku provides built-in\nL<anchors|/language/regexes#Anchors> and L<zero-width\nassertions|/language/regexes#Zero-width_assertions> defined as named regexes.\nThese include C<wb> (word boundary), C<ww> (within word), and C<same> (the next\nand previous character are the same).  See the\nL<anchors|/language/regexes#Anchors> and L<zero-width\nassertions|/language/regexes#Zero-width_assertions> sections for details.\n\nRaku also provides the two predefined tokens (i.e., regexes that don't\nL<backtrack|/language/regexes#Backtracking>) shown below:\n\n=table\n    Token    | Regex equivalent |   Description\n    =========+=====================================\n    <ws>     |  <!ww> \\s*:      | Word-separating whitespace (including zero, e.g. at EOF)\n    <ident>  |  <.alpha> \\w*:   | L<Ordinary identifiers|/language/Syntax#Identifiers> (no support for ' or -).\n\n=head2 X«Unicode properties|Regexes,<:property>»\n\nThe character classes mentioned so far are mostly for convenience; another\napproach is to use Unicode character properties. These come in the form\nC«<:property>», where C<property> can be a short or long Unicode General\nCategory name. These use pair syntax.\n\nTo match against a Unicode property you can use either smartmatch or\nL<C<uniprop>|/routine/uniprop>:\n\n    \"a\".uniprop('Script');                 # OUTPUT: «Latin␤»\n    \"a\" ~~ / <:Script<Latin>> /;           # OUTPUT: «｢a｣␤»\n    \"a\".uniprop('Block');                  # OUTPUT: «Basic Latin␤»\n    \"a\" ~~ / <:Block('Basic Latin')> /;    # OUTPUT: «｢a｣␤»\n\nThese are the Unicode general categories used for matching:\n\n=begin table\n\n    Short   |    Long\n    ========+========\n    L       |    Letter\n    LC      |    Cased_Letter\n    Lu      |    Uppercase_Letter\n    Ll      |    Lowercase_Letter\n    Lt      |    Titlecase_Letter\n    Lm      |    Modifier_Letter\n    Lo      |    Other_Letter\n    M       |    Mark\n    Mn      |    Nonspacing_Mark\n    Mc      |    Spacing_Mark\n    Me      |    Enclosing_Mark\n    N       |    Number\n    Nd      |    Decimal_Number or digit\n    Nl      |    Letter_Number\n    No      |    Other_Number\n    P       |    Punctuation or punct\n    Pc      |    Connector_Punctuation\n    Pd      |    Dash_Punctuation\n    Ps      |    Open_Punctuation\n    Pe      |    Close_Punctuation\n    Pi      |    Initial_Punctuation\n    Pf      |    Final_Punctuation\n    Po      |    Other_Punctuation\n    S       |    Symbol\n    Sm      |    Math_Symbol\n    Sc      |    Currency_Symbol\n    Sk      |    Modifier_Symbol\n    So      |    Other_Symbol\n    Z       |    Separator\n    Zs      |    Space_Separator\n    Zl      |    Line_Separator\n    Zp      |    Paragraph_Separator\n    C       |    Other\n    Cc      |    Control or cntrl\n    Cf      |    Format\n    Cs      |    Surrogate\n    Co      |    Private_Use\n    Cn      |    Unassigned\n\n=end table\n\nFor example, C«<:Lu>» matches a single, uppercase letter.\n\nIts negation is this: C«<:!property>». So, C«<:!Lu>» matches a single\ncharacter that is not an uppercase letter.\n\nCategories can be used together, with an infix operator:\n\n=begin table\n    Operator  |  Meaning\n    ==========+=========\n    \\+        |  set union\n     -        |  set difference\n=end table\n\nTo match either a lowercase letter or a number, write\nC«<:Ll+:N>» or C«<:Ll+:Number>» or C«<+ :Lowercase_Letter + :Number>».\n\nIt's also possible to group categories and sets of categories with\nparentheses; for example:\n\n    say $0 if 'raku9' ~~ /\\w+(<:Ll+:N>)/ # OUTPUT: «｢9｣␤»\n\n=head2 X«Enumerated character classes and ranges|Regexes,<[ ]>»\n\nX«|Regexes,<-[ ]>»\nSometimes the pre-existing wildcards and character classes are not\nenough. Fortunately, defining your own is fairly simple. Within C«<[ ]>»,\nyou can put any number of single characters and ranges of characters\n(expressed with two dots between the end points), with or without\nwhitespace.\n\n    \"abacabadabacaba\" ~~ / <[ a .. c 1 2 3 ]>* /;\n    # Unicode hex codepoint range\n    \"ÀÁÂÃÄÅÆ\" ~~ / <[ \\x[00C0] .. \\x[00C6] ]>* /;\n    # Unicode named codepoint range\n    \"αβγ\" ~~ /<[\\c[GREEK SMALL LETTER ALPHA]..\\c[GREEK SMALL LETTER GAMMA]]>*/;\n    # Non-alphanumeric\n    '$@%!' ~~ /<[ ! @ $ % ]>+/  # OUTPUT: «｢$@%!｣␤»\n\nAs the last line above illustrates, within C«<[ ]>» you do I<not> need to\nquote or escape most non-alphanumeric characters the way you do in regex text\noutside of C«<[ ]>».  You do, however, need to escape the much smaller set of\ncharacters that have special meaning within C«<[ ]>», such as C<\\>, C<[>, and\nC<]>.\n\nX<|Language,escaping characters>\nTo escape characters that would have some meaning inside the C«<[ ]>», precede\nthe character with a C<\\>.\n\n    say \"[ hey ]\" ~~ /<-[ \\] \\[ \\s ]>+/; # OUTPUT: «｢hey｣␤»\n\nYou do not have the option of quoting special characters inside a C«<[ ]>» –\na C<'> just matches a literal C<'>.\n\nWithin the C«< >» you can use C<+> and C<-> to add or remove multiple range\ndefinitions and even mix in some of the Unicode categories above. You can also\nwrite the backslashed forms for character classes between the C<[ ]>.\n\n    / <[\\d] - [13579]> /;\n    # starts with \\d and removes odd ASCII digits, but not quite the same as\n    / <[02468]> /;\n    # because the first one also contains \"weird\" unicodey digits\n\nYou can include Unicode properties in the list as well:\n\n    /<:Zs + [\\x9] - [\\xA0] - [\\x202F] >/\n    # Any character with \"Zs\" property, or a tab, but not a \"no-break space\" or \"narrow no-break space\"\n\nTo negate a character class, put a C<-> after the opening angle bracket:\n\n    say 'no quotes' ~~ /  <-[ \" ]> + /;  # <-[\"]> matches any character except \"\n\nA common pattern for parsing quote-delimited strings involves negated\ncharacter classes:\n\n    say '\"in quotes\"' ~~ / '\"' <-[ \" ]> * '\"'/;\n\nThis regex first matches a quote, then any characters that aren't quotes, and\nthen a quote again. The meaning of C<*> and C<+> in the examples above are\nexplained in the next section on quantifiers.\n\nJust as you can use the C<-> for both set difference and negation of a\nsingle value, you can also explicitly put a C<+> in front:\n\n    / <+[123]> /  # same as <[123]>\n\n=head1 Quantifiers\n\nA quantifier makes the preceding atom match a variable number of times. For\nexample, C<a+> matches one or more C<a> characters.\n\nQuantifiers bind tighter than concatenation, so C<ab+> matches one C<a>\nfollowed by one or more C<b>s. This is different for quotes, so C<'ab'+>\nmatches the strings C<ab>, C<abab>, C<ababab> etc.\n\n=head2 X<One or more: C<+>|Regexes,+>\n\nThe C<+> quantifier makes the preceding atom match one or more times, with\nno upper limit.\n\nFor example, to match strings of the form C<key=value>, you can write a regex\nlike this:\n\n    / \\w+ '=' \\w+ /\n\n=head2 X<Zero or more: C<*>|Regexes,*>\n\nThe C<*> quantifier makes the preceding atom match zero or more times, with\nno upper limit.\n\nFor example, to allow optional whitespace between C<a> and C<b> you can write:\n\n    / a \\s* b /\n\n=head2 X<Zero or one: C<?>|Regexes,? (quantifier)>\n\nThe C<?> quantifier makes the preceding atom match zero or once.\n\nFor example, to match C<dog> or C<dogs>, you can write:\n\n    / dogs? /\n\n=head2 X<General quantifier: C<** min..max>|Regexes,**>\n\nTo quantify an atom an arbitrary number of times, use the C<**> quantifier,\nwhich takes a single L<C<Int>|/type/Int> or a L<C<Range>|/type/Range> on the\nright-hand side that specifies the number of times to match. If a\nL<C<Range>|/type/Range> is specified, the end-points specify the minimum and\nmaximum number of times to match.\n\n=begin code\nsay 'abcdefg' ~~ /\\w ** 4/;      # OUTPUT: «｢abcd｣␤»\nsay 'a'       ~~ /\\w **  2..5/;  # OUTPUT: «Nil␤»\nsay 'abc'     ~~ /\\w **  2..5/;  # OUTPUT: «｢abc｣␤»\nsay 'abcdefg' ~~ /\\w **  2..5/;  # OUTPUT: «｢abcde｣␤»\nsay 'abcdefg' ~~ /\\w ** 2^..^5/; # OUTPUT: «｢abcd｣␤»\nsay 'abcdefg' ~~ /\\w ** ^3/;     # OUTPUT: «｢ab｣␤»\nsay 'abcdefg' ~~ /\\w ** 1..*/;   # OUTPUT: «｢abcdefg｣␤»\n=end code\n\nOnly basic literal syntax for the right-hand side of the quantifier is\nsupported, to avoid ambiguities with other regex constructs. If you need to use\na more complex expression, for example, a L<C<Range>|/type/Range> made from\nvariables, enclose the L<C<Range>|/type/Range> in curly braces:\n\n    =begin code\n    my $start = 3;\n    say 'abcdefg' ~~ /\\w ** {$start .. $start+2}/; # OUTPUT: «｢abcde｣␤»\n    say 'abcdefg' ~~ /\\w ** {π.Int}/;              # OUTPUT: «｢abc｣␤»\n    =end code\n\nNegative values are treated like zero:\n\n    =begin code\n    say 'abcdefg' ~~ /\\w ** {-Inf}/;     # OUTPUT: «｢｣␤»\n    say 'abcdefg' ~~ /\\w ** {-42}/;      # OUTPUT: «｢｣␤»\n    say 'abcdefg' ~~ /\\w ** {-10..-42}/; # OUTPUT: «｢｣␤»\n    say 'abcdefg' ~~ /\\w ** {-42..-10}/; # OUTPUT: «｢｣␤»\n    =end code\n\nIf then, the resultant value is C<Inf> or C<NaN> or the resultant\nL<C<Range>|/type/Range> is empty, non-Numeric, contains C<NaN> end-points, or has\nminimum effective end-point as C<Inf>, the C<X::Syntax::Regex::QuantifierValue>\nexception will be thrown:\n\n    =begin code\n    (try say 'abcdefg' ~~ /\\w ** {42..10}/  )\n        orelse say ($!.^name, $!.empty-range);\n        # OUTPUT: «(X::Syntax::Regex::QuantifierValue True)␤»\n    (try say 'abcdefg' ~~ /\\w ** {Inf..Inf}/)\n        orelse say ($!.^name, $!.inf);\n        # OUTPUT: «(X::Syntax::Regex::QuantifierValue True)␤»\n    (try say 'abcdefg' ~~ /\\w ** {NaN..42}/ )\n        orelse say ($!.^name, $!.non-numeric-range);\n        # OUTPUT: «(X::Syntax::Regex::QuantifierValue True)␤»\n    (try say 'abcdefg' ~~ /\\w ** {\"a\"..\"c\"}/)\n        orelse say ($!.^name, $!.non-numeric-range);\n        # OUTPUT: «(X::Syntax::Regex::QuantifierValue True)␤»\n    (try say 'abcdefg' ~~ /\\w ** {Inf}/)\n        orelse say ($!.^name, $!.inf);\n        # OUTPUT: «(X::Syntax::Regex::QuantifierValue True)␤»\n    (try say 'abcdefg' ~~ /\\w ** {NaN}/)\n        orelse say ($!.^name, $!.non-numeric);\n        # OUTPUT: «(X::Syntax::Regex::QuantifierValue True)␤»\n    =end code\n\n=head2 X<Modified quantifier: C<%>, C<%%>|Regexes,%>\n\nX<|Regexes,%%>\nTo more easily match things like comma separated values, you can tack on a\nC<%> modifier to any of the above quantifiers to specify a separator that must\noccur between each of the matches. For example, C<a+ % ','> will match\nC<a> or C<a,a> or C<a,a,a>, etc.\n\nC<%%> is like C<%>, with the difference that it can optionally match trailing\ndelimiters as well. This means that besides C<a> and C<a,a>, it can also match\nC<a,> and C<a,a,>.\n\nThe quantifier interacts with C<%> and controls the number of overall\nrepetitions that can match successfully, so C<a* % ','> also matches the empty\nstring. If you want match words delimited by commas, you might need to nest an\nordinary and a modified quantifier:\n\n    =begin code\n    say so 'abc,def' ~~ / ^ [\\w+] ** 1 % ',' $ /;  # OUTPUT: «False␤»\n    say so 'abc,def' ~~ / ^ [\\w+] ** 2 % ',' $ /;  # OUTPUT: «True␤»\n    =end code\n\n=head2 Preventing backtracking: C<:>\n\nOne way to prevent L<backtracking|/language/regexes#Backtracking> is\nthrough the use of the C<ratchet> adverb as described\nL<below|/language/regexes#Ratchet>. Another more fine-grained way of preventing\nbacktracking in regexes is attaching a C<:> modifier to a quantifier:\n\n=begin code\nmy $str = \"ACG GCT ACT An interesting chain\";\nsay $str ~~ /<[ACGT\\s]>+ \\s+ (<[A..Z a..z \\s]>+)/;\n# OUTPUT: «｢ACG GCT ACT An interesting chain｣␤ 0 => ｢An interesting chain｣␤»\nsay $str ~~ /<[ACGT\\s]>+: \\s+ (<[A..Z a..z \\s]>+)/;\n# OUTPUT: «Nil␤»\n=end code\n\nIn the second case, the \"A\" in \"An\" had already been absorbed by the\npattern, preventing the matching of the second part of the pattern, after\nC<\\s+>. Generally we will want the opposite: prevent backtracking to match\nprecisely what we are looking for.\n\nIn most cases, you will want to prevent backtracking for efficiency reasons, for\ninstance here:\n\n=for code :preamble<my $str>\nsay $str ~~ m:g/[(<[ACGT]> **: 3) \\s*]+ \\s+ (<[A..Z a..z \\s]>+)/;\n# OUTPUT:\n# «(｢ACG GCT ACT An interesting chain｣\n# «0 => ｢ACG｣␤»\n# «0 => ｢GCT｣␤»\n# «0 => ｢ACT｣␤»\n# «1 => ｢An interesting chain｣)␤»\n\nAlthough in this case, eliminating the C<:> from behind C<**> would make it\nbehave exactly in the same way. The best use is to create I<tokens> that will\nnot be backtracked:\n\n    $_ = \"ACG GCT ACT IDAQT\";\n    say  m:g/[(\\w+:) \\s*]+ (\\w+) $$/;\n    # OUTPUT:\n    # «(｢ACG GCT ACT IDAQT｣␤»\n    # «0 => ｢ACG｣␤»\n    # «0 => ｢GCT｣␤»\n    # «0 => ｢ACT｣␤»\n    # «1 => ｢IDAQT｣)␤»\n\nWithout the C<:> following C<\\w+>, the I<ID> part captured would have been\nsimply C<T>, since the pattern would go ahead and match everything, leaving a\nsingle letter to match the C<\\w+> expression at the end of the line.\n\n=head2 X<Greedy versus frugal quantifiers: C<?>|Regexes,?>\n\nBy default, quantifiers request a greedy match:\n\n=for code\n'abababa' ~~ /a .* a/ && say ~$/;   # OUTPUT: «abababa␤»\n\n\nYou can attach a C<?> modifier to the quantifier to enable frugal\nmatching:\n\n=for code\n'abababa' ~~ /a .*? a/ && say ~$/;   # OUTPUT: «aba␤»\n\n\nYou can also enable frugal matching for general quantifiers:\n\n    say '/foo/o/bar/' ~~ /\\/.**?{1..10}\\//;  # OUTPUT: «｢/foo/｣␤»\n    say '/foo/o/bar/' ~~ /\\/.**!{1..10}\\//;  # OUTPUT: «｢/foo/o/bar/｣␤»\n\nGreedy matching can be explicitly requested with the C<!> modifier.\n\n=head1 X<Alternation: C<||>|Regexes,||>\n\nTo match one of several possible alternatives, separate them by C<||>; the\nfirst matching alternative wins.\n\nFor example, C<ini> files have the following form:\n\n=begin code :lang<text>\n[section]\nkey = value\n=end code\n\nHence, if you parse a single line of an C<ini> file, it can be either a\nsection or a key-value pair and the regex would be (to a first\napproximation):\n\n    / '[' \\w+ ']' || \\S+ \\s* '=' \\s* \\S* /\n\nThat is, either a word surrounded by square brackets, or a string of\nnon-whitespace characters, followed by zero or more spaces, followed by the\nequals sign C<=>, followed again by optional whitespace, followed by another\nstring of non-whitespace characters.\n\nAn empty string as the first branch is ignored, to allow you to format\nbranches consistently. You could have written the previous example as\n\n    /\n    || '[' \\w+ ']'\n    || \\S+ \\s* '=' \\s* \\S*\n    /\n\nEven in non-backtracking contexts, the alternation operator C<||> tries\nall the branches in order until the first one matches.\n\n=head1 X<Longest alternation: C<|>|Regexes,|>\n\nIn short, in regex branches separated by C<|>, the longest token match wins,\nindependent of the textual ordering in the regex. However, what C<|> really\ndoes is more than that.\nIt does not decide which branch wins after finishing the whole match,\nbut follows the L<longest-token matching (LTM) strategy|https://github.com/Raku/old-design-docs/blob/master/S05-regex.pod#Longest-token_matching>.\n\nBriefly, what C<|> does is this:\n\n=item1 First, select the branch which has the longest declarative prefix.\n\n    say \"abc\" ~~ /ab | a.* /;                 # OUTPUT: «⌜abc⌟␤»\n    say \"abc\" ~~ /ab | a {} .* /;             # OUTPUT: «⌜ab⌟␤»\n    say \"if else\" ~~ / if | if <.ws> else /;  # OUTPUT: «｢if｣␤»\n    say \"if else\" ~~ / if | if \\s+   else /;  # OUTPUT: «｢if else｣␤»\n\nAs is shown above, C<a.*> is a declarative prefix, while C<a {} .*> terminates\nat C<{}>, then its declarative prefix is C<a>. Note that non-declarative atoms\nterminate declarative prefix. This is quite important if you want to apply\nC<|> in a C<rule>, which automatically enables C<:s>, and C«<.ws>» accidentally\nterminates declarative prefix.\n\n=item1 If it's a tie, select the match with the highest specificity.\n\n    say \"abc\" ~~ /a. | ab { print \"win\" } /;  # OUTPUT: «win｢ab｣␤»\n\nWhen two alternatives match at the same length, the tie is broken by\nspecificity. That is, C<ab>, as an exact match, counts as closer than C<a.>,\nwhich uses character classes.\n\n=item1 If it's still a tie, use additional tiebreakers.\n\n    say \"abc\" ~~ /a\\w| a. { print \"lose\" } /; # OUTPUT: «⌜ab⌟␤»\n\nIf the tiebreaker above doesn't work, then the textually earlier alternative\ntakes precedence.\n\nFor more details, see\nL<the LTM strategy|https://github.com/Raku/old-design-docs/blob/master/S05-regex.pod#Longest-token_matching>.\n\n=head2 Quoted lists are LTM matches\n\nUsing a quoted list in a regex is equivalent to specifying the\nlongest-match alternation of the list's elements.  So, the following\nmatch:\n\n    say 'food' ~~ /< f fo foo food >/;      # OUTPUT: «｢food｣␤»\n\nis equivalent to:\n\n    say 'food' ~~ / f | fo | foo | food /;  # OUTPUT: «｢food｣␤»\n\nNote that the space after the first C«<» is significant here: C«<food>»\ncalls the named rule C<food> while C«< food >» and C«< food>» specify\nquoted lists with a single element, C<'food'>.\n\nIf the first branch is an empty string, it is ignored. This allows you to\nformat your regexes consistently:\n\n    /\n    | f\n    | fo\n    | foo\n    | food\n    /\n\nArrays can also be interpolated into a regex to achieve the same effect:\n\n    my @increasingly-edible = <f fo foo food>;\n    say 'food' ~~ /@increasingly-edible/;   # OUTPUT: «｢food｣␤»\n\nThis is documented further under L<Regex Interpolation|#Regex_interpolation>,\nbelow.\n\n=head1 X<Conjunction: C<&&>|Regexes,&&>\n\nMatches successfully if all C<&&>-delimited segments match the same substring\nof the target string. The segments are evaluated left to right.\n\nThis can be useful for augmenting an existing regex. For example if you have\na regex C<quoted> that matches a quoted string, then C</ <quoted> && <-[x]>* />\nmatches a quoted string that does not contain the character C<x>.\n\nNote that you cannot easily obtain the same behavior with a lookahead, that\nis, a regex that doesn't consume characters, because a lookahead doesn't stop\nlooking when the quoted string stops matching.\n\n    =begin code\n    say 'abc' ~~ / <?before a> && . /;    # OUTPUT: «Nil␤»\n    say 'abc' ~~ / <?before a> . && . /;  # OUTPUT: «｢a｣␤»\n    say 'abc' ~~ / <?before a> . /;       # OUTPUT: «｢a｣␤»\n    say 'abc' ~~ / <?before a> .. /;      # OUTPUT: «｢ab｣␤»\n    =end code\n\nJust like with C<||>, empty first branches are ignored.\n\n=head1 X<Conjunction: C<&>|Regexes,&>\n\nMuch like C<&&> in a Regexes, it matches successfully if all segments\nseparated by C<&> match the same part of the target string.\n\nC<&> (unlike C<&&>) is considered declarative, and notionally all the\nsegments can be evaluated in parallel, or in any order the compiler chooses.\n\nJust like with C<||> and C<&>, empty first branches are ignored.\n\n=head1 Anchors\n\nRegexes search an entire string for matches. Sometimes this is not what\nyou want. Anchors match only at certain positions in the string, thereby\nanchoring the regex match to that position.\n\n=head2 X<Start of string and end of string|Regexes,^>\n\nX<|Regexes,$>\nThe C<^> anchor only matches at the start of the string:\n\n    say so 'karakul'  ~~ /  raku/;    # OUTPUT: «True␤»\n    say so 'karakul'  ~~ /^ raku/;    # OUTPUT: «False␤»\n    say so 'rakuy'    ~~ /^ raku/;    # OUTPUT: «True␤»\n    say so 'raku'     ~~ /^ raku/;    # OUTPUT: «True␤»\n\nThe C<$> anchor only matches at the end of the string:\n\n    say so 'use raku' ~~ /  raku  /;   # OUTPUT: «True␤»\n    say so 'use raku' ~~ /  raku $/;   # OUTPUT: «True␤»\n    say so 'rakuy'    ~~ /  raku $/;   # OUTPUT: «False␤»\n\nYou can combine both anchors:\n\n    say so 'use raku' ~~ /^ raku $/;   # OUTPUT: «False␤»\n    say so 'raku'     ~~ /^ raku $/;   # OUTPUT: «True␤»\n\nKeep in mind that C<^> matches the start of a B<string>, not the start of\na B<line>. Likewise, C<$> matches the end of a B<string>, not the end of\na B<line>.\n\nThe following is a multi-line string:\n\n    my $str = chomp q:to/EOS/;\n       Keep it secret\n       and keep it safe\n       EOS\n\n    # 'safe' is at the end of the string\n    say so $str ~~ /safe   $/;   # OUTPUT: «True␤»\n\n    # 'secret' is at the end of a line, not the string\n    say so $str ~~ /secret $/;   # OUTPUT: «False␤»\n\n    # 'Keep' is at the start of the string\n    say so $str ~~ /^Keep   /;   # OUTPUT: «True␤»\n\n    # 'and' is at the start of a line -- not the string\n    say so $str ~~ /^and    /;   # OUTPUT: «False␤»\n\n=head2 X<Start of line and end of line|Regexes,^^>\n\nX<|Regexes,$$>\nThe C<^^> anchor matches at the start of a logical line. That is, either\nat the start of the string, or after a newline character. However, it does not\nmatch at the end of the string, even if it ends with a newline character.\n\nThe C<$$> anchor matches at the end of a logical line. That is, before a newline\ncharacter, or at the end of the string when the last character is not a\nnewline character.\n\nTo understand the following example, it's important to know that the\nC<q:to/EOS/...EOS> L<heredoc|/language/quoting#Heredocs:_:to> syntax removes\nleading indention to the same level as the C<EOS> marker, so that the first,\nsecond and last lines have no leading space and the third and fourth lines have\ntwo leading spaces each.\n\n    my $str = q:to/EOS/;\n        There was a young man of Japan\n        Whose limericks never would scan.\n          When asked why this was,\n          He replied \"It's because I always try to fit\n        as many syllables into the last line as ever I possibly can.\"\n        EOS\n\n    # 'There' is at the start of string\n    say so $str ~~ /^^ There/;        # OUTPUT: «True␤»\n\n    # 'limericks' is not at the start of a line\n    say so $str ~~ /^^ limericks/;    # OUTPUT: «False␤»\n\n    # 'as' is at start of the last line\n    say so $str ~~ /^^ as/;            # OUTPUT: «True␤»\n\n    # there are blanks between start of line and the \"When\"\n    say so $str ~~ /^^ When/;         # OUTPUT: «False␤»\n\n    # 'Japan' is at end of first line\n    say so $str ~~ / Japan $$/;       # OUTPUT: «True␤»\n\n    # there's a . between \"scan\" and the end of line\n    say so $str ~~ / scan $$/;        # OUTPUT: «False␤»\n\n    # matched at the last line\n    say so $str ~~ / '.\"' $$/;        # OUTPUT: «True␤»\n\n=head2 X«Word boundary|Regexes,<?wb>»\n\nX«|Regexes,<!wb>»\nTo match any word boundary, use C«<?wb>». This is similar to\nX«C<\\b>|Regexes,\\b» in other languages. To match the opposite, any\ncharacter that is not bounding a word, use C«<!wb>». This is similar\nto X«C<\\B>|Regexes,\\B» in other languages; C<\\b> and C<\\B> will\nthrow an L<C<X::Obsolete>|/type/X::Obsolete> exception from version 6.d of Raku.\n\nThese are both zero-width regex elements.\n\n    say \"two-words\" ~~ / two<?wb>\\-<?wb>words /;    # OUTPUT: «｢two-words｣␤»\n    say \"twowords\" ~~ / two<!wb><!wb>words /;     # OUTPUT: «｢twowords｣␤»\n\n=head2 Left and right word boundary\n\nX«|Regexes,<<»\nX«|Regexes,>>»\nX<|Regexes,«>\nX<|Regexes,»>\nC«<<» matches a left word boundary. It matches positions where there is a\nnon-word character at the left, or the start of the string, and a word\ncharacter to the right.\n\nC«>>» matches a right word boundary. It matches positions where there\nis a word character at the left and a non-word character at the right, or\nthe end of the string.\n\nThese are both zero-width regex elements.\n\n    my $str = 'The quick brown fox';\n    say so ' ' ~~ /\\W/;               # OUTPUT: «True␤»\n    say so $str ~~ /br/;              # OUTPUT: «True␤»\n    say so $str ~~ /<< br/;           # OUTPUT: «True␤»\n    say so $str ~~ /br >>/;           # OUTPUT: «False␤»\n    say so $str ~~ /own/;             # OUTPUT: «True␤»\n    say so $str ~~ /<< own/;          # OUTPUT: «False␤»\n    say so $str ~~ /own >>/;          # OUTPUT: «True␤»\n    say so $str ~~ /<< The/;          # OUTPUT: «True␤»\n    say so $str ~~ /fox >>/;          # OUTPUT: «True␤»\n\nYou can also use the variants C<«> and C<»> :\n\n    my $str = 'The quick brown fox';\n    say so $str ~~ /« own/;          # OUTPUT: «False␤»\n    say so $str ~~ /own »/;          # OUTPUT: «True␤»\n\nTo see the difference between C«<?wb>» and C<«>, C<»>:\n\n    say \"stuff here!!!\".subst(:g, />>/, '|');   # OUTPUT: «stuff| here|!!!␤»\n    say \"stuff here!!!\".subst(:g, /<</, '|');   # OUTPUT: «|stuff |here!!!␤»\n    say \"stuff here!!!\".subst(:g, /<?wb>/, '|'); # OUTPUT: «|stuff| |here|!!!␤»\n\n=head2 Summary of anchors\n\nAnchors are zero-width regex elements. Hence they do not use up a character of\nthe input string, that is, they do not advance the current position at which\nthe regex engine tries to match. A good mental model is that they match between\ntwo characters of an input string, or before the first, or after the last\ncharacter of an input string.\n\n=begin table\n\n    Anchor   | Description         | Examples\n    =========+=====================+=================\n    ^        | Start of string     | \"⏏two\\nlines\"\n    ^^       | Start of line       | \"⏏two\\n⏏lines\"\n    $        | End of string       | \"two\\nlines⏏\"\n    $$       | End of line         | \"two⏏\\nlines⏏\"\n    << or «  | Left word boundary  | \"⏏two ⏏words\"\n    >> or »  | Right word boundary | \"two⏏ words⏏\"\n    <?wb>    | Any word boundary   | \"⏏two⏏ ⏏words⏏~!\"\n    <!wb>    | Not a word boundary | \"t⏏w⏏o w⏏o⏏r⏏d⏏s~⏏!\"\n    <?ww>    | Within word         | \"t⏏w⏏o w⏏o⏏r⏏d⏏s~!\"\n    <!ww>    | Not within word     | \"⏏two⏏ ⏏words⏏~⏏!⏏\"\n    <at(n)>  | After nth character | \"abc⏏de\" for <at(3)>\n    <!at(n)> | Not after nth char  | \"⏏a⏏b⏏cd⏏e\" for <!at(3)>\n\n=end table\n\n=head1 Zero-width assertions\n\nZero-Width assertions can help you implement your own anchor: it turns another\nregex into an anchor, making them consume no characters of the input string.\nThere are two variants: lookahead and lookbehind assertions.\n\nTechnically, anchors are also zero-width assertions, and they can look\nboth ahead and behind.\n\n=head2 X«Lookaround assertions|Regexes,positive lookaround assertion <?>»\n\nX«|Regexes,negative lookaround assertion <!>»\nX«|Regexes,?[»\nLookaround assertions, which need a character class in its simpler form, work\nboth ways. They match, but they don't consume a\ncharacter.\n\n=begin code\nmy regex key {^^ <![#-]> \\d+ }\nsay \"333\" ~~ &key;                  # OUTPUT: «｢333｣␤»\nsay '333$' ~~ m/ \\d+ <?[$]>/;       # OUTPUT: «｢333｣␤»\nsay '$333' ~~ m/^^ <?[$]> . \\d+ /;  # OUTPUT: «｢$333｣␤»\n=end code\n\nThey can be positive or negative: C<![]> is negative, while C<?[]> is\npositive; the square brackets will contain the characters or backslashed\ncharacter classes that are going to be matched.\n\nYou can use predefined character classes and Unicode properties directly\npreceded by the exclamation or interrogation mark to convert them into\nlookaround assertions.:\n\n=for code\nsay '333' ~~ m/^^ <?alnum> \\d+ /;          # OUTPUT: «｢333｣␤»\nsay '333' ~~ m/^^ <?:Nd> \\d+ /;            # OUTPUT: «｢333｣␤»\nsay '333' ~~ m/^^ <!:L> \\d+ /;             # OUTPUT: «｢333｣␤»\nsay '333' ~~ m/^^ \\d+ <!:Script<Tamil>> /; # OUTPUT: «｢33｣␤»\n\n\nIn the first two cases, the corresponding character class matches, but does not\nconsume,\nthe first digit, which is then consumed by the expression; in the third, the\nnegative lookaround assertion behaves in the same way. In the fourth\nstatement the last digit is matched but not consumed, thus the match includes\n only the first two digits.\n\nThe inbuilt named assertion C«<same>» also works like a lookaround assertion:\nIt requires that the next and previous character are the same,\nbut consumes none of them.\n\n=for code\nsay '123345' ~~ m/ <same>\\d+ /;          # OUTPUT: «｢345｣␤ same => ｢｣␤»\nsay 'aa11' ~~ m/ <alpha><same><digit> /; # OUTPUT: «False␤»\n\n\n=head2 X«Lookahead assertions|Regexes,before»\n\nX«|Regexes,<?before>»\nTo check that a pattern appears before another pattern, use a\nlookahead assertion via the C<before> assertion. This has the form:\n\n    <?before pattern>\n\nThus, to search for the string C<foo> which is immediately followed by the\nstring C<bar>, use the following regexp:\n\n    / foo <?before bar> /\n\nFor example:\n\n    say \"foobar\" ~~ / foo <?before bar> /;  # OUTPUT: «foo␤»\n\nHowever, if you want to search for a pattern which is B<not> immediately\nfollowed by some pattern, then you need to use a negative lookahead\nassertion, this has the form:\n\n    <!before pattern>\n\nIn the following example, all occurrences of C<foo> which is not before\nC<bar> would match with\n\n    say \"foobaz\" ~~ / foo <!before bar> /;  # OUTPUT: «foo␤»\n\nLookahead assertions can be used also with other patterns, like characters\nranges, interpolated variables subscripts and so on. In such cases it does\nsuffice to use a C<?>, or a C<!> for the negate form. For instance, the\nfollowing lines all produce the very same result:\n\n    say 'abcdefg' ~~ rx{ abc <?before def> };        # OUTPUT: «｢abc｣␤»\n    say 'abcdefg' ~~ rx{ abc <?[ d..f ]> };          # OUTPUT: «｢abc｣␤»\n    my @ending_letters = <d e f>;\n    say 'abcdefg' ~~ rx{ abc <?@ending_letters> };   # OUTPUT: «｢abc｣␤»\n\nMetacharacters can also be used in lookahead or -behind assertions.\n\n    say \"First. Second\" ~~ m:g/ <?after ^^ | \".\" \\s+> <:Lu>\\S+ /\n    # OUTPUT: «(｢First.｣ ｢Second｣)␤»\n\nA practical use of lookahead assertions is in substitutions, where\nyou only want to substitute regex matches that are in a certain\ncontext. For example, you might want to substitute only numbers\nthat are followed by a unit (like I<kg>), but not other numbers:\n\n    my @units = <kg m km mm s h>;\n    $_ = \"Please buy 2 packs of sugar, 1 kg each\";\n    s:g[\\d+ <?before \\s* @units>] = 5 * $/;\n    say $_;         # OUTPUT: «Please buy 2 packs of sugar, 5 kg each␤»\n\nSince the lookahead is not part of the match object, the unit\nis not substituted.\n\n=head2 X«Lookbehind assertions|Regexes,after»\n\nX«|Regexes,<?after>»\nTo check that a pattern appears after another pattern, use a\nlookbehind assertion via the C<after> assertion. This has the form:\n\n    <?after pattern>\n\nTherefore, to search for the string C<bar> immediately preceded by the\nstring C<foo>, use the following regexp:\n\n    / <?after foo> bar /\n\nFor example:\n\n    say \"foobar\" ~~ / <?after foo> bar /;   # OUTPUT: «bar␤»\n\nHowever, if you want to search for a pattern which is B<not> immediately\npreceded by some pattern, then you need to use a negative lookbehind\nassertion, this has the form:\n\n    <!after pattern>\n\nHence all occurrences of C<bar> which do not have C<foo> before them\nwould be matched by\n\n    say \"fotbar\" ~~ / <!after foo> bar /;    # OUTPUT: «bar␤»\n\nThese are, as in the case of lookahead, zero-width assertions which do not I<consume> characters, like here:\n\n    say \"atfoobar\" ~~ / (.**3) .**2 <?after foo> bar /;\n    # OUTPUT: «｢atfoobar｣␤ 0 => ｢atf｣␤»\n\nwhere we capture the first 3 of the 5 characters before bar, but only if C<bar>\nis preceded by C<foo>. The fact that the assertion is zero-width allows us to\nuse part of the characters in the assertion for capture.\n\n\n\n=head1 Grouping and capturing\n\nIn regular (non-regex) Raku, you can use parentheses to group things\ntogether, usually to override operator precedence:\n\n    say 1 + 4 * 2;     # OUTPUT: «9␤», parsed as 1 + (4 * 2)\n    say (1 + 4) * 2;   # OUTPUT: «10␤»\n\nThe same grouping facility is available in regexes:\n\n    / a || b c /;      # matches 'a' or 'bc'\n    / ( a || b ) c /;  # matches 'ac' or 'bc'\n\nThe same grouping applies to quantifiers:\n\n    / a b+ /;          # matches an 'a' followed by one or more 'b's\n    / (a b)+ /;        # matches one or more sequences of 'ab'\n    / (a || b)+ /;     # matches a string of 'a's and 'b's, except empty string\n\nAn unquantified capture produces a L<C<Match>|/type/Match> object. When a capture\nis quantified (except with the C<?> quantifier) the capture becomes a list of\nL<C<Match>|/type/Match> objects instead.\n\n=head2 X«Capturing|Regexes,( )»\n\nThe round parentheses don't just group, they also I<capture>; that is, they\nmake the string matched within the group available as a variable, and also as\nan element of the resulting L<C<Match>|/type/Match> object:\n\n    my $str =  'number 42';\n    if $str ~~ /'number ' (\\d+) / {\n        say \"The number is $0\";         # OUTPUT: «The number is 42␤»\n        # or\n        say \"The number is $/[0]\";      # OUTPUT: «The number is 42␤»\n    }\n\nPairs of parentheses are numbered left to right, starting from zero.\n\n    if 'abc' ~~ /(a) b (c)/ {\n        say \"0: $0; 1: $1\";             # OUTPUT: «0: a; 1: c␤»\n    }\n\nThe C<$0> and C<$1> etc. syntax is shorthand. These captures\nare canonically available from the match object C<$/> by using it as a list,\nso C<$0> is actually syntactic sugar for C<$/[0]>.\n\nCoercing the match object to a list gives an easy way to programmatically\naccess all elements:\n\n    if 'abc' ~~ /(a) b (c)/ {\n        say $/.list.join: ', '  # OUTPUT: «a, c␤»\n    }\n\n=head2 X«Non-capturing grouping|Regexes,[ ]»\n\nThe parentheses in regexes perform a double role: they group the regex\nelements inside and they capture what is matched by the sub-regex inside.\n\nTo get only the grouping behavior, you can use square brackets C<[ ... ]>\nwhich, by default, don't capture.\n\n    if 'abc' ~~ / [a||b] (c) / {\n        say ~$0;                # OUTPUT: «c␤»\n    }\n\nIf you do not need the captures, using non-capturing C<[ ... ]>\ngroups provides the following benefits:\n=item  they more cleanly communicate the regex intent,\n=item  they make it easier to count the capturing groups that do match, and\n=item  they make matching a bit faster.\n\n=head2 Capture numbers\n\nIt is stated above that captures are numbered from left to right. While true\nin principle, this is also an over simplification.\n\nThe following rules are listed for the sake of completeness. When you find\nyourself using them regularly, it's worth considering named captures (and\npossibly subrules) instead.\n\nAlternations reset the capture count:\n\n    / (x) (y)  || (a) (.) (.) /\n    # $0  $1      $0  $1  $2\n\nExample:\n\n    if 'abc' ~~ /(x)(y) || (a)(.)(.)/ {\n        say ~$1;        # OUTPUT: «b␤»\n    }\n\nIf two (or more) alternations have a different number of captures,\nthe one with the most captures determines the index of the next capture:\n\n    if 'abcd' ~~ / a [ b (.) || (x) (y) ] (.) / {\n        #                 $0     $0  $1    $2\n        say ~$2;            # OUTPUT: «d␤»\n    }\n\nCaptures can be nested, in which case they are numbered per level; level 0 gets\nto use the capture variables, but it will become a list with the rest of the\nlevels behaving as elements of that list\n\n    if 'abc' ~~ / ( a (.) (.) ) / {\n        say \"Outer: $0\";                # OUTPUT: «Outer: abc␤»\n        say \"Inner: $0[0] and $0[1]\";   # OUTPUT: «Inner: b and c␤»\n    }\n\nThese capture variables are only available outside the regex.\n\n=begin code\n# !!WRONG!! The $0 refers to a capture *inside* the second capture\nsay \"11\" ~~ /(\\d) ($0)/; # OUTPUT: «Nil␤»\n=end code\n\nIn order to make them available inside the Regexes, you need to insert a code\nblock behind the match; this code block may be empty if there's nothing\nmeaningful to do:\n\n=begin code\n# CORRECT: $0 is saved into a variable outside the second capture\n# before it is used inside\nsay \"11\" ~~ /(\\d) {} :my $c = $0; ($c)/; # OUTPUT: «｢11｣␤ 0 => ｢1｣␤ 1 => ｢1｣␤»\nsay \"Matched $c\"; # OUTPUT: «␤Matched 1␤»\n=end code\n\nThis code block I<publishes> the capture inside the regex, so that it can be\nassigned to other variables or used for subsequent matches\n\n=for code\nsay \"11\" ~~ /(\\d) {} $0/; # OUTPUT: «｢11｣␤ 0 => ｢1｣␤»\n\n\nX<|Regexes,:my>\nC<:my> helps scoping the C<$c> variable within the regex and beyond; in this\ncase we can use it in the next sentence to show what has been matched inside the\nregex. This can be used for debugging inside regular expressions, for instance:\n\n    my $paragraph=\"line\\nline2\\nline3\";\n    $paragraph ~~ rx| :my $counter = 0; ( \\V* { ++$counter } ) *%% \\n |;\n    say \"Matched $counter lines\"; # OUTPUT: «Matched 3 lines␤»\n\nSince C<:my> blocks are simply declarations, the match variable C<$/> or\nnumbered matches such as C<$0> will not be available in them unless they are\npreviously I<published> by inserting the empty block (or any block):\n\n=for code\n\"aba\" ~~ / (a) b {} :my $c = $/; /;\nsay $c; # OUTPUT: «｢ab｣␤ 0 => ｢a｣␤»\n\nAny other code block will also reveal the variables and make them available in\ndeclarations:\n\n=for code\n\"aba\" ~~ / (a) {say \"Check so far \", ~$/} b :my $c = ~$0; /;\n# OUTPUT: «Check so far a␤»\nsay \"Capture $c\"; # OUTPUT: «Capture a␤»\n\nX<|Regexes,:our>\nThe C<:our>, similarly to L<C<our>|/syntax/our> in classes, can be used in\nL<C<Grammar>|/type/Grammar>s to declare variables that can be accessed, via its\nfully qualified name, from outside the grammar:\n\n=begin code\ngrammar HasOur {\n    token TOP {\n        :our $our = 'Þor';\n        $our \\s+ is \\s+ mighty\n    }\n}\n\nsay HasOur.parse('Þor is mighty'); # OUTPUT: «｢Þor is mighty｣␤»\nsay $HasOur::our;                  # OUTPUT: «Þor␤»\n=end code\n\nOnce the parsing has been done successfully, we use the L<FQN name|/syntax/FQN> of the C<$our>\nvariable to access its value, that can be none other than C<Þor>.\n\n=head2 X<Named captures|Regexes,Named captures>\n\nInstead of numbering captures, you can also give them names. The generic,\nand slightly verbose, way of naming captures is like this:\n\n    if 'abc' ~~ / $<myname> = [ \\w+ ] / {\n        say ~$<myname>      # OUTPUT: «abc␤»\n    }\n\nThe square brackets in the above example, which don't usually capture, will now\ncapture its grouping with the given name.\n\nThe access to the named capture, C«$<myname>», is a shorthand for indexing\nthe match object as a hash, in other words: C<$/{ 'myname' }> or C«$/<myname>».\n\nWe can also use parentheses in the above example, but they will work exactly the\nsame as square brackets. The captured group will only be accessible by its name\nas a key from the match object and not from its position in the list with\nC<$/[0]> or C<$0>.\n\nNamed captures can also be nested using regular capture group syntax:\n\n    if 'abc-abc-abc' ~~ / $<string>=( [ $<part>=[abc] ]* % '-' ) / {\n        say ~$<string>;          # OUTPUT: «abc-abc-abc␤»\n        say ~$<string><part>;    # OUTPUT: «abc abc abc␤»\n        say ~$<string><part>[0]; # OUTPUT: «abc␤»\n    }\n\nCoercing the match object to a hash gives you easy programmatic access to\nall named captures:\n\n    if 'count=23' ~~ / $<variable>=\\w+ '=' $<value>=\\w+ / {\n        my %h = $/.hash;\n        say %h.keys.sort.join: ', ';        # OUTPUT: «value, variable␤»\n        say %h.values.sort.join: ', ';      # OUTPUT: «23, count␤»\n        for %h.kv -> $k, $v {\n            say \"Found value '$v' with key '$k'\";\n            # outputs two lines:\n            #   Found value 'count' with key 'variable'\n            #   Found value '23' with key 'value'\n        }\n    }\n\nA more convenient way to get named captures is by using named regex as discussed in\nthe L<Subrules|/language/regexes#Subrules> section.\n\n=head2 X«Capture markers: C«<( )>»|Regexes,<( )>»\n\nA C«<(» token indicates the start of the match's overall capture, while the\ncorresponding C«)>» token indicates its endpoint. The C«<(» is similar to other\nlanguages X<\\K|Regexes,\\K> to discard any matches found before the\nC<\\K>.\n\n    say 'abc' ~~ / a <( b )> c/;            # OUTPUT: «｢b｣␤»\n    say 'abc' ~~ / <(a <( b )> c)>/;        # OUTPUT: «｢bc｣␤»\n\nAs in the example above, you can see C«<(» sets the start point and C«)>» sets\nthe endpoint; since they are actually independent of each other, the inner-most\nstart point wins (the one attached to C<b>) and the outer-most end wins (the one\nattached to C<c>).\n\n=head1 Substitution\n\nRegular expressions can also be used to substitute one piece of text for\nanother. You can use this for anything, from correcting a spelling error\n(e.g., replacing 'Perl Jam' with 'Pearl Jam'), to reformatting an ISO8601\ndate from C<yyyy-mm-ddThh:mm:ssZ> to C<mm-dd-yy h:m {AM,PM}> and beyond.\n\nJust like the search-and-replace editor's dialog box, the C<s/ / /> operator\nhas two sides, a left and right side. The left side is where your matching\nexpression goes, and the right side is what you want to replace it with.\n\n=head2 X<Lexical conventions|Syntax,s/ / />\n\nSubstitutions are written similarly to matching, but the substitution operator\nhas both an area for the regex to match, and the text to substitute:\n\n    =begin code :preamble<my $str;>\n    s/replace/with/;           # a substitution that is applied to $_\n    $str ~~ s/replace/with/;   # a substitution applied to a scalar\n    =end code\n\nThe substitution operator allows delimiters other than the slash:\n\n    s|replace|with|;\n    s!replace!with!;\n    s,replace,with,;\n\nNote that neither the colon C<:> nor balancing delimiters such as C<{}> or\nC<()> can be substitution delimiters. Colons clash with adverbs such as\nC<s:i/Foo/bar/> and the other delimiters are used for other purposes.\n\nIf you use balancing curly braces, square brackets, or parentheses, the\nsubstitution works like this instead:\n\n    =begin code :preamble<my $str;>\n    s[replace] = 'with';\n    $str ~~ s[replace] = 'with';\n    =end code\n\nThe right-hand side of the equal sign is now a (not quoted) Raku expression,\nin which C<$/> is available as the current match:\n\n    $_ = 'some 11 words 21';\n    s:g[ \\d+ ] =  2 * $/;\n    .say;                    # OUTPUT: «some 22 words 42␤»\n\nLike the C<m//> operator, whitespace is ignored in the regex part of a\nsubstitution.\n\n=head2 Replacing string literals\n\nThe simplest thing to replace is a string literal. The string you want to\nreplace goes on the left-hand side of the substitution operator, and the string\nyou want to replace it with goes on the right-hand side; for example:\n\n    $_ = 'The Replacements';\n    s/Replace/Entrap/;\n    .say;                    # OUTPUT: «The Entrapments␤»\n\nAlphanumeric characters and the underscore are literal matches, just as in its\ncousin the C<m//> operator. All other characters must be escaped with a\nbackslash C<\\> or included in quotes:\n\n    $_ = 'Space: 1999';\n    s/Space\\:/Party like it's/;\n    .say                        # OUTPUT: «Party like it's 1999␤»\n\nNote that the matching restrictions generally only apply to the left-hand side of the\nsubstitution expression, but some special characters or combinations of them may need\nto be escaped in the right-hand side (RHS). For example\n\n    $_ = 'foo';\n    s/foo/\\%(/;\n    .say        # OUTPUT: «%(␤»\n\nor escape the '(' instead for the same result\n\n    s/foo/%\\(/;\n    .say        # OUTPUT: «%(␤»\n\nbut using either character alone does not require escaping. Forward slashes will need\nto be escaped, but escaping alphanumeric characters will cause them to be ignored. (NOTE:\nThis RHS limitation was only recently noticed and this is not yet an exhaustive list of all characters\nor character pairs that require escapes for the RHS.)\n\nBy default, substitutions are only done on the first match:\n\n    $_ = 'There can be twly two';\n    s/tw/on/;                     # replace 'tw' with 'on' once\n    .say;                         # OUTPUT: «There can be only two␤»\n\n=head2 Wildcards and character classes\n\nAnything that can go into the C<m//> operator can go into the left-hand side\nof the substitution operator, including wildcards and character classes. This\nis handy when the text you're matching isn't static, such as trying to match\na number in the middle of a string:\n\n    $_ = \"Blake's 9\";\n    s/\\d+/7/;         # replace any sequence of digits with '7'\n    .say;             # OUTPUT: «Blake's 7␤»\n\nOf course, you can use any of the C<+>, C<*> and C<?> modifiers, and they'll\nbehave just as they would in the C<m//> operator's context.\n\n=head2 Capturing groups\n\nJust as in the match operator, capturing groups are allowed on the left-hand\nside, and the matched contents populate the C<$0>..C<$n> variables and the\nC<$/> object:\n\n    $_ = '2016-01-23 18:09:00';\n    s/ (\\d+)\\-(\\d+)\\-(\\d+) /today/;   # replace YYYY-MM-DD with 'today'\n    .say;                             # OUTPUT: «today 18:09:00␤»\n    \"$1-$2-$0\".say;                   # OUTPUT: «01-23-2016␤»\n    \"$/[1]-$/[2]-$/[0]\".say;          # OUTPUT: «01-23-2016␤»\n\nAny of these variables C<$0>, C<$1>, C<$/> can be used on the right-hand side\nof the operator as well, so you can manipulate what you've just matched. This\nway you can separate out the C<YYYY>, C<MM> and C<DD> parts of a date and\nreformat them into C<MM-DD-YYYY> order:\n\n    $_ = '2016-01-23 18:09:00';\n    s/ (\\d+)\\-(\\d+)\\-(\\d+) /$1-$2-$0/;    # transform YYYY-MM-DD to MM-DD-YYYY\n    .say;                                 # OUTPUT: «01-23-2016 18:09:00␤»\n\nNamed capture can be used too:\n\n    $_ = '2016-01-23 18:09:00';\n    s/ $<y>=(\\d+)\\-$<m>=(\\d+)\\-$<d>=(\\d+) /$<m>-$<d>-$<y>/;\n    .say;                                 # OUTPUT: «01-23-2016 18:09:00␤»\n\nSince the right-hand side is effectively a regular Raku interpolated string,\nyou can reformat the time from C<HH:MM> to C<h:MM {AM,PM}> like so:\n\n    $_ = '18:38';\n    s/(\\d+)\\:(\\d+)/{$0 % 12}\\:$1 {$0 < 12 ?? 'AM' !! 'PM'}/;\n    .say;                                 # OUTPUT: «6:38 PM␤»\n\nUsing the modulo C<%> operator above keeps the sample code under 80 characters,\nbut is otherwise the same as C«$0 < 12 ?? $0 !! $0 - 12». When combined with\nthe power of the Parser Expression Grammars that B<really> underlies what\nyou're seeing here, you can use \"regular expressions\" to parse pretty much any\ntext out there.\n\n=head2 Common adverbs\n\nThe full list of adverbs that you can apply to regular expressions can be found\nelsewhere in this document (section L<Adverbs|#Adverbs>), but the most\ncommon are probably C<:g> and C<:i>.\n\n=item Global adverb C<:g>\n\nOrdinarily, matches are only made once in a given string, but adding the\nC<:g> modifier overrides that behavior, so that substitutions are made\neverywhere possible. Substitutions are non-recursive; for example:\n\n    $_ = q{I can say \"banana\" but I don't know when to stop};\n    s:g/na/nana,/;    # substitute 'nana,' for 'na'\n    .say;             # OUTPUT: «I can say \"banana,nana,\" but I don't ...␤»\n\nHere, C<na> was found twice in the original string and each time there was a\nsubstitution. The substitution only\napplied to the original string, though. The resulting string was not impacted.\n\n=item Insensitive adverb C<:i>\n\nOrdinarily, matches are case-sensitive. C<s/foo/bar/> will only match\nC<'foo'> and not C<'Foo'>. If the adverb C<:i> is used, though, matches become\ncase-insensitive.\n\n    $_ = 'Fruit';\n    s/fruit/vegetable/;\n    .say;                          # OUTPUT: «Fruit␤»\n\n    s:i/fruit/vegetable/;\n    .say;                          # OUTPUT: «vegetable␤»\n\nFor more information on what these adverbs are actually\ndoing, refer to the L<Adverbs|#Adverbs> section of this document.\n\nThese are just a few of the transformations you can apply with the substitution\noperator. Some of the simpler uses in the real world include removing personal\ndata from log files, editing MySQL timestamps into PostgreSQL format, changing\ncopyright information in HTML files and sanitizing form fields in a web\napplication.\n\nAs an aside, novices to regular expressions often get overwhelmed and think\nthat their regular expression needs to match every piece of data in the line,\nincluding what they want to match. Write just enough to match the data you're\nlooking for, no more, no less.\n\n=head2 X«C<S///> non-destructive substitution|Regexes,S/// non-destructive substitution»\n\n    say S/o .+ d/new/ with 'old string';      # OUTPUT: «new string␤»\n    S:g/« (.)/$0.uc()/.say for <foo bar ber>; # OUTPUT: «Foo␤Bar␤Ber␤»\n\nC<S///> uses the same semantics as the C<s///> operator, except\nit leaves the original string intact\nand I<returns the resultant string> instead of C<$/> (C<$/> still being set\nto the same values as with C<s///>).\n\nB<Note:> since the result is obtained as a return value, using this\noperator with the C<~~> smartmatch operator is a mistake and will issue a\nwarning. To execute the substitution on a variable that isn't the C<$_> this\noperator uses, alias it to C<$_> with C<given>, C<with>, or any other way.\nAlternatively, use the L«C<.subst> method|/routine/subst».\n\n=head1 X<Subrules|Syntax,regex>\n\nJust like you can put pieces of code into subroutines, you can also put\npieces of regex into named rules.\n\n    my regex line { \\N*\\n }\n    if \"abc\\ndef\" ~~ /<line> def/ {\n        say \"First line: \", $<line>.chomp;      # OUTPUT: «First line: abc␤»\n    }\n\nA named regex can be declared with C<my regex named-regex { body here }>, and\ncalled with C«<named-regex>». At the same time, calling a named regex\ninstalls a named capture with the same name.\n\nTo give the capture a different name from the regex, use the syntax\nC«<capture-name=named-regex>». If no capture is desired, a leading dot\nor ampersand will suppress it: C«<.named-regex>» if it is a method\ndeclared in the same class or grammar, C«<&named-regex>» for a regex\ndeclared in the same lexical context.\n\nHere's more complete code for parsing C<ini> files:\n\n    my regex header { \\s* '[' (\\w+) ']' \\h* \\n+ }\n    my regex identifier  { \\w+ }\n    my regex kvpair { \\s* <key=identifier> '=' <value=identifier> \\n+ }\n    my regex section {\n        <header>\n        <kvpair>*\n    }\n\n    my $contents = q:to/EOI/;\n        [passwords]\n            jack=password1\n            joy=muchmoresecure123\n        [quotas]\n            jack=123\n            joy=42\n    EOI\n\n    my %config;\n    if $contents ~~ /<section>*/ {\n        for $<section>.list -> $section {\n            my %section;\n            for $section<kvpair>.list -> $p {\n                %section{ $p<key> } = ~$p<value>;\n            }\n            %config{ $section<header>[0] } = %section;\n        }\n    }\n    say %config.raku;\n\n    # OUTPUT: «{:passwords(${:jack(\"password1\"), :joy(\"muchmoresecure123\")}),\n    #           :quotas(${:jack(\"123\"), :joy(\"42\")})}»\n\nNamed regexes can and should be grouped in L<grammars|/language/grammars>. A\nlist of predefined subrules is L<here|#Predefined_character_classes>.\n\n=head2 X<Regexes with signatures|Syntax,Parameterised regexes>\n\nRegexes are a subclass of the Code, Routine, and Method classes.\nThat is, they are callable objects with all the characteristics of\nsubroutines/methods...including the characteristic of having a signature.\n\nWhen a regex is declared with an explicit signature, it can (and must) then be called\nwith the equivalent number and type of arguments, using the in-regex syntax:\n\n    <regexname:  arg, list, here >\n\nThe arguments passed to the regex can be of I<any> type, and are accessible within\nthe regex's body via the corresponding parameter variable. For example:\n=begin code\n    my regex demo ($param) {\n        foo             # First match 'foo'\n        { say $param }  # Then show the value that was passed in\n        bar             # Then match 'bar'\n    }\n\n    'foobar' ~~ / <demo: { key => <v a l> }> /  # say prints: {key => (v a l)}\n=end code\n\nOf course, we rarely pass complex arguments into regexes just to print them out.\nMostly we pass arguments that help us configure the regex to match something.\nThat means we most often pass strings or other regexes (but see below for other uses).\n\nThe parameter variables of the regex's signature can be used within the regex body\nin any way that any other variable can be used within a regex. For example, you can\npass a L<(string)|/type/Str> argument and then have it match literally within the regex:\n=begin code\n    #                     vvvvvvvvv\n    my regex prefixed_int ($prefix) {   # Pass desired prefix into regex\n        $prefix                         # First match that specified prefix (literally)\n        \\d+                             # Then match digits\n    }\n\n    'inc123' ~~ / <prefixed_int: 'inc' > /;       # Matches\n    'inc456' ~~ / <prefixed_int: 'dec' > /;       # Doesn't match\n    'dec789' ~~ / <prefixed_int: 'dec' > /;       # Matches\n    #                            ^^^^^\n=end code\n\nOr you can pass a L<(regex)|/type/Regex> argument and have it match like a regex:\n\n=begin code\n    my regex prefixed_int ($prefix) {   # Pass desired prefix into regex\n        $prefix                         # First match that specified prefix\n        \\d+                             # Then match digits\n    }\n\n    'inc123' ~~ / <prefixed_int: /i<alpha>+/ > /;    # Matches\n    'inc456' ~~ / <prefixed_int: /d<alpha>+/ > /;    # Doesn't match\n    'dec789' ~~ / <prefixed_int: /d<alpha>+/ > /;    # Matches\n    #                            ^^^^^^^^^^^\n=end code\n\nOf course, if you definitely want users to pass a regex there\n(i.e. not a string or anything else), then you can specify\nthat constraint in the signature:\n\n=begin code\n    #                      vvvvv\n    my regex prefixed_int (Regex $prefix) {\n        $prefix     # First match the specified prefix\n        \\d+           # Then digits\n    }\n\n    'inc123' ~~ / <prefixed_int: /i<alpha>+/ > /;      # Matches\n    'inc456' ~~ / <prefixed_int: /d<alpha>+/ > /;      # Doesn't match\n    'dec789' ~~ / <prefixed_int: 'dec'       > /;      # Dies (parameter type mismatch)\n=end code\n\nAlternatively, you could use the C«<{...}>» \"match-like-a-regex\" construct\nto ensure that the contents of the parameter are...well...matched like a regex:\n\n=begin code\n    my regex prefix_int ($prefix) {\n    #   vvvvvvvvvvv\n        <{$prefix}>     # First match prefix (as a regex)\n        \\d+             # Then match digits\n    }\n\n    '123'    ~~ / <prefix_int: /abc/ > /;      # Doesn't match\n    'abc456' ~~ / <prefix_int: /abc/ > /;      # Matches\n    'abc456' ~~ / <prefix_int: /def/ > /;      # Doesn't match\n=end code\n\nYou can also use a parameter in the C«<?{...}>» and C«<!{...}>» Boolean-condition-check constructs,\nto enable users to switch certain matches on or off. For example:\n\n=begin code\n    my regex maybe_prefixed_num ($require-prefix) {\n        ^                                  # From start of string\n        # vvvvvvvvvvvvvvvvvvvv\n        [ <?{$require-prefix}> <alpha>+    # First match prefix (if required)\n        | <!{$require-prefix}>             # Or skip (if not required)\n        ]\n        \\d+                                # Then match digits\n    }\n\n    '123'    ~~ / <maybe_prefixed_num: True  > /;      # Doesn't match\n    '123'    ~~ / <maybe_prefixed_num: False > /;      # Matches\n    'abc456' ~~ / <maybe_prefixed_num: True  > /;      # Matches\n    'abc456' ~~ / <maybe_prefixed_num: False > /;      # Doesn't match\n=end code\n\nOf course, raw True and False values like that are a major code smell and maintenance nightmare,\nso we might prefer to pass the Boolean values in a named parameter instead:\n\n=begin code\n    #                            vvvvvvvvvvvvv\n    my regex maybe_prefixed_num (:$with-prefix) {\n        ^                                  # From start of string\n        # vvvvvvvvvvvvvvvvv\n        [ <?{$with-prefix}> <alpha>+       # First match prefix (if required)\n        | <!{$with-prefix}>                # Or skip (if not required)\n        ]\n        \\d+                                # Then match digits\n    }\n\n    '123'    ~~ / <maybe_prefixed_num: :with-prefix  > /;      # Doesn't match\n    '123'    ~~ / <maybe_prefixed_num: :!with-prefix > /;      # Matches\n    'abc456' ~~ / <maybe_prefixed_num: :with-prefix  > /;      # Matches\n    'abc456' ~~ / <maybe_prefixed_num: :!with-prefix > /;      # Doesn't match\n=end code\n\nYou can also pass an integer or range argument and then use it as a repetition counter:\n\n=begin code\n    my regex prefix_len ($repcount) {\n        ^                         # From start of string only\n        <alpha> ** {$repcount}    # First match the specified number of alphas\n        \\d+                       # Then digits\n    }\n\n    'x123'   ~~ / <prefix_len: 1     > /;      # Matches\n    'xx456'  ~~ / <prefix_len: 2     > /;      # Matches\n    'xx789'  ~~ / <prefix_len: 1..2  > /;      # Matches\n\n    'x123'   ~~ / <prefix_len: 2     > /;      # Doesn't match\n    'xx456'  ~~ / <prefix_len: 1     > /;      # Doesn't match\n    'xxx789' ~~ / <prefix_len: 1..2  > /;      # Doesn't match\n=end code\n\nAnd, as we've seen earlier, any parameter you pass can be accessed within\na code block inside the regex. So you can (for example) set flags on certain\noutcomes:\n\n=begin code\n    my regex prefix_optional ($has-prefix is rw) {\n        { $has-prefix = False }                  # No prefix (yet)\n        [ <alpha>+  { $has-prefix = True } ]?    # First match optional prefix (and set flag)\n        \\d+                                      # Then match digits\n    }\n\n    my $prefix-seen;\n\n    '123'     ~~ / <prefix_optional: $prefix-seen  > /;      # $prefix-seen is false\n\n    'abc456'  ~~ / <prefix_optional: $prefix-seen  > /;      # $prefix-seen is true\n=end code\n\nIn summary, then, regex parameter lists are a way of making regexes runtime configurable\n(in exactly the same way that subroutine parameter lists are a way of making subroutines\nruntime configurable).\n\n=head1 X<Regex interpolation|Regexes,Regex Interpolation>\n\nInstead of using a literal pattern for a regex match, you can use a variable\nthat holds that pattern. This variable can then be 'interpolated' into a regex,\nsuch that its appearance in the regex is replaced with the pattern that it\nholds. You can also use a block of code, the return value of which may be used\nliterally, interpreted as a regex, or interpreted as a Boolean that either\nallows the match or prevents it.\n\nThe advantage of using interpolation this way, is that the pattern need\nnot be hardcoded in the source of your Raku program, but may instead be\nvariable and generated at runtime.\n\nThere are five different ways of interpolating a variable or code-block into a\nregex as a pattern, which may be summarized as follows:\n\n=begin table\n\nSyntax         | Description\n===============+===========================================================\n$variable,     | Interpolates stringified contents of variable literally.\n@variable      |\n---------------------------------------------------------------------------\n$(code),       | Runs Raku code inside the regex, and interpolates the\n@(code)        | stringified return value literally.\n---------------------------------------------------------------------------\n<$variable>    | Interpolates stringified contents of variable as a regex.\n<@variable>    |\n---------------------------------------------------------------------------\n<{code}>       | Runs Raku code inside the regex, and interpolates the\n               | stringified return value as a regex.\n---------------------------------------------------------------------------\n<?{code}>,     | Evaluates Raku code inside the regex in Boolean context,\n<!{code}>      | with result either allowing or preventing the match.\n\n=end table\n\nThe use of hashes in regexes is reserved.\n\n=head2 Literal interpolation\n\nX<|Regexes,$variable>X<|Regexes,$(code)>\nLet's start with the first two syntactical forms: C«$variable» and C«$(code)».\nThese forms will interpolate the stringified value of the variable or the\nstringified return value of the code literally, provided that the respective\nvalue isn't a L<C<Regex>|/type/Regex> object. If the value is a L<C<Regex>|/type/Regex>, it\nwill not be stringified, but instead be interpolated as such. 'Literally' means\nI<strictly literally>, that is: as if the respective stringified value is quoted\nwith a basic C<Q> string L<C<Q[...]>|/language/quoting#Literal_strings:_Q>.\nConsequently, the stringified value will not itself undergo any further\ninterpolation.\n\nFor C«$variable» this means the following:\n\n    my $string   = 'Is this a regex or a string: 123\\w+False$pattern1 ?';\n    my $pattern1 = 'string';\n    my $pattern2 = '\\w+';\n    my $number   = 123;\n    my $regex    = /\\w+/;\n\n    say $string.match: / 'string' /;                      #  [1] OUTPUT: «｢string｣␤»\n    say $string.match: / $pattern1 /;                     #  [2] OUTPUT: «｢string｣␤»\n    say $string.match: / $pattern2 /;                     #  [3] OUTPUT: «｢\\w+｣␤»\n    say $string.match: / $regex /;                        #  [4] OUTPUT: «｢Is｣␤»\n    say $string.match: / $number /;                       #  [5] OUTPUT: «｢123｣␤»\n\nIn this example, the statements C<[1]> and C<[2]> are equivalent and meant to\nillustrate a plain case of regex interpolation. Since unescaped/unquoted\nalphabetic characters in a regex match literally, the single quotes in the regex\nof statement C<[1]> are functionally redundant; they have merely been included\nto emphasize the correspondence between the first two statements. Statement\nC<[3]> unambiguously shows that the string pattern held by C<$pattern2> is\ninterpreted literally, and not as a regex. In case it would have been\ninterpreted as a regex, it would have matched the first word of C<$string>, i.e.\nC<｢Is｣>, as can be seen in statement C<[4]>. Statement C<[5]> shows how the\nstringified number is used as a match pattern.\n\nThis code exemplifies the use of the C«$(code)» syntax:\n\n    my $string   = 'Is this a regex or a string: 123\\w+False$pattern1 ?';\n    my $pattern1 = 'string';\n    my $pattern3 = 'gnirts';\n    my $pattern4 = '$pattern1';\n    my $bool     = True;\n    my sub f1    { return Q[$pattern1] };\n\n    say $string.match: / $pattern3.flip /;                #  [6] OUTPUT: «Nil␤»\n    say $string.match: / \"$pattern3.flip()\" /;            #  [7] OUTPUT: «｢string｣␤»\n    say $string.match: / $($pattern3.flip) /;             #  [8] OUTPUT: «｢string｣␤»\n    say $string.match: / $([~] $pattern3.comb.reverse) /; #  [9] OUTPUT: «｢string｣␤»\n    say $string.match: / $(!$bool) /;                     # [10] OUTPUT: «｢False｣␤»\n\n    say $string.match: / $pattern4 /;                     # [11] OUTPUT: «｢$pattern1｣␤»\n    say $string.match: / $(f1) /;                         # [12] OUTPUT: «｢$pattern1｣␤»\n\nStatement C<[6]> does not work as probably intended. To the human reader, the\ndot C<.> may seem to represent the L<method call operator|/language/operators#methodop_.>,\nbut since a dot is not a valid character for an L<ordinary identifier|/language/syntax#Ordinary_identifiers>,\nand given the regex context, the compiler will parse it as the regex wildcard\nL<.|/language/regexes#Wildcards> that matches any character. The apparent\nambiguity may be resolved in various ways, for instance through the use of\nstraightforward L<string interpolation|/language/quoting#Interpolation:_qq>\nfrom the regex as in statement C<[7]> (note that the inclusion of the call\noperator C<()> is key here), or by using the second syntax form from the above\ntable as in statement C<[8]>, in which case the match pattern C<string> first\nemerges as the return value of the C<flip> method call. Since general Raku\ncode may be run from within the parentheses of C<$( )>, the same effect can\nalso be achieved with a bit more effort, like in statement C<[9]>. Statement\nC<[10]> illustrates how the stringified version of the code's return value (the\nBoolean value C<False>) is matched literally.\n\nFinally, statements C<[11]> and C<[12]> show how the value of C<$pattern4> and\nthe return value of C<f1> are I<not> subject to a further round of\ninterpolation. Hence, in general, after possible stringification, C«$variable»\nand C«$(code)» provide for a strictly literal match of the variable or return\nvalue.\n\n=head2 Interpolation as a regex\n\nX«|Regexes,<$variable>»X«|Regexes,<{code}>»\nNow consider the second two syntactical forms from the table above:\nC«<$variable>» and C«<{code}>». These forms will stringify the value of the\nvariable or the return value of the code and interpolate it as a regex. If the\nrespective value is a L<C<Regex>|/type/Regex>, it is interpolated as such:\n\n    my $string         = 'Is this a regex or a string: 123\\w+$x ?';\n    my $pattern1       = '\\w+';\n    my $number         = 123;\n    my sub f1          { return /s\\w+/ };\n\n    say $string.match: / <$pattern1>  /;                  # OUTPUT: «｢Is｣␤»\n    say $string.match: / <$number>    /;                  # OUTPUT: «｢123｣␤»\n    say $string.match: / <{ f1 }>     /;                  # OUTPUT: «｢string｣␤»\n\nImportantly, 'to interpolate as a regex' means to interpolate/insert into the\ntarget regex without protective quoting. Consequently, if the value of the\nvariable C<$variable1> is itself of the form C<$variable2>, evaluation of\nC«<$variable1>» or C«<{ $variable1 }>» inside a target regex C</.../> will cause\nthe target regex to assume the form C</$variable2/>. As described above, the\nevaluation of this regex will then trigger further interpolation of\nC<$variable2>:\n\n    my $string    = Q[Mindless \\w+ $variable1 $variable2];\n    my $variable1 = Q[\\w+];\n    my $variable2 = Q[$variable1];\n    my sub f1     { return Q[$variable2] };\n\n    # /<{ f1 }>/ ==> /$variable2/ ==> / '$variable1' /\n    say $string.match: / <{ f1 }>     /; # OUTPUT: «｢$variable1｣␤»\n\n    # /<$variable2>/ ==> /$variable1/ ==> / '\\w+' /\n    say $string.match: /<$variable2>/;   # OUTPUT: «｢\\w+｣␤»\n\n    # /<$variable1>/ ==> /\\w+/\n    say $string.match: /<$variable1>/;   # OUTPUT: «｢Mindless｣␤»\n\nWhen an array variable is interpolated into a regex, the regex engine handles it\nlike a C<|> alternative of the regex elements (see the documentation on\nL<embedded lists|/language/regexes#Quoted_lists_are_LTM_matches>, above). The\ninterpolation rules for individual elements are the same as for scalars, so\nstrings and numbers match literally, and L<C<Regex>|/type/Regex> objects match as\nregexes. Just as with ordinary C<|> interpolation, the longest match succeeds:\n\n    my @a = '2', 23, rx/a.+/;\n    say ('b235' ~~ /  b @a /).Str;      # OUTPUT: «b23␤»\n\nIf you have an expression that evaluates to a list, but you do not want to\nassign it to an @-sigiled variable first, you can interpolate it with\nC<@(code)>. In this example, both regexes are equivalent:\n\n    my %h = a => 1, b => 2;\n    my @a = %h.keys;\n    say S:g/@(%h.keys)/%h{$/}/ given 'abc';    # OUTPUT: «12c␤»\n    say S:g/@a/%h{$/}/ given 'abc';            # OUTPUT: «12c␤»\n\n=head2 Regex Boolean condition check\n\nX«|Regexes,<?{}>»\nX«|Regexes,<!{}>»\nThe fifth syntactical form C«<?{}>» allows the evaluation of a Boolean expression that\ncan perform a semantic evaluation of the match before the regular expression\ncontinues. In other words, it is possible to check in a Boolean context a part\nof a regular expression and therefore invalidate the whole match (or allow it to\ncontinue) even if the match succeeds from a syntactic point of view.\n\nIn particular the C«<?{}>» operator requires a C<True> value in order to allow\nthe regular expression to match, while its negated form C«<!{}>» requires a\nC<False> value.\n\nIn order to demonstrate the above operator, please consider the following\nexample that involves a simple IPv4 address matching:\n\n=begin code\nmy $localhost = '127.0.0.1';\nmy regex ipv4-octet { \\d ** 1..3 <?{ True }> }\n$localhost ~~ / ^ <ipv4-octet> ** 4 % \".\" $ /;\nsay $/<ipv4-octet>;   # OUTPUT: «[｢127｣ ｢0｣ ｢0｣ ｢1｣]␤»\n=end code\n\nThe C<octet> regular expression matches against a number made by one up to three\ndigits. Each match is driven by the result of the C«<?{}>», that being the fixed\nvalue of C<True> means that the regular expression match has to be always\nconsidered as good. As a counter-example, using the special constant value\nC<False> will invalidate the match even if the regular expression matches from a\nsyntactic point of view:\n\n=begin code\nmy $localhost = '127.0.0.1';\nmy regex ipv4-octet { \\d ** 1..3 <?{ False }> }\n$localhost ~~ / ^ <ipv4-octet> ** 4 % \".\" $ /;\nsay $/<ipv4-octet>;   # OUTPUT: «Nil␤»\n=end code\n\nFrom the above examples, it should be clear that it is possible to improve the\nsemantic check, for instance ensuring that each I<octet> is really a valid IPv4\noctet:\n\n=begin code\nmy $localhost = '127.0.0.1';\nmy regex ipv4-octet { \\d ** 1..3 <?{ 0 <= $/.Int <= 255 }> }\n$localhost ~~ / ^ <ipv4-octet> ** 4 % \".\" $ /;\nsay $/<ipv4-octet>;   # OUTPUT: «[｢127｣ ｢0｣ ｢0｣ ｢1｣]␤»\n=end code\n\nPlease note that it is not required to evaluate the regular expression in-line,\nbut also a regular method can be called to get the Boolean value:\n\n=begin code\nmy $localhost = '127.0.0.1';\nsub check-octet ( Int $o ){ 0 <= $o <= 255 }\nmy regex ipv4-octet { \\d ** 1..3 <?{ &check-octet( $/.Int ) }> }\n$localhost ~~ / ^ <ipv4-octet> ** 4 % \".\" $ /;\nsay $/<ipv4-octet>;   # OUTPUT: «[｢127｣ ｢0｣ ｢0｣ ｢1｣]␤»\n=end code\n\nOf course, being C«<!{}>» the negation form of C«<?{}>» the same Boolean\nevaluation can be rewritten in a negated form:\n\n=begin code\nmy $localhost = '127.0.0.1';\nsub invalid-octet( Int $o ){ $o < 0 || $o > 255 }\nmy regex ipv4-octet { \\d ** 1..3 <!{ &invalid-octet( $/.Int ) }> }\n$localhost ~~ / ^ <ipv4-octet> ** 4 % \".\" $ /;\nsay $/<ipv4-octet>;   # OUTPUT: «[｢127｣ ｢0｣ ｢0｣ ｢1｣]␤»\n=end code\n\n=head1 Adverbs\n\nAdverbs, which modify how regexes work and provide convenient shortcuts for\ncertain kinds of recurring tasks, are combinations of one or more letters\npreceded by a colon C<:>.\n\nThe so-called I<regex> adverbs apply at the point where a regex is defined;\nadditionally, I<matching> adverbs apply at the point that a regex matches\nagainst a string and I<substitution> adverbs are applied exclusively in\nsubstitutions.\n\nThis distinction often blurs, because matching and declaration are often\ntextually close but using the method form of matching, that is, C<.match>, makes\nthe distinction clear.\n\n    say \"Abra abra CADABRA\" ~~ m:exhaustive/:i a \\w+ a/;\n    # OUTPUT: «(｢Abra｣ ｢abra｣ ｢ADABRA｣ ｢ADA｣ ｢ABRA｣)␤»\n    my $regex = /:i a \\w+ a /;\n    say \"Abra abra CADABRA\".match($regex,:ex);\n    # OUTPUT: «(｢Abra｣ ｢abra｣ ｢ADABRA｣ ｢ADA｣ ｢ABRA｣)␤»\n\nIn the first example, the matching adverb (C<:exhaustive>) is contiguous to the\nregex adverb (C<:i>), and as a matter of fact, the \"definition\" and the\n\"matching\" go together; however, by using C<match> it becomes clear that C<:i>\nis only used when defining the C<$regex> variable, and C<:ex> (short for\nC<:exhaustive>) as an argument when matching. As a matter of fact, matching\nadverbs cannot even be used in the definition of a regex:\n\n=for code :skip-test<illustrates error>\nmy $regex = rx:ex/:i a \\w+ a /;\n# ===SORRY!=== Error while compiling (...)␤Adverb ex not allowed on rx\n\nRegex adverbs like C<:i> go into the definition line and matching adverbs like\nC<:overlap> (which can be abbreviated to C<:ov>) are appended to the match call:\n\n    my $regex = /:i . a/;\n    for 'baA'.match($regex, :overlap) -> $m {\n        say ~$m;\n    }\n    # OUTPUT: «ba␤aA␤»\n\n=head2 X<Regex adverbs|Regexes,Regex adverbs>\n\nThe adverbs that appear at the time of a regex declaration are part of the\nactual regex and influence how the Raku compiler translates the regex into\nbinary code.\n\nFor example, the C<:ignorecase> (C<:i>) adverb tells the compiler to ignore\nthe distinction between uppercase, lowercase, and titlecase letters.\n\nSo C<'a' ~~ /A/> is false, but C<'a' ~~ /:i A/> is a successful match.\n\nRegex adverbs can come before or inside a regex declaration and only affect the\npart of the regex that comes afterwards, lexically. Note that regex adverbs\nappearing before the regex must appear after something that introduces the regex\nto the parser, like 'rx' or 'm' or a bare '/'. This is NOT valid:\n\n=begin code :skip-test<illustrates error>\nmy $rx1 = :i/a/;      # adverb is before the regex is recognized => exception\n=end code\n\nbut these are valid:\n\n    my $rx1 = rx:i/a/;     # before\n    my $rx2 = m:i/a/;      # before\n    my $rx3 = /:i a/;      # inside\n\nThese two regexes are equivalent:\n\n    my $rx1 = rx:i/a/;      # before\n    my $rx2 = rx/:i a/;     # inside\n\nWhereas these two are not:\n\n    my $rx3 = rx/a :i b/;   # matches only the b case insensitively\n    my $rx4 = rx/:i a b/;   # matches completely case insensitively\n\nSquare brackets and parentheses limit the scope of an adverb:\n\n    / (:i a b) c /;         # matches 'ABc' but not 'ABC'\n    / [:i a b] c /;         # matches 'ABc' but not 'ABC'\n\nAlternations and conjunctions, and their branches, have no impact on the scope of an adverb:\n\n    /  :i a | b c /;        # matches 'a', 'A', 'bc', 'Bc', 'bC' or 'BC'\n    / [:i a | b] c /;       # matches 'ac', 'Ac', 'bc', or 'Bc' but not 'aC', 'AC', 'bC' or 'BC'\n\nWhen two adverbs are used together, they each keep their colon at the front:\n\n    \"þor is Þor\" ~~ m:g:i/þ/;  # OUTPUT: «(｢þ｣ ｢Þ｣)␤»\n\nThat implies that when there are multiple characters together after a C<:>, they\ncorrespond to the same adverb, as in C<:ov> or C<:P5>.\n\n=head3 X<Ignorecase|Adverbs,:ignorecase>\n\nX<|Adverbs,:i>\nThe C<:ignorecase> or C<:i> adverb instructs the regex engine to ignore\nthe distinction between uppercase, lowercase, and titlecase letters.\n\nSee the section L<Regex adverbs|/language/regexes#Regex_adverbs>\nfor examples.\n\nNote that ignorecase can be imprecise due to the inherent nature of Unicode\ncomposition. For comparisons, it is generally best to gather the text and use\nL<routine fc|/type/Str#routine_fc> (fold case) first and then do the case-insensitive\ncheck as a separate step. For example, using a regex lookahead assertion:\n\n    =begin code\n    say so 'STRASSE' ~~ /(\\w+) <?{$0.fc eq 'straße'.fc}>/  # OUTPUT: «True␤»\n    =end code\n\n=head3 X<Ignoremark|Adverbs,:ignoremark>\n\nX<|Adverbs,:m>\nThe C<:ignoremark> or C<:m> adverb instructs the regex engine to only\ncompare base characters, and ignore additional marks such as combining\naccents:\n\n    =begin code\n    say so 'a' ~~ rx/ä/;                # OUTPUT: «False␤»\n    say so 'a' ~~ rx:ignoremark /ä/;    # OUTPUT: «True␤»\n    say so 'ỡ' ~~ rx:ignoremark /o/;    # OUTPUT: «True␤»\n    =end code\n\n=head3 X<Ratchet|Adverbs,:ratchet>\n\nX<|Adverbs,:r>\nThe C<:ratchet> or C<:r> adverb causes the regex engine to not backtrack\n(see L<backtracking|/language/regexes#Backtracking>). Mnemonic: a\nL<ratchet|https://en.wikipedia.org/wiki/Ratchet_%28device%29> only moves\nin one direction and can't backtrack.\n\nWithout this adverb, parts of a regex will try different ways to match a\nstring in order to make it possible for other parts of the regex to match.\nFor example, in C<'abc' ~~ /\\w+ ./>, the C<\\w+> first eats up the whole\nstring, C<abc>, but then the C<.> fails. Thus C<\\w+> gives up a character,\nmatching only C<ab>, and the C<.> can successfully match the string C<c>.\nThis process of giving up characters (or in the case of alternations, trying\na different branch) is known as backtracking.\n\n    say so 'abc' ~~ / \\w+ . /;        # OUTPUT: «True␤»\n    say so 'abc' ~~ / :r \\w+ . /;     # OUTPUT: «False␤»\n\nRatcheting can be an optimization, because backtracking is costly. But more\nimportantly, it closely corresponds to how humans parse a text. If you have\na regex C<my regex identifier { \\w+ }> and\nC<my regex keyword { if | else | endif }>, you intuitively expect the\nC<identifier> to gobble up a whole word and not have it give up its end to\nthe next rule, if the next rule otherwise fails.\n\nFor example, you don't\nexpect the word C<motif> to be parsed as the identifier C<mot> followed by\nthe keyword C<if>. Instead, you expect C<motif> to be parsed as one identifier;\nand if the parser expects an C<if> afterwards, best that it should fail than\nhave it parse the input in a way you don't expect.\n\nSince ratcheting behavior is often desirable in parsers, there's a\nshortcut to declaring a ratcheting regex:\n\n    =begin code :skip-test<illustrates pattern>\n    my token thing { ... };\n    # short for\n    my regex thing { :r ... };\n    =end code\n\n=head3 X<Sigspace|Adverbs,:sigspace>\n\nX<|Adverbs,:s>\nThe B<C<:sigspace>> or B<C<:s>> adverb changes the behavior of\nunquoted whitespace in a regex.\n\nWithout C<:sigspace>, unquoted whitespace in a regex is generally\nignored, to make regexes more readable by programmers.\nWhen C<:sigspace> is present, unquoted whitespace may be converted into\nC«<.ws>» subrule calls depending on where it occurs in the regex.\n\n    =begin code\n    say so \"I used Photoshop®\"   ~~ m:i/   photo shop /;  # OUTPUT: «True␤»\n    say so \"I used a photo shop\" ~~ m:i:s/ photo shop /;  # OUTPUT: «True␤»\n    say so \"I used Photoshop®\"   ~~ m:i:s/ photo shop /;  # OUTPUT: «False␤»\n    =end code\n\nC<m:s/ photo shop /> acts the same as\nC<m/ photo <.ws> shop <.ws> />. By default, C«<.ws>» makes sure that\nwords are separated, so C<a b> and C<^&> will match C«<.ws>» in the\nmiddle, but C<ab> won't:\n\n    =begin code\n    say so \"ab\" ~~ m:s/a <.ws> b/;     # OUTPUT: «False␤»\n    say so \"a b\" ~~ m:s/a <.ws> b/;    # OUTPUT: «True␤»\n    say so \"^&\" ~~ m:s/'^' <.ws> '&'/; # OUTPUT: «True␤»\n    =end code\n\nThe third line is matched, because C<^&> is not a word. For more clarification\non how C«<.ws>» rule works, refer to L<WS rule description|/language/grammars#ws>.\n\nWhere whitespace in a regex turns into C«<.ws>» depends on what comes before\nthe whitespace. In the above example, whitespace in the beginning of a regex\ndoesn't turn into C«<.ws>», but whitespace after characters does. In\ngeneral, the rule is that if a term might match something, whitespace after\nit will turn into C«<.ws>».\n\nIn addition, if whitespace comes after a term but I<before> a quantifier\n(C<+>, C<*>, or C<?>), C«<.ws>» will be matched after every match of the\nterm. So, C<foo +> becomes C«[ foo <.ws> ]+». On the other hand, whitespace\nI<after> a quantifier acts as normal significant whitespace; e.g.,\nZ<ignore-code-ws>\"C<foo+ >\" becomes C«foo+ <.ws>».  On the other hand,\nwhitespace between a quantifier and the C<%> or C<%%> quantifier modifier\nis not significant.  Thus C<foo+ % ,> does I<not> become C«foo+ <.ws>% ,»\n(which would be invalid anyway); instead, neither of the spaces are significant.\n\nIn all, this code:\n\n    =begin code\n    rx :s {\n        ^^\n        {\n            say \"No sigspace after this\";\n        }\n        <.assertion_and_then_ws>\n        characters_with_ws_after+\n        ws_separated_characters *\n        [\n        | some \"stuff\" .. .\n        | $$\n        ]\n        :my $foo = \"no ws after this\";\n        $foo\n    }\n    =end code\n\nBecomes:\n\n    =begin code\n    rx {\n        ^^ <.ws>\n        {\n            say \"No space after this\";\n        }\n        <.assertion_and_then_ws> <.ws>\n        characters_with_ws_after+ <.ws>\n        [ws_separated_characters <.ws>]* <.ws>\n        [\n        | some <.ws> \"stuff\" <.ws> .. <.ws> . <.ws>\n        | $$ <.ws>\n        ] <.ws>\n        :my $foo = \"no ws after this\";\n        $foo <.ws>\n    }\n    =end code\n\nIf a regex is declared with the C<rule> keyword, both the C<:sigspace> and\nC<:ratchet> adverbs are implied.\n\nGrammars provide an easy way to override what C«<.ws>» matches:\n\n    grammar Demo {\n        token ws {\n            <!ww>       # only match when not within a word\n            \\h*         # only match horizontal whitespace\n        }\n        rule TOP {      # called by Demo.parse;\n            a b '.'\n        }\n    }\n\n    # doesn't parse, whitespace required between a and b\n    say so Demo.parse(\"ab.\");                 # OUTPUT: «False␤»\n    say so Demo.parse(\"a b.\");                # OUTPUT: «True␤»\n    say so Demo.parse(\"a\\tb .\");              # OUTPUT: «True␤»\n\n    # \\n is vertical whitespace, so no match\n    say so Demo.parse(\"a\\tb\\n.\");             # OUTPUT: «False␤»\n\nWhen parsing file formats where some whitespace (for example, vertical\nwhitespace) is significant, it's advisable to override C<ws>.\n\n=head3 Perl compatibility adverb\n\nThe B<C<:Perl5>> or B<C<:P5>> adverb switches the Regex parsing and matching\nto the way Perl regexes behave:\n\n    so 'hello world' ~~ m:Perl5/^hello (world)/;   # OUTPUT: «True␤»\n    so 'hello world' ~~ m/^hello (world)/;         # OUTPUT: «False␤»\n    so 'hello world' ~~ m/^ 'hello ' ('world')/;   # OUTPUT: «True␤»\n\nThe regular behavior is recommended and more idiomatic in Raku of course,\nbut the B<C<:Perl5>> adverb can be useful when compatibility with Perl is required.\n\n=head2 Matching adverbs\n\nIn contrast to regex adverbs, which are tied to the declaration of a regex,\nmatching adverbs only make sense when matching a string against a regex.\n\nThey can never appear inside a regex, only on the outside – either as part\nof an C<m/.../> match or as arguments to a match method.\n\n=head3 X<Positional adverbs|Adverbs,:1st>\n\nX<|Adverbs,:2nd>\nX<|Adverbs,:3rd>\nX<|Adverbs,:nth>\nPositional adverbs make the expression match only the string in the indicated\nposition:\n\n    my $data = \"f fo foo fooo foooo fooooo foooooo\";\n    say $data ~~ m:nth(4)/fo+/;   # OUTPUT: «｢foooo｣␤»\n    say $data ~~ m:1st/fo+/;      # OUTPUT: «｢fo｣␤»\n    say $data ~~ m:3rd/fo+/;      # OUTPUT: «｢fooo｣␤»\n    say $data ~~ m:nth(1,3)/fo+/; # OUTPUT: «(｢fo｣ ｢fooo｣)␤»\n\nAs you can see, the adverb argument can also be a list. There's actually no\ndifference between the C<:nth> adverb and the rest. You choose them only based\non legibility. From 6.d, you can also use L<C<Junction>|/type/Junction>s, L<C<Seq>|/type/Seq>s and L<C<Range>|/type/Range>s,\neven\ninfinite ones, as arguments.\n\n    my $data = \"f fo foo fooo foooo fooooo foooooo\";\n    say $data ~~ m:st(1|8)/fo+/;  # OUTPUT: «True␤»\n\nIn this case, one of them exists (1), so it returns True. Observe that we have\nused C<:st>. As said above, it's functionally equivalent, although obviously\nless legible than using C<:nth>, so this last form is advised.\n\n=head3 X<Counting|Adverbs,:x>\n\nThe C<:x> counting adverb makes the expression match many times, like the C<:g>\nadverb, but only up to the limit given by the adverb expression, stopping once the\nspecified number of matches has been reached. The value must be a\nL<C<Numeric>|/type/Numeric> or a L<C<Range>|/type/Range>.\n\n    my $data = \"f fo foo fooo foooo fooooo foooooo\";\n    $data ~~ s:x(8)/o/X/; # f fX fXX fXXX fXXoo fooooo foooooo\n\n=head3 X<Continue|Adverbs,:continue>\n\nX<|Adverbs,:c>\nThe C<:continue> or short C<:c> adverb takes an argument. The argument is\nthe position where the regex should start to search. By default, it searches\nfrom the start of the string, but C<:c> overrides that. If no position is\nspecified for C<:c>, it will default to C<0> unless C<$/> is set, in which\ncase, it defaults to C<$/.to>.\n\n    given 'a1xa2' {\n        say ~m/a./;         # OUTPUT: «a1␤»\n        say ~m:c(2)/a./;    # OUTPUT: «a2␤»\n    }\n\nI<Note:> unlike C<:pos>, a match with :continue() will attempt to\nmatch further in the string, instead of failing:\n\n    say \"abcdefg\" ~~ m:c(3)/e.+/; # OUTPUT: «｢efg｣␤»\n    say \"abcdefg\" ~~ m:p(3)/e.+/; # OUTPUT: «False␤»\n\n=head3 X<Exhaustive|Adverbs,:exhaustive>\n\nX<|Adverbs,:ex>\nTo find all possible matches of a regex – including overlapping ones – and\nseveral ones that start at the same position, use the C<:exhaustive> (short\nC<:ex>) adverb.\n\n    given 'abracadabra' {\n        for m:exhaustive/ a .* a / -> $match {\n            say ' ' x $match.from, ~$match;\n        }\n    }\n\nThe above code produces this output:\n\n=begin code :lang<text>\n    abracadabra\n    abracada\n    abraca\n    abra\n       acadabra\n       acada\n       aca\n         adabra\n         ada\n           abra\n=end code\n\n=head3 X<Global|Adverbs,:global>\n\nX<|Adverbs,:g>\nInstead of searching for just one match and returning a\nL<C<Match>|/type/Match>, search for every non-overlapping match and\nreturn them in a L<C<List>|/type/List>. In order to do this, use the C<:global>\nadverb:\n\n    given 'several words here' {\n        my @matches = m:global/\\w+/;\n        say @matches.elems;         # OUTPUT: «3␤»\n        say ~@matches[2];           # OUTPUT: «here␤»\n    }\n\nC<:g> is shorthand for C<:global>.\n\n=head3 X<Pos|Adverbs,:pos>\n\nX<|Adverbs,:p>\nAnchor the match at a specific position in the string:\n\n    given 'abcdef' {\n        my $match = m:pos(2)/.*/;\n        say $match.from;        # OUTPUT: «2␤»\n        say ~$match;            # OUTPUT: «cdef␤»\n    }\n\nC<:p> is shorthand for C<:pos>.\n\nI<Note:> unlike C<:continue>, a match anchored with :pos() will fail,\ninstead of attempting to match further down the string:\n\n    say \"abcdefg\" ~~ m:c(3)/e.+/; # OUTPUT: «｢efg｣␤»\n    say \"abcdefg\" ~~ m:p(3)/e.+/; # OUTPUT: «False␤»\n\n=head3 X<Overlap|Adverbs,:overlap>\n\nX<|Adverbs,:ov>\nTo get several matches, including overlapping matches, but only one (the\nlongest) from each starting position, specify the C<:overlap> (short C<:ov>)\nadverb:\n\n    given 'abracadabra' {\n        for m:overlap/ a .* a / -> $match {\n            say ' ' x $match.from, ~$match;\n        }\n    }\n\nproduces\n\n=begin code :lang<text>\n    abracadabra\n       acadabra\n         adabra\n           abra\n=end code\n\n=head2 Substitution adverbs\n\nYou can apply matching adverbs (such as C<:global>, C<:pos> etc.) to\nsubstitutions. In addition, there are adverbs that only make sense for\nsubstitutions, because they transfer a property from the matched string\nto the replacement string.\n\n=head3 X<Samecase|Adverbs,:samecase>\n\nX<|Adverbs,:ii>\nThe C<:samecase> or C<:ii> substitution adverb implies the\nC<:ignorecase> adverb for the regex part of the substitution, and in\naddition carries the case information to the replacement string:\n\n=begin code\n$_ = 'The cat chases the dog';\ns:global:samecase[the] = 'a';\nsay $_;                 # OUTPUT: «A cat chases a dog␤»\n=end code\n\nHere you can see that the first replacement string C<a> got capitalized,\nbecause the first string of the matched string was also a capital\nletter.\n\n=head3 X<Samemark|Adverbs,:samemark>\n\nX<|Adverbs,:mm>\nThe C<:samemark> or C<:mm> adverb implies C<:ignoremark> for the regex,\nand in addition, copies the markings from the matched characters to the\nreplacement string:\n\n=begin code\ngiven 'äộñ' {\n    say S:mm/ a .+ /uia/;           # OUTPUT: «üị̂ã␤»\n}\n=end code\n\n=head3 X<Samespace|Adverbs,:samespace>\n\nX<|Adverbs,:ss>\nThe C<:samespace> or C<:ss> substitution modifier implies the\nC<:sigspace> modifier for the regex, and in addition, copies the\nwhitespace from the matched string to the replacement string:\n\n=begin code\nsay S:samespace/a ./c d/.raku given \"a b\";      # OUTPUT: «\"c d\"␤»\nsay S:samespace/a ./c d/.raku given \"a\\tb\";     # OUTPUT: «\"c\\td\"␤»\nsay S:samespace/a ./c d/.raku given \"a\\nb\";     # OUTPUT: «\"c\\nd\"␤»\n=end code\n\nThe C<ss/.../.../> syntactic form is a shorthand for\nC<s:samespace/.../.../>.\n\n=head1 X<Tilde for nesting structures|Regexes,tilde>\n\nX<|Regexes,~>\nThe C<~> operator is a helper for matching nested subrules with a\nspecific terminator as the goal. It is designed to be placed between\nan opening and closing delimiter pair, like so:\n\n    / '(' ~ ')' <expression> /\n\nHowever, it mostly ignores the left argument, and operates on the next\ntwo atoms (which may be quantified). Its operation on those next two\natoms is to \"twiddle\" them so that they are actually matched in\nreverse order. Hence the expression above, at first blush, is merely\nanother way of writing:\n\n    / '(' <expression> ')' /\n\nUsing C<~> keeps the separators closer together but beyond that,\nwhen it rewrites the atoms it also inserts the apparatus that will\nset up the inner expression to recognize the terminator, and to\nproduce an appropriate error message if the inner expression does\nnot terminate on the required closing atom. So it really does pay\nattention to the left delimiter as well, and it actually rewrites\nour example to something more like:\n\nX<|Regexes,SETGOAL>\n    =begin code :skip-test<incomplete code>\n    $<OPEN> = '(' <SETGOAL: ')'> <expression> [ $GOAL || <FAILGOAL> ]\n    =end code\n\nX<FAILGOAL|Regexes,FAILGOAL> is a special method that can be defined by the user and it\nwill be called on parse failure:\n\n    grammar A { token TOP { '[' ~ ']' \\w+  };\n                method FAILGOAL($goal) {\n                    die \"Cannot find $goal near position {self.pos}\"\n                }\n    }\n\n    say A.parse: '[good]';  # OUTPUT: «｢[good]｣␤»\n    A.parse: '[bad';        # will throw FAILGOAL exception\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::AdHoc: Cannot find ']'  near position 4␤»\n\nNote that you can use this construct to set up expectations for a\nclosing construct even when there's no opening delimiter:\n\n    \"3)\"  ~~ / <?> ~ ')' \\d+ /;  # OUTPUT: «｢3)｣»\n    \"(3)\" ~~ / <?> ~ ')' \\d+ /;  # OUTPUT: «｢3)｣»\n\nHere C«<?>» successfully matches the null string.\n\nThe order of the regex capture is original:\n\n    \"abc\" ~~ /a ~ (c) (b)/;\n    say $0; # OUTPUT: «｢c｣␤»\n    say $1; # OUTPUT: «｢b｣␤»\n\n=head1 X«Recursive Regexes|Regexes,recursive»\n\nX«|Regexes,tilde tilde»\nX«|Regexes,~~»\nX«|Regexes,<~~>»\nYou can use C«<~~>» to recursively invoke the current Regex from within the\nRegex.  This can be extremely helpful for matching nested data structures.  For\nexample, consider this Regex:\n\n    / '(' <-[()]>* ')' || '('[ <-[()]>* <~~> <-[()]>* ]* ')' /\n\nThis says \"match B<either> an open parenthesis, followed by zero or more\nnon-parentheses characters, followed by a close parenthesis B<or> an open\nparenthesis followed by zero or more non-parentheses characters, followed by\nI<another match for this Regex>, followed by zero or more non-parentheses\ncharacters, followed by a close parenthesis.\"  This Regex allows you to match\narbitrarily many nested parentheses, as show below:\n\n     my $paren = rx/ '(' <-[()]>* ')' || '('[ <-[()]>* <~~> <-[()]>* ]* ')' /;\n     say 'text' ~~ $paren;                            # OUTPUT: «Nil␤»\n     say '(1 + 1) = 2' ~~ $paren;                     # OUTPUT: «｢(1 + 1)｣␤»\n     say '(1 + (2 × 3)) = 7' ~~ $paren;               # OUTPUT: «｢(1 + (2 × 3))｣␤»\n     say '((5 + 2) × 6) = 42 (the answer)' ~~ $paren  # OUTPUT: «｢((5 + 2) × 6)｣␤»\n\nNote that the last expression shown above does I<not> match all the\nway to the final C<)>, as would have happened with C</'('.*')'/>, nor\ndoes it match only to the first C<)>.  Instead, it correctly matches\nto the close parenthesis paired with the first opening parenthesis, an\neffect that is very difficult to duplicate without recursive regexes.\n\nWhen using recursive regexes (as with any other recursive data\nstructure) you should be careful to avoid infinite recursion, which\nwill cause your program to hang or crash.\n\n=head1 Backtracking\n\nRaku defaults to L<backtracking|/language/glossary#Backtracking> when evaluating regular expressions.\nBacktracking is a technique that allows the engine to try different\nmatching in order to allow every part of a regular expression to succeed.\nThis is costly, because it requires the engine to usually\neat up as much as possible in the first match and then\nadjust going backwards in order to ensure all regular expression parts\nhave a chance to match.\n\n=head2 Understanding backtracking\n\nIn order to better understand backtracking, consider the following example:\n\n=begin code\nmy $string = 'PostgreSQL is a SQL database!';\nsay $string ~~ /(.+)(SQL) (.+) $1/; # OUTPUT: «｢PostgreSQL is a SQL｣␤»\n=end code\n\nWhat happens in the above example is that the string has to be matched against\nthe second occurrence of the word I<SQL>, eating all characters before and\nleaving out the rest.\n\nSince it is possible to execute a piece of code within a regular expression, it\nis also possible to inspect the L<C<Match>|/type/Match> object within the regular\nexpression itself:\n\n=begin code :preamble<my $string = '';>\nmy $iteration = 0;\nsub show-captures( Match $m ){\n    my Str $result_split;\n    say \"\\n=== Iteration {++$iteration} ===\";\n    for $m.list.kv -> $i, $capture {\n        say \"Capture $i = $capture\";\n        $result_split ~= '[' ~ $capture ~ ']';\n    }\n\n    say $result_split;\n}\n\n$string ~~ /(.+)(SQL) (.+) $1 .+ { show-captures( $/ );  }/;\n=end code\n\nThe C<show-captures> method will dump all the elements of C<$/> producing\nthe following output:\n\n=for code :lang<text>\n=== Iteration 1 ===\nCapture 0 = Postgre\nCapture 1 = SQL\nCapture 2 =  is a\n[Postgre][SQL][ is a ]\n\nshowing that the string has been split around the second occurrence of I<SQL>, that\nis the repetition of the first capture (C<$/[1]>).\n\nWith that in place, it is now possible to see how the engine backtracks to find\nthe above match: it does suffice to move the C<show-captures> in the middle of\nthe regular expression, in particular before the repetition of the first capture\nC<$1> to see it in action:\n\n=begin code :preamble<my $string = '';>\nmy $iteration = 0;\nsub show-captures( Match $m ){\n    my Str $result-split;\n    say \"\\n=== Iteration {++$iteration} ===\";\n    for $m.list.kv -> $i, $capture {\n        say \"Capture $i = $capture\";\n        $result-split ~= '[' ~ $capture ~ ']';\n    }\n\n    say $result-split;\n}\n\n$string ~~ / (.+)(SQL) (.+) { show-captures( $/ );  } $1 /;\n=end code\n\nThe output will be much more verbose and will show several iterations, with the\nlast one being the I<winning>. The following is an excerpt of the output:\n\n=begin code :lang<text>\n=== Iteration 1 ===\n[PostgreSQL is a ][SQL][ database!]\n\n=== Iteration 2 ===\n[PostgreSQL is a ][SQL][ database]\n\n...\n\n=== Iteration 10 ===\n[PostgreSQL is a ][SQL][ ]\n\n=== Iteration 11 ===\n[Postgre][SQL][ is a SQL database!]\n\n=== Iteration 12 ===\n[Postgre][SQL][ is a SQL database]\n\n...\n\n=== Iteration 24 ===\n[Postgre][SQL][ is a ]\n=end code\n\nIn the first iteration the I<SQL> part of I<PostgreSQL> is kept within the word: that is not what\nthe regular expression asks for, so there's the need for another iteration. The second iteration will move back,\nin particular one character back (removing thus the final I<!>) and try to match again, resulting\nin a fail since again the I<SQL> is still kept within I<PostgreSQL>.\nAfter ten iterations (the initial run and nine shortenings), the last capture C<$2> cannot be shortened any further,\nso now capture C<$1> changes to matching the first instead of the second I<SQL>.\nThe rest of the string is left for C<$2>, including the part that was backtracked before but now needs to be backtracked anew.\nAfter 14 further iterations (the initial run and 13 shortenings), the final result is a match.\n\nBacktracking is a costly machinery, therefore it is possible to disable\nit in those cases where the matching can be found I<forward> only.\n\nWith regards to the above example, disabling backtracking means\nthe regular expression will not have any chance to match:\n\n=begin code :preamble<my $string = '';>\nsay $string ~~ /(.+)(SQL) (.+) $1/;      # OUTPUT: «｢PostgreSQL is a SQL｣␤»\nsay $string ~~ / :r (.+)(SQL) (.+) $1/;  # OUTPUT: «Nil␤»\n=end code\n\nThe fact is that, as shown in the I<iteration 1> output, the first match of the\nregular expression engine will be Z<ignore-code-ws> C<PostgreSQL is a >,\nC<SQL>, C<database> that does not leave out any room for matching another\noccurrence of the word I<SQL> (as C<$1> in the regular expression). Since the\nengine is not able to get backward and change the path to match, the regular\nexpression fails.\n\nIn general, disabling backtracking does not mean disabling possible\nmultiple iterations of the matching engine, but rather disabling the backward\nmatching tuning.\n\nTo address problematic backtracking, there are also other, at times better ways.\n\nOne is by using frugal quantifiers (or by leaving out certain capture groups altogether).\nMost of the backtracking in our example above is indeed necessary because the\ngreedy capture groups C<(.+)> (especially the first one)\nimmediately eat up as many characters as they can.\n\nBy making the first one frugal, C<(.+?)>,\nwe cause it to extend only until the beginning of the first I<SQL>.\nThis way, the capture groups C<$0> and C<$1> attain\ntheir final result right off the bat, so that the characters at the very end\nneed to be backtracked only once (rather than twice like above):\n\n=begin code :lang<text>\n$string ~~ / (.+?) (SQL) (.+) { show-captures( $/ ); } $1 /;\n\n=== Iteration 1 ===\n[Postgre][SQL][ is a SQL database!]\n\n=== Iteration 2 ===\n[Postgre][SQL][ is a SQL database]\n\n...\n\n=== Iteration 13 ===\n[Postgre][SQL][ is a S]\n\n=== Iteration 14 ===\n[Postgre][SQL][ is a ]\n=end code\n\nFrugality of the I<second> C<(.+)> can also helps us.\nIn our case, it is most useful when combined with frugality of the first.\nObserve how it changes the behavior of the capture group C<$2>\nfrom gradual shortening to gradual lengthening:\n\n=begin code :lang<text>\n$string ~~ / (.+?) (SQL) (.+?) { show-captures( $/ ); } $1 /;\n\n=== Iteration 1 ===\n[Postgre][SQL][ ]\n\n=== Iteration 2 ===\n[Postgre][SQL][ i]\n\n...\n\n=== Iteration 5 ===\n[Postgre][SQL][ is a]\n\n=== Iteration 6 ===\n[Postgre][SQL][ is a ]\n=end code\n\nOn the other hand, combining ratcheting I<and> frugal quantifiers would not help in our case.\nFor example:\n\n=begin code :lang<text>\n$string ~~ /:r (.+?) (SQL) { show-captures( $/ ); } (.+?) $1 /;\n\n=== Iteration 1 ===\nCapture 0 = e\nCapture 1 = SQL  # from the word \"PostgreSQL\"\n[e][SQL]\n\n=== Iteration 2 ===\nCapture 0 =      # one whitespace\nCapture 1 = SQL  # from the stand-alone word \"SQL\"\n[ ][sql]\n=end code\n\nYou can play around with putting the C<{ show-captures( $/ ); }> in different places\nto get a better feel of how C<:r> and frugal as well as greedy quantifiers interact.\n\n=head2 Backtracking control\n\nRaku offers several tools for controlling backtracking.  First, you can use the\nC<:ratchet> regex adverb to turn ratcheting on (or C<:!ratchet> to turn it off).\nSee L<backtracking|/language/regexes#Ratchet> for details.  Note that, as with\nall regex adverbs, you can limit the scope of C<:ratchet> using square\nbrackets.  Thus, in the following code, backtracking is enabled for the first\nquantifier (C<\\S+>), disabled for the second quantifier (C<\\s+>), and re-enabled\nfor the third (C<\\d+>).\n\n=begin code\n'A  42' ~~  rx/\\S+ [:r \\s+ [:!r \\d+ ] ] . /  # OUTPUT: «｢A  42｣␤»\n=end code\n\nC<:ratchet> is enabled by default in C<token>s and C<rule>s; see\nL<grammars|/language/grammars> for more details.\n\nRaku also offers three regex metacharacters to control backtracking for an\nindividual atom.\n\n=head3 X<Disable backtracking: C<:>|Regexes,:>\n\nX<|Regexes,disable backtracking>\nThe C<:> metacharacter disables backtracking for the previous atom.  Thus,\nC</ .*: a/> does not match C<\"  a\"> because the C<.*> matches the entire string,\nleaving nothing for the C<a> to match without backtracking.\n\n=head3 X<Enable greedy backtracking: C<:!>|Regexes,:!>\n\nX<|Regexes,greedy backtracking>\nThe C<:!> metacharacter enables greedy backtracking for the previous atom – that\nis, provides the backtracking behavior that's used when C<:ratchet> is not in\neffect.  C<:!> is closely related to the C<!> L<greedy quantifier\nmodifier|/language/regexes#Greedy_versus_frugal_quantifiers:_?>; however – unlike\nC<!>, which can only be used after a quantifier – C<:!> can be used after any\natom.  For example, C<:!> can be used after an alternation:\n\n=begin code\n'abcd' ~~ /:ratchet [ab | abc]   cd/;  # OUTPUT: «Nil␤»\n'abcd' ~~ /:ratchet [ab | abc]:! cd/;  # OUTPUT: «｢abcd｣␤»\n=end code\n\n=head3 X<Enable frugal backtracking: C<:?>|Regexes,:?>\n\nX<|Regexes,frugal backtracking>\nThe C<:?> metacharacter works exactly like C<:!>, except that it enables frugal\nbacktracking.  It is thus closely related to C<?> L<frugal quantifier\nmodifier|/language/regexes#Greedy_versus_frugal_quantifiers:_?>; again,\nhowever C<:?> can be used after non-quantifier atoms.  This includes contexts in\nwhich C<?> would be the L<zero or one|#Zero_or_one:_?> quantifier\n(instead of providing backtracking control):\n\n=begin code\nmy regex numbers { \\d* }\n\n'4247' ~~ /:ratchet <numbers>?  47/;  # OUTPUT: «Nil␤»\n'4247' ~~ /:ratchet <numbers>:? 47/;  # OUTPUT: «｢4247｣␤»\n=end code\n\n=head2 A note on backtracking with sub-regexes\n\nC<:>, C<:!>, and C<:?> control the backtracking behavior in their current regex\n– that is, they cause an atom to behave as though C<:ratchet> were set\ndifferently in the current regex.  However, neither these metacharacters nor\nC<:!ratchet> can cause a non-backtracking sub-regex (including rules or tokens) to\nbacktrack; the sub-regex has already failed to backtrack.  On the other hand,\nthey I<can> prevent the sub-regex from backtracking.  To expand on our previous\nexample:\n\n\n=begin code\nmy regex numbers { \\d* }\n\n# By default <numbers> backtracks\n'4247' ~~ / <numbers>  47/;  # OUTPUT: «｢4247｣␤»\n# : can disable backtracking over <numbers>\n'4247' ~~ / <numbers>: 47/;  # OUTPUT: «Nil␤»\n\nmy regex numbers-ratchet {:ratchet \\d* }\n\n# <numbers-ratchet> never backtracks\n'4247' ~~ /   <numbers-ratchet>   47/;  # OUTPUT: «Nil␤»\n# :! can't make it\n'4247' ~~ /   <numbers-ratchet>:! 47/;  # OUTPUT: «Nil␤»\n# Neither can setting :!ratchet\n'4247' ~~ /:!r <numbers-ratchet>  47/;  # OUTPUT: «Nil␤»\n=end code\n\n\n=head1 C<$/> changes each time a regular expression is matched\n\nIt is worth noting that each time a regular expression is used, the\nreturned L<C<Match>|/type/Match> (i.e., C<$/>) is reset. In other\nwords, C<$/> always refers to the very last regular expression\nmatched:\n\n=begin code\nmy $answer = 'a lot of Stuff';\nsay 'Hit a capital letter!' if $answer ~~ / <[A..Z>]> /;\nsay $/;  # OUTPUT: «｢S｣␤»\nsay 'hit an x!' if $answer ~~ / x /;\nsay $/;  # OUTPUT: «Nil␤»\n=end code\n\nThe reset of C<$/> applies independently from the scope where the regular expression\nis matched:\n\n=begin code\nmy $answer = 'a lot of Stuff';\nif $answer ~~ / <[A..Z>]> / {\n   say 'Hit a capital letter';\n   say $/;  # OUTPUT: «｢S｣␤»\n}\nsay $/;     # OUTPUT: «｢S｣␤»\n\nif True {\n  say 'hit an x!' if $answer ~~ / x /;\n  say $/;   # OUTPUT: «Nil␤»\n}\n\nsay $/;     # OUTPUT: «Nil␤»\n=end code\n\nThe very same concept applies to named captures:\n\n=begin code\nmy $answer = 'a lot of Stuff';\nif $answer ~~ / $<capital>=<[A..Z>]> / {\n   say 'Hit a capital letter';\n   say $/<capital>; # OUTPUT: «｢S｣␤»\n}\n\nsay $/<capital>;    # OUTPUT: «｢S｣␤»\nsay 'hit an x!' if $answer ~~ / $<x>=x /;\nsay $/<x>;          # OUTPUT: «Nil␤»\nsay $/<capital>;    # OUTPUT: «Nil␤»\n=end code\n\n=head1 Best practices and gotchas\n\nThe L<Regexes: Best practices and gotchas|/language/regexes-best-practices>\nprovides useful information on how to avoid common pitfalls when writing regexes\nand grammars.\n\nSee also the type reference for L<C<Str>|/type/Str> for an overview of\nways other than regexes to investigate and manipulate strings.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/setbagmix.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Sets, bags, and mixes\n\n=SUBTITLE Unordered collections of unique and weighted objects in Raku\n\n=head1 Introduction\n\nThe six collection classes are L<C<Set>|/type/Set>, L<C<SetHash>|/type/SetHash>,\nL<C<Bag>|/type/Bag>, L<C<BagHash>|/type/BagHash>, L<C<Mix>|/type/Mix> and\nL<C<MixHash>|/type/MixHash>.   They all share similar semantics.\n\nIn a nutshell, these classes hold, in general, unordered collections of\nobjects, much like an L<object hash|/type/Hash>.\nThe L<C<QuantHash>|/type/QuantHash> role is the role that is implemented by all\nof these classes: therefore they are also referenced as L<C<QuantHash>|/type/QuantHash>es.\n\nL<C<Set>|/type/Set> and L<C<SetHash>|/type/SetHash> also implement the L<C<Setty>|/type/Setty> role,\nL<C<Bag>|/type/Bag> and L<C<BagHash>|/type/BagHash> implement the L<C<Baggy>|/type/Baggy> role, L<C<Mix>|/type/Mix> and\nL<C<MixHash>|/type/MixHash> implement the L<C<Mixy>|/type/Mixy> role (which itself implements\nthe L<C<Baggy>|/type/Baggy> role).\n\nSets only consider if objects in the collection are present or not, bags can\nhold several objects of the same kind, and mixes also allow fractional (and\nnegative) weights. The regular versions are immutable, the I<-Hash> versions\nare mutable.\n\nLet's elaborate on that. If you want to collect objects in a container but\nyou do not care about the order of these objects, Raku provides these\nI<unordered> collection types.  Being unordered, these containers can be more\nefficient than L<C<List>|/type/List>s or L<C<Array>|/type/Array>s for looking up\nelements or dealing with repeated items.\n\nOn the other hand, if you want to get the contained objects (elements)\nB<without duplicates> and you only care I<whether> an element is in the\ncollection or not, you can use a L<C<Set>|/type/Set> or L<C<SetHash>|/type/SetHash>.\n\nIf you want to get rid of duplicates but still preserve order, take a look\nat the L<unique|/routine/unique> routine for L<C<List>|/type/List>.\n\n=begin comment\n=defn  Set or SetHash\nCollection of distinct objects\n=end comment\n\nIf you want to keep track of the B<number of times each object appeared>,\nyou can use a L<C<Bag>|/type/Bag> or L<C<BagHash>|/type/BagHash>. In these\nL<C<Baggy>|/type/Baggy> containers each element has a weight (an unsigned integer)\nindicating the number of times the same object has been included in the\ncollection.\n\nThe types L<C<Mix>|/type/Mix> and L<C<MixHash>|/type/MixHash> are similar\nto L<C<Bag>|/type/Bag> and L<C<BagHash>|/type/BagHash>, but they also\nallow B<fractional and negative weights>.\n\nL<C<Set>|/type/Set>, L<C<Bag>|/type/Bag>, and L<C<Mix>|/type/Mix> are I<immutable> types.\nUse the mutable variants L<C<SetHash>|/type/SetHash>, L<C<BagHash>|/type/BagHash>,\nand L<C<MixHash>|/type/MixHash> if you want to add or remove elements after the\ncontainer has been constructed.\n\nFor one thing, as far as they are concerned, identical objects refer to the\nsame element – where identity is determined using the L<WHICH|/routine/WHICH>\nmethod (i.e. the same way that the L<===|/routine/===> operator checks identity). For value\ntypes like L<C<Str>|/type/Str>, this means having the same value; for reference types\nlike L<C<Array>|/type/Array>, it means referring to the same object instance.\n\nSecondly, they provide a Hash-like interface where the actual elements of\nthe collection (which can be objects of any type) are the 'keys', and the\nassociated weights are the 'values':\n\n=table\n                      value of $a{$b} if $b       value of $a{$b} if $b\n    type of $a        is an element               is not an element\n    -------------     ----------------------      ---------------------\n    Set / SetHash     True                        False\n    Bag / BagHash     a positive integer          0\n    Mix / MixHash     a non-zero real number      0\n\n=head1 Operators with set semantics\n\nThere are several infix operators devoted to performing common operations\nusing L<C<QuantHash>|/type/QuantHash> semantics.  Since that is a mouthful, these operators\nare usually referred to as \"set operators\".\n\nThis does B<not> mean that the parameters of these operators must always be\nL<C<Set>|/type/Set>, or even a more generic L<C<QuantHash>|/type/QuantHash>.  It just means that the logic\nthat is applied to the operators is the logic of\nL<Set Theory|https://en.wikipedia.org/wiki/Set_theory>.\n\nThese infixes can be written using the Unicode character that represents the\nfunction (like C<∈> or C<∪>), or with an equivalent ASCII version (like\nC<(elem)> or C<(|)>). Prefix the ASCII version with C<!> to negate it\n(like C<!(elem)> or C<!(|)>).\n\nSo explicitly using L<C<Set>|/type/Set> (or L<C<Bag>|/type/Bag> or L<C<Mix>|/type/Mix>) objects with these infixes is\nunnecessary.  All set operators work with all possible arguments, including\n(since 6.d) those that are not explicitly set-like.  If necessary, a coercion\nwill take place internally: but in many cases that is not actually needed.\n\nHowever, if a L<C<Bag>|/type/Bag> or L<C<Mix>|/type/Mix> is one of the parameters to these set operators,\nthen the semantics will be upgraded to that type (where L<C<Mix>|/type/Mix> supersedes\nL<C<Bag>|/type/Bag> if both types happen to be used).\n\n=head2 Set operators that return L<C<Bool>|/type/Bool>\n\n=head3 infix (elem), infix ∈\n\nReturns C<True> if C<$a> is an B<element> of C<$b>, else C<False>.\nL<More information|/language/operators#infix_(elem),_infix_∈>,\nL<Wikipedia definition|https://en.wikipedia.org/wiki/Element_(mathematics)#Notation_and_terminology>.\n\n=head3 infix !(elem), infix ∉\n\nReturns C<True> if C<$a> is B<not> an element of C<$b>, else C<False>.\nL<More information|/language/operators#infix_∉>,\nL<Wikipedia definition|https://en.wikipedia.org/wiki/Element_(mathematics)#Notation_and_terminology>.\n\n=head3 infix (cont), infix ∋\n\nReturns C<True> if C<$a> B<contains> C<$b> as an element, else C<False>.\nL<More information|/language/operators#infix_(cont),_infix_∋>,\nL<Wikipedia definition|https://en.wikipedia.org/wiki/Element_(mathematics)#Notation_and_terminology>.\n\n=head3 infix !(cont), infix ∌\n\nReturns C<True> if C<$a> does B<not> contain C<$b>, else C<False>.\nL<More information|/language/operators#infix_∌>,\nL<Wikipedia definition|https://en.wikipedia.org/wiki/Element_(mathematics)#Notation_and_terminology>.\n\n=head3 infix (<=), infix ⊆\n\nReturns C<True> if C<$a> is a B<subset> or is equal to C<$b>, else C<False>.\nL<<More information|/language/operators#infix_(<=),_infix_⊆>>,\nL<Wikipedia definition|https://en.wikipedia.org/wiki/Subset#Definitions>.\n\n=head3 infix !(<=), infix ⊈\n\nReturns C<True> if C<$a> is B<not> a B<subset> nor equal to C<$b>, else C<False>.\nL<More information|/language/operators#infix_⊈>,\nL<Wikipedia definition|https://en.wikipedia.org/wiki/Subset#Definitions>.\n\n=head3 infix (<), infix ⊂\n\nReturns C<True> if C<$a> is a B<strict subset> of C<$b>, else C<False>.\nL<<More information|/language/operators#infix_(<),_infix_⊂>>,\nL<Wikipedia definition|https://en.wikipedia.org/wiki/Subset#Definitions>.\n\n=head3 infix !(<), infix ⊄\n\nReturns C<True> if C<$a> is B<not> a B<strict subset> of C<$b>, else C<False>.\nL<More information|/language/operators#infix_⊄>,\nL<Wikipedia definition|https://en.wikipedia.org/wiki/Subset#Definitions>.\n\n=head3 infix (>=), infix ⊇\n\nReturns C<True> if C<$a> is a B<superset> of or equal to C<$b>, else C<False>.\nL«More information|/language/operators#infix_(>=),_infix_⊇»,\nL<Wikipedia definition|https://en.wikipedia.org/wiki/Subset#Definitions>.\n\n=head3 infix !(>=), infix ⊉\n\nReturns C<True> if C<$a> is B<not> a B<superset> nor equal to C<$b>, else C<False>.\nL<More information|/language/operators#infix_⊉>,\nL<Wikipedia definition|https://en.wikipedia.org/wiki/Subset#Definitions>.\n\n=head3 infix (>), infix ⊃\n\nReturns C<True> if C<$a> is a B<strict superset> of C<$b>, else C<False>.\nL«More information|/language/operators#infix_(>),_infix_⊃»,\nL<Wikipedia definition|https://en.wikipedia.org/wiki/Subset#Definitions>.\n\n=head3 infix !(>), infix ⊅\n\nReturns C<True> if C<$a> is B<not> a B<strict superset> of C<$b>, else C<False>.\nL<More information|/language/operators#infix_⊅>,\nL<Wikipedia definition|https://en.wikipedia.org/wiki/Subset#Definitions>.\n\n=head3 infix (==), infix ≡\n\nReturns C<True> if C<$a> and C<$b> are B<identical>, else C<False>.\nL<More information|/language/operators#infix_(==),_infix_≡>,\nL<Wikipedia definition|https://en.wikipedia.org/wiki/Equality_(mathematics)#Equality_in_set_theory>.\n\nAvailable as of the 2020.07 Rakudo compiler release.  Users of older\nversions of Rakudo can install the\nL<Set::Equality|https://raku.land/zef:lizmat/Set::Equality> module for\nthe same functionality.\n\n=head3 infix !(==), infix ≢\n\nReturns C<True> if C<$a> and C<$b> are B<not identical>, else C<False>.\nL<More information|/language/operators#infix_≢>,\nL<Wikipedia definition|https://en.wikipedia.org/wiki/Equality_(mathematics)#Equality_in_set_theory>.\n\nAvailable as of the 2020.07 Rakudo compiler release.  Users of older\nversions of Rakudo can install the\nL<Set::Equality|https://raku.land/zef:lizmat/Set::Equality> module for\nthe same functionality.\n\n=head2 Set operators that return a L<C<QuantHash>|/type/QuantHash>\n\n=head3 infix (|), infix ∪\n\nReturns the B<union> of all its arguments.\nL<More information|/language/operators#infix_(|),_infix_∪>,\nL<Wikipedia definition|https://en.wikipedia.org/wiki/Union_(set_theory)>.\n\n=head3 infix (&), infix ∩\n\nReturns the B<intersection> of all of its arguments.\nL<More information|/language/operators#infix_(&),_infix_∩>,\nL<Wikipedia definition|https://en.wikipedia.org/wiki/Intersection_(set_theory)>.\n\n=head3 infix (-), infix ∖\n\nReturns the B<set difference> of all its arguments.\nL<More information|/language/operators#infix_(-),_infix_∖>,\nL<Wikipedia definition|https://en.wikipedia.org/wiki/Complement_(set_theory)#Relative_complement>.\n\n=head3 infix (^), infix ⊖\n\nReturns the B<symmetric set difference> of all its arguments.\nL<More information|/language/operators#infix_(^),_infix_⊖>,\nL<Wikipedia definition|https://en.wikipedia.org/wiki/Symmetric_difference>.\n\n=head2 Set operators that return a L<C<Baggy>|/type/Baggy>\n\n=head3 infix (.), infix ⊍\n\nReturns the Baggy B<multiplication> of its arguments.\nL<More information|/language/operators#infix_(.),_infix_⊍>.\n\n=head3 infix (+), infix ⊎\n\nReturns the Baggy B<addition> of its arguments.\nL<More information|/language/operators#infix_(+),_infix_⊎>.\n\n=head2 Terms related to set operators\n\n=head3 term ∅\n\nThe empty set.  L<More information|/language/terms#term_∅>,\nL<Wikipedia definition|https://en.wikipedia.org/wiki/Empty_set>.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/signatures.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Signature literals\n\n=SUBTITLE A guide to signatures in Raku\n\nX<|Syntax,signature literal>\nX<|Syntax,:()>\n\nL<C<Signatures>|/type/Signature> appear inside parentheses after L<subroutine|/type/Sub> and\nL<method|/type/Method> names, on blocks after a C«->» or C«<->» arrow,\nas the input to\nL<variable declarators|/language/variables#Variable_declarators_and_scope> like\nL<C<my>|/syntax/my>, or as a separate term starting with a colon.\n\n    sub f($x) { }\n    #    ^^^^ Signature of sub f\n    my method x() { }\n    #          ^^ Signature of a method\n    my $s = sub (*@a) { }\n    #           ^^^^^ Signature of an anonymous function\n\n    for <a b c> -> $x { }\n    #              ^^   Signature of a Block\n\n    my ($a, @b) = 5, (6, 7, 8);\n    #  ^^^^^^^^ Signature of a variable declarator\n\n    my $sig = :($a, $b);\n    #          ^^^^^^^^ Standalone Signature object\n\nSignature literals can be used to define the signature of a callback or a\nclosure.\n\n    sub f(&c:(Int)) { }\n    sub will-work(Int) { }\n    sub won't-work(Str) { }\n    f(&will-work);\n\n    f(&won't-work);\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::TypeCheck::Binding::Parameter: Constraint type check failed in binding to parameter '&c'␤»\n\n    f(-> Int { 'this works too' } );\n\nYou can use any kind of literal, including numeric ones, as part of a\nsignature; this\nis generally\nused in conjunction with multis\n\n=for code\nproto stuff(|) {*}\nmulti stuff(33) { 58 }\nmulti stuff(⅓) { 43 }\nmulti stuff(Int)  { 3 }\nmulti stuff(Complex)  { 66 }\nsay stuff($_) for (33, ⅓, i, 48); # OUTPUT: «58␤43␤66␤3␤»\n\nHowever, you can't use C<True> or C<False> as literals in signatures since\nthey will always succeed (or fail). A warning will be issued if you do so:\n\n=for code\nsub foo(True) {};\nmy $sig =  :( True );\n\nThey will both warn \"Literal values in signatures are smartmatched against\nand smartmatch with C<True> will always succeed. Use the C<where> clause\ninstead.\". Use of C<False> will produce a similar warning.\n\nSmartmatching signatures against a L<C<List>|/type/List> is supported.\n\n    my $sig = :(Int $i, Str $s);\n    say (10, 'answer') ~~ $sig;\n    # OUTPUT: «True␤»\n    my $sub = sub ( Str $s, Int $i ) { return $s xx $i };\n    say $sub.signature ~~ :( Str, Int );\n    # OUTPUT: «True␤»\n    given $sig {\n        when :(Str, Int) { say 'mismatch' }\n        when :($, $)     { say 'match' }\n        default          { say 'no match' }\n    }\n    # OUTPUT: «match␤»\n\nIt matches the second C<when> clause since C<:($, $)> represents a\nL<C<Signature>|/type/Signature> with two scalar, anonymous, arguments, which is a more general\nversion of C<$sig>.\n\nWhen smartmatching against a L<C<Hash>|/type/Hash>, the signature is assumed to consist of the\nkeys of the L<C<Hash>|/type/Hash>.\n\n    my %h = left => 1, right => 2;\n    say %h ~~ :(:$left, :$right);\n    # OUTPUT: «True␤»\n\nL<C<Signature>|/type/Signature> literals can contain string/numeric literals\n\n    my $sig = :('Þor', Str, Int);\n    say <Þor Hammer 1> ~~ $sig; # OUTPUT: «True␤»\n\nSignatures can contain a named L<slurpy parameter|/language/signatures#Slurpy_parameters>,\nwhich I<slurps up> any extra named arguments into one big hash.\nIt can have any name; conventionally, it's an underscore:\n\n    my $sig = :($p, :$n, *%_);\n\nSignatures can also contain a slurpy positional parameter\n(which must be the last of all positional parameters);\nit slurps up any extra positional arguments into one big L<C<Array>|/type/Array>.\nThe slurpy positional parameter can be one of L<three kinds|/language/signatures#Types_of_slurpy_array_parameters>:\n\n    my $sig = :($p, :$n, **@_); # keep arguments as they are: @_ contains one entry per argument\n    my $sig = :($p, :$n,  *@_); # flatten any lists\n    my $sig = :($p, :$n,  +@_); # set @_ = argument if it's a single list, else act like **@_\n\n=head1 Parameter separators\n\nA signature consists of zero or more L<C<Parameter>|/type/Parameter>s, separated by\ncommas.\n\n    my $sig = :($a, @b, %c);\n    sub add($a, $b) { $a + $b };\n\nAs an exception, the first parameter may be followed by a colon instead\nof a comma to mark the invocant of a method. This is done in order to\ndistinguish it from what would otherwise be a regular positional parameter.\nThe invocant is the object that was used to call the method, which is usually\nbound to L<C<self>|/routine/self>. By specifying it in the signature, you can\nchange the variable name it is bound to.\n\n    method ($a: @b, %c) {};       # first argument is the invocant\n\n    class Foo {\n        method whoami($me:) {\n            \"Well I'm class $me.^name(), of course!\"\n        }\n    }\n    say Foo.whoami; # OUTPUT: «Well I'm class Foo, of course!␤»\n    say Foo.^methods.first(*.name eq 'whoami').signature ~~ :($: *%) ; # OUTPUT: «True␤»\n\nAnother exception is the L<double semicolon C<;;>|/language/Signatures#The_;;_separator>,\nwhich can take the place of one comma in a L<multi|/language/functions#Multi-dispatch> signature\nto declare that the subsequent parameters should not contribute to its precedence in multiple dispatch.\n\nX<|Language,type constraint>\nX<|Language,Constraint>\n=head1 Type constraints\n\nParameters can optionally have a type constraint (the default is L<C<Any>|/type/Any>).\nThese can be used to restrict the allowed input to a function.\n\n=for code\nmy $sig = :(Int $a, Str $b);\n\nType constraints can have any compile-time defined value\n\n=begin code\nsubset Positive-integer of Int where * > 0;\nsub divisors(Positive-integer $n) { $_ if $n %% $_ for 1..$n };\nCATCH { default { put .^name, ': ', .Str; .resume } };\n\ndivisors 2.5;\n# OUTPUT: «X::TypeCheck::Binding::Parameter: Type check failed in binding to parameter '$n'; expected Positive-integer but got Rat (2.5)␤»\n\ndivisors -3;\n# OUTPUT: «X::TypeCheck::Binding::Parameter: Constraint type check failed in binding to parameter '$n'; expected Positive-integer but got Int (-3)␤»\n=end code\n\nPlease note that in the code above type constraints are enforced at two\ndifferent levels: the first level checks if it belongs to the type in which the\nsubset is based, in this case L<C<Int>|/type/Int>. If it fails, a C<Type check> error is\nproduced. Once that filter is cleared, the constraint that defined the subset is\nchecked, producing a C<Constraint type check> error if it fails.\n\nType constraints can define multiple allowable types\n\n=begin code\nsub abbrev($arg where Str|List|Hash) {...} # throws if $arg is not one of those types\n=end code\n\nX<|Language,anonymous arguments>\nAnonymous arguments are fine too, if you don't actually need to refer to a\nparameter by name, for instance to distinguish between different signatures in a\nL<multi|/language/functions#Multi-dispatch> or to\ncheck the signature of a L<C<Callable>|/type/Callable>.\n\n=for code :preamble<my $sig;>\nmy $sig = :($, @, %a);          # two anonymous and a \"normal\" parameter\n$sig = :(Int, Positional);      # just a type is also fine (two parameters)\nsub baz(Str) { \"Got passed a Str\" }\n\nType constraints may also be L<type captures|/language/signatures#Type_captures>.\n\nX<|Language,where clause>\nIn addition to those I<nominal> types, additional constraints can\nbe placed on parameters in the form of code blocks which must return\na true value to pass the type check\n\n    sub f(Real $x where { $x > 0 }, Real $y where { $y >= $x }) { }\n\nThe code in C<where> clauses has some limitations: anything that produces\nside-effects (e.g., printing output, pulling from an iterator, or increasing a\nstate variable) is not supported and may produce surprising results if used.\nAlso, the code of the C<where> clause may run more than once for a single\ntypecheck in some implementations.\n\nThe C<where> clause doesn't need to be a code block, anything on the right of\nthe C<where>-clause will be used to L<smartmatch|/language/operators#infix_~~>\nthe argument against it.  So you can also write:\n\n    multi factorial(Int $ where 0) { 1 }\n    multi factorial(Int $x)        { $x * factorial($x - 1) }\n\nThe first of those can be shortened to\n\n    multi factorial(0) { 1 }\n\ni.e., you can use a literal directly as a type and value constraint\non an anonymous parameter.\n\nB<Tip:> pay attention to not accidentally leave off a block when you,\nsay, have several conditions:\n\n  -> $y where   .so && .name    {}( sub one   {} ); # WRONG!!\n  -> $y where { .so && .name }  {}( sub two   {} ); # OK!\n  -> $y where   .so &  .name.so {}( sub three {} ); # Also good\n\nThe first version is wrong and will issue a warning about a sub object coerced\nto string. The reason is the expression is equivalent to\nC<($y ~~ ($y.so && $y.name))>; that is \"call C<.so>, and if that is C<True>,\ncall C<.name>; if that is also C<True> use its value for smartmatching…\". It's\nthe B<result> of C<(.so && .name)> it will be smartmatched against, but we\nwant to check that both C<.so> and C<.name> are truthy values. That is why\nan explicit Block or a L<C<Junction>|/type/Junction> is the right version.\n\nAll previous arguments that are not part of a sub-signature in a L<C<Signature>|/type/Signature>\nare accessible in a C<where>-clause that follows an argument. Therefore,\nthe C<where>-clause of the last argument has access to all arguments of a\nsignature that are not part of a sub-signature. For a sub-signature place\nthe C<where>-clause inside the sub-signature.\n\n    sub foo($a, $b where * == $a ** 2) { say \"$b is a square of $a\" }\n    foo 2, 4; # OUTPUT: «4 is a square of 2␤»»\n    # foo 2, 3;\n    # OUTPUT: «Constraint type check failed in binding to parameter '$b'…»\n\n=head2 Constraining optional arguments\n\nL<Optional arguments|#Optional_and_mandatory_arguments> can have constraints,\ntoo. Any C<where> clause on any parameter will be executed, even if it's\noptional and not provided by the caller. In that case you may have to guard\nagainst undefined values within the C<where> clause.\n\n    sub f(Int $a, UInt $i? where { !$i.defined or $i > 5 }) { ... }\n\n=head2 Constraining slurpy arguments\n\nL<Slurpy arguments|#Slurpy_parameters> can not have type\nconstraints. A C<where>-clause in conjunction with a L<C<Junction>|/type/Junction>\ncan be used to that effect.\n\n=for code\nsub f(*@a where {$_.all ~~ Int}) { say @a };\nf(42);\nf(<a>);\nCATCH { default { say .^name, ' ==> ', .Str }  }\n# OUTPUT: «[42]␤Constraint type check failed in binding to parameter '@a' ...»\n\n=head2 Constraining named arguments\n\nConstraints against L<named arguments|#Positional_vs._named_arguments> apply to\nthe value part of the L<colon-pair|/type/Pair>.\n\n    sub f(Int :$i){};\n    f :i<forty-two>;\n    CATCH { default { say .^name, ' ==> ', .Str }  }\n    # OUTPUT: «X::TypeCheck::Binding::Parameter ==> Type check failed in\n    # binding to parameter '$i'; expected Int but got Str (\"forty-two\")␤»\n\nX<|Syntax,:D>\nX<|Syntax,:U>\nX<|Syntax,:_>\n\n=head2 Constraining argument definiteness\n\nNormally, a type constraint only checks whether the value of the parameter is of\nthe correct type. Crucially, both I<object instances> and I<type objects> will\nsatisfy such a constraint as illustrated below:\n\n    say  42.^name;    # OUTPUT: «Int␤»\n    say  42 ~~ Int;   # OUTPUT: «True␤»\n    say Int ~~ Int;   # OUTPUT: «True␤»\n\nNote how both C<42> and L<C<Int>|/type/Int> satisfy the match.\n\nSometimes we need to distinguish between these object instances (C<42>)\nand type objects (L<C<Int>|/type/Int>). Consider the following code:\n\n    sub limit-lines(Str $s, Int $limit) {\n        my @lines = $s.lines;\n        @lines[0 .. min @lines.elems, $limit].join(\"\\n\")\n    }\n    say (limit-lines \"a \\n b \\n c \\n d \\n\", 3).raku; # \"a \\n b \\n c \\n d \"\n    say limit-lines Str, 3;\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Multi::NoMatch: Cannot resolve caller lines(Str: );\n    # none of these signatures match:\n    #     (Str:D $: :$count!, *%_)\n    #     (Str:D $: $limit, *%_)\n    #     (Str:D $: *%_)»\n    say limit-lines \"a \\n b\", Int; # Always returns the max number of lines\n\nHere we really only want to deal with string instances, not type objects. To do\nthis, we can use the C<:D> type constraint.  This constraint checks that the\nvalue passed is an I<object instance>, in a similar fashion to calling its\nL<DEFINITE|/language/mop#DEFINITE> (meta)method.\n\nTo warm up, let's apply C<:D> to the right-hand side of our humble L<C<Int>|/type/Int>\nexample:\n\n    say  42 ~~ Int:D;  # OUTPUT: «True␤»\n    say Int ~~ Int:D;  # OUTPUT: «False␤»\n\nNote how only C<42> matches C<Int:D> in the above.\n\nReturning to C<limit-lines>, we can now amend its signature to catch the error\nearly:\n\n    sub limit-lines(Str:D $s, Int $limit) { };\n    say limit-lines Str, 3;\n    CATCH { default { put .^name ~ '--' ~ .Str } };\n    # OUTPUT: «Parameter '$s' of routine 'limit-lines' must be an object instance of type 'Str',\n    #          not a type object of type 'Str'.  Did you forget a '.new'?»\n\nThis is much better than the way the program failed before, since here the\nreason for failure is clearer.\n\nIt's also possible that I<type objects> are the only ones that make\nsense for a routine to accept. This can be done with the C<:U> type\nconstraint, which checks whether the value passed is a type object\nrather than an object instance. Here's our L<C<Int>|/type/Int> example again, this\ntime with C<:U> applied:\n\n    say  42 ~~ Int:U;  # OUTPUT: «False␤»\n    say Int ~~ Int:U;  # OUTPUT: «True␤»\n\nNow C<42> fails to match C<Int:U> while L<C<Int>|/type/Int> succeeds.\n\nHere's a more practical example:\n\n    sub can-turn-into(Str $string, Any:U $type) {\n       return so $string.$type;\n    }\n    say can-turn-into(\"3\", Int);        # OUTPUT: «True␤»\n    say can-turn-into(\"6.5\", Int);      # OUTPUT: «True␤»\n    say can-turn-into(\"6.5\", Num);      # OUTPUT: «True␤»\n    say can-turn-into(\"a string\", Num); # OUTPUT: «False␤»\n\nCalling C<can-turn-into> with an object instance as its second parameter\nwill yield a constraint violation as intended:\n\n=for code :preamble< sub can-turn-into(Str $, Any:U $) {...}>\nsay can-turn-into(\"a string\", 123);\n# OUTPUT: «Parameter '$type' of routine 'can-turn-into' must be a type object\n# of type 'Any', not an object instance of type 'Int'...»\n\nFor explicitly indicating the normal behavior, that is, not constraining whether\nthe argument will be an instance or a type object, C<:_> can be used but this\nis unnecessary since this is the default constraint (of this kind) on arguments.\nThus, C<:(Num:_ $)> is the same as C<:(Num $)>.\n\nTo recap, here is a quick illustration of these type constraints, also\nknown collectively as I<type smileys>:\n\n    # Checking a type object\n    say Int ~~ Any:D;    # OUTPUT: «False␤»\n    say Int ~~ Any:U;    # OUTPUT: «True␤»\n    say Int ~~ Any:_;    # OUTPUT: «True␤»\n\n    # Checking a subset\n    subset Even of Int where * %% 2;\n    say 3 ~~ Even:D;     # OUTPUT: «False␤»\n    say 3 ~~ Even:U;     # OUTPUT: «False␤»\n    say Int ~~ Even:U;   # OUTPUT: «Use of uninitialized value of type Int in numeric context␤...␤True␤»\n\n    # Checking an object instance\n    say 42 ~~ Any:D;     # OUTPUT: «True␤»\n    say 42 ~~ Any:U;     # OUTPUT: «False␤»\n    say 42 ~~ Any:_;     # OUTPUT: «True␤»\n\n    # Checking a user-supplied class\n    class Foo {};\n    say Foo ~~ Any:D;    # OUTPUT: «False␤»\n    say Foo ~~ Any:U;    # OUTPUT: «True␤»\n    say Foo ~~ Any:_;    # OUTPUT: «True␤»\n\n    # Checking an instance of a class\n    my $f = Foo.new;\n    say $f  ~~ Any:D;    # OUTPUT: «True␤»\n    say $f  ~~ Any:U;    # OUTPUT: «False␤»\n    say $f  ~~ Any:_;    # OUTPUT: «True␤»\n\nThe L<Classes and Objects|/language/classtut>\ndocument further elaborates on the concepts of instances and type\nobjects and discovering them with the C<.DEFINITE> method.\n\nKeep in mind all parameters have values; even optional ones have default\nvalues that are the type object of the constrained type for explicit type\nconstraints. If no explicit type constraint exists, the default value is an\nL<C<Any>|/type/Any> type object for methods, submethods, and subroutines, and a\nL<C<Mu>|/type/Mu> type object for blocks. This means that if you use the C<:D>\ntype smiley, you'd need to provide a default value or make the parameter\nrequired. Otherwise, the default value would be a type object, which would\nfail the definiteness constraint.\n\n    sub divide (Int:D :$a = 2, Int:D :$b!) { say $a/$b }\n    divide :1a, :2b; # OUTPUT: «0.5␤»\n\nThe default value will kick in when that particular parameter, either\npositional or named, gets no value I<at all>.\n\n    sub f($a = 42){\n      my $b is default('answer');\n      say $a;\n      $b = $a;\n      say $b\n    };\n    f;     # OUTPUT: «42␤42␤»\n    f Nil; # OUTPUT: «Nil␤answer␤»\n\nC<$a> has 42 as its default value. With no value, C<$a> will be assigned the\ndefault value declared in the L<C<Signature>|/type/Signature>. However, in the second case, the parameter C<$a>\nI<does> receive a value, which happens to be L<C<Nil>|/type/Nil>. Assigning L<C<Nil>|/type/Nil> to\nany I<variable> resets it to its default value, which for C<$b> has been declared as\nC<'answer'> by use of the I<default> trait. That explains what happens the second time we call C<f>.\nRoutine parameters and variables deal differently with default value,\nwhich is in part clarified by the different way default values are\ndeclared in each case (using C<=> for parameters, using the C<default>\ntrait for variables).\n\nNote: in 6.c language, the default value of C<:U>/C<:D> constrained\nvariables was a type object with such a constraint, which is not initializable,\nthus you cannot use the C<.=> operator, for example.\n\n=for code :solo\nuse v6.c;\nmy Int:D $x .= new: 42;\n# OUTPUT: You cannot create an instance of this type (Int:D)\n# in block <unit> at -e line 1\n\nIn the 6.d language, the default I<default> is the type object without the smiley\nconstraint:\n\n=for code :solo\nuse v6.d;\nmy Int:D $x .= new: 42; # OUTPUT: «42␤»\n\nA closing remark on terminology: this section is about the use of the type\nsmileys C<:D> and C<:U> to constrain the definiteness of arguments.\nOccasionally I<definedness> is used as a synonym for I<definiteness>; this may\nbe confusing, since the terms have subtly different meanings.\n\nAs explained above, I<definiteness> is concerned with the distinction between\ntype objects and object instances. A type object is always indefinite, while an\nobject instance is always definite. Whether an object is a type\nobject/indefinite or an object instance/definite can be verified using the\nL<DEFINITE|/language/mop#DEFINITE> (meta)method.\n\nI<Definiteness> should be distinguished from I<definedness>, which is concerned\nwith the difference between defined and undefined objects. Whether an object is\ndefined or undefined can be verified using the C<defined>-method, which is\nimplemented in class L<C<Mu>|/type/Mu>. By default a type object is considered\nundefined, while an object instance is considered defined; that is: C<.defined>\nreturns C<False> on a type object, and C<True> otherwise. But this default\nbehavior may be overridden by subclasses. An example of a subclass that\noverrides the default C<.defined> behavior is L<C<Failure>|/type/Failure>,\nso that even an instantiated L<C<Failure>|/type/Failure> acts as an undefined value:\n\n    my $a = Failure;                # Initialize with type object\n    my $b = Failure.new(\"foo\");     # Initialize with object instance\n    say $a.DEFINITE;                # OUTPUT: «False␤» : indefinite type object\n    say $b.DEFINITE;                # OUTPUT: «True␤»  : definite object instance\n    say $a.defined;                 # OUTPUT: «False␤» : default response\n    say $b.defined;                 # OUTPUT: «False␤» : .defined override\n\n=head2 Constraining signatures of L<C<Callable>|/type/Callable>s\n\nThe signature of a L<C<Callable>|/type/Callable> parameter can be constrained by\nspecifying a L<C<Signature>|/type/Signature> literal right after the parameter\n(no whitespace allowed):\n\n    =begin code :skip-test<compile time error>\n    sub apply(&l:(Int:D --> Int:D), Int:D \\n) {\n        l(n)\n    }\n\n    sub double(Int:D \\x --> Int:D) { 2 * x }\n    say apply &double, 10;         # OUTPUT: «20␤»\n\n    sub general-double(Numeric:D \\x --> Numeric:D) { 2 * x }\n    say apply &general-double, 10; # OUTPUT: «Signature constraint check failed(…)␤»\n    =end code\n\nThis shorthand syntax for constraining the signature of C<&l>\nis only available because it has the C<&> sigil.\nFor C<$>-sigiled callable parameters, you need to use the long version with C<where>:\n\n    sub apply($l where .signature ~~ :(Int:D --> Int:D), Int:D \\n) {\n        $l(n)\n    }\n\nYou can also pass typed L<lambdas|/language/functions#Blocks_and_lambdas>\nfor constrained callable parameters like C<&l> or C<$l>:\n\n=for code :preamble<sub apply {...}>\nsay apply -> Int:D \\x --> Int:D { 2 * x }, 3;  # OUTPUT: «6␤»\nsay apply -> Int:D \\x --> Int:D { x ** 3 }, 3; # OUTPUT: «27␤»\n\nConstraints without type smileys are also possible.\n\n   sub play-with-tens(&c:(Int, Str)) { say c(10, 'ten') }\n   play-with-tens ->   Int \\i, Str \\s { s ~ i }                 # OUTPUT: «ten10»\n   play-with-tens ->   Int \\i, Str \\s { s x (1..30).roll mod i} # OUTPUT: «tenten(…)ten␤»\n\n=head2 Constraining return types\n\nThere are multiple ways to constrain return types on a\nL<C<Routine>|/type/Routine>. All versions below are currently valid and\nwill force a type check on successful execution of a routine.\n\nL<C<Nil>|/type/Nil> and L<C<Failure>|/type/Failure> are always allowed\nas return types, regardless of any type constraint. This allows\nL<C<Failure>|/type/Failure> to be returned and passed on down the call\nchain.\n\n    sub foo(--> Int) { Nil };\n    say foo.raku; # OUTPUT: «Nil␤»\n\nA L<captured type|/language/signatures#Type_captures> can also be used\nas the return type constraint (see there for details).\n\nX«|Syntax,-->»\nX«|Syntax,Return type arrow»\n=head3 Return type arrow: C«-->»\n\nThis form of indicating return types (or constants) in the signature is\npreferred, since it can handle constant values while the others can't. For\nconsistency, it is the only form accepted on this site.\n\nThe return type arrow has to be placed at the end of the parameter list,\nwith or without a C<,> before it.\n\n=begin code\nsub greeting1(Str $name  --> Str) { say \"Hello, $name\" } # Valid\nsub greeting2(Str $name, --> Str) { say \"Hello, $name\" } # Valid\n\nsub favorite-number1(--> 42) {        } # OUTPUT: 42\nsub favorite-number2(--> 42) { return } # OUTPUT: 42\n=end code\n\nIf the type constraint is a constant expression, it is used as the\nreturn value of the routine. Any return statement in that routine has to\nbe argumentless.\n\n=begin code\nsub foo(Str $word --> 123) { say $word; return; }\nmy $value = foo(\"hello\"); # OUTPUT: hello\nsay $value;               # OUTPUT: 123\n=end code\n\n=begin code :skip-test<compile time error>\n# The code below will not compile\nsub foo(Str $word --> 123) { say $word; return $word; }\nmy $value = foo(\"hello\");\nsay $value;\n=end code\n\n=head3 C<returns>\n\nThe keyword C<returns> following a signature declaration has the same function\nas C«-->» with the caveat that this form does not work with constant values. You\ncannot use it in a block either. That is why the pointy arrow form is always\npreferred.\n\n=for code\nsub greeting(Str $name) returns Str { say \"Hello, $name\" }; # Valid\nsay &greeting.signature  # OUTPUT: «(Str $name --> Str)␤»\n\n=for code :skip-test<compile time error>\nsub favorite-number returns 42 { }; # This will fail.\n\n=head3 C<of>\n\nC<of> is just the real name of the C<returns> keyword.\n\n=for code\nsub foo() of Int { 42 }; # Valid\nsay &foo.signature       # OUTPUT: «( --> Int)␤»\n\n=for code :skip-test<compile time error>\nsub foo() of 42 { };     # This will fail.\n\n=head3 prefix (C-like) form\n\nThis is similar to placing type constraints on variables like C<my Type $var =\n20;>, except the C<$var> is a definition for a routine.\n\n=for code\nmy Int sub bar { 1 };     # Valid\nsay &bar.signature        # OUTPUT: «( --> Int)␤»\n\n=for code :skip-test<compile time error>\nmy 42 sub bad-answer { }; # This will fail.\n\n=head2 X<Coercion type|Language,Coercion type>\n\nTo accept one type but coerce it automatically to another, use the\naccepted type as an argument to the target type. If the accepted type is\nL<C<Any>|/type/Any> it can be omitted.\n\n    sub f(Int(Str) $becomes-int, Str() $becomes-str) {\n        say $becomes-int.^name ~ ' ' ~ $becomes-str.^name\n    }\n    f '10', 10;\n    # OUTPUT: «Int Str␤»\n\n    sub foo(Date(Str) $d) { say $d.^name; say $d };\n    foo \"2016-12-01\";\n    # OUTPUT: «Date␤2016-12-01␤»\n\nThe coercion is performed by calling the method with the name of the\ntype to coerce to, if it exists. In this example, we're calling the\nbuiltin method L<C<Date>|/type/Date> on the L<C<Str>|/type/Str> class. The method is assumed\nto return the correct type—no additional checks on the result are\ncurrently performed.\n\nCoercion can also be performed on return types:\n\n=begin code\nsub square-str (Int $x --> Str(Int)) {\n    $x²\n}\n\nfor 2,4, *²  … 256 -> $a {\n    say $a, \"² is \", square-str( $a ).chars, \" figures long\";\n}\n\n# OUTPUT: «2² is 1 figures long␤\n#          4² is 2 figures long␤\n#          16² is 3 figures long␤\n#          256² is 5 figures long␤»\n=end code\n\nIn this example, coercing the return type to L<C<Str>|/type/Str> allows us to\ndirectly apply string methods, such as the number of characters.\n\nB<Note>: The appropriate method must be available on the argument, so be careful\nwhen trying to coerce custom types.\n\n=begin code\nclass Foo { }\n\nsub bar(Foo(Int) $x) { say $x }\n\nbar(3);\n# OUTPUT: «Impossible coercion from 'Int' into 'Foo': no acceptable coercion method found␤»\n=end code\n\n\nX<|Language,Type capture>\n=head1 Type captures\n\nType captures allow deferring the specification of a type constraint to the time\nthe function is called. They allow referring to a type both in the signature and\nthe function body.\n\n    sub f(::T $p1, T $p2, ::C){\n        # $p1 and $p2 are of the same type T, that we don't know yet\n        # C will hold a type we derive from a type object or value\n        my C $division = $p1 / $p2;\n        return sub (T $p1) {\n            $division * $p1;\n        }\n    }\n\n    # The first parameter is Int and so must be the 2nd.\n    # We derive the 3rd type from calling the operator that is used in &f.\n    my &s = f(10, 2, Int.new / Int.new);\n    say s(2); # 10 / 2 * 2 == 10\n\nA captured type can be used as the return type constraint\n(cf. L<Constraining return types|/language/signatures#Constraining_return_types>):\n\n    sub cast-by-example(Any $x, ::T $example --> T) { T($x) }\n    sub cast-or-create(Any $x, ::T $example --> T:D) { with $x { T($x) } else { T.new } }\n\nCaptured types can also be used to coerce other parameters to that type\n(just like it is done in section L<Coercion types|/language/signatures#Coercion_type>\nfor fixed types).\nFor example, this function coerces the second parameter C<b>, which must be of type L<C<Cool>|/type/Cool>,\nto whichever type the first parameter C<a> has:\n\n    sub accum( ::T \\a, T(Cool) \\b ) { a += b };\n\n    my $t = 3;        # Int\n    accum( $t, 5/3 ); # OUTPUT: «4␤»\n\n    my $t = 3.0;      # Rat\n    accum( $t, 5/3 ); # OUTPUT: «4.666667␤»\n\n    my $t = 3.0;      # Rat, and the second parameter an Array\n    accum ( $t, [\"x\",\"y\"] ); # OUTPUT: «5.0»\n\nType captures can also be subject to type constraints.\nIn the example above, certain nonsensical calls could be prevented by changing\nthe signature to one of the following:\n\n    =for code :skip-test<simple snippet>\n    (Numeric ::T \\a, T(Cool) \\b )\n    (::T Numeric \\a, T(Cool) \\b )\n\nSee also section L<method type_captures|/type/Parameter#method_type_captures>\nin the type reference for L<C<Parameter>|/type/Parameter>.\n\n\nX<|Language,positional argument>\nX<|Language,named argument>\n=head1 Positional vs. named arguments\n\nAn argument can be I<positional> or I<named>. By default, arguments are\npositional, except slurpy hash and arguments marked with a leading colon C<:>.\nThe latter is called a L<colon-pair|/type/Pair>. Check the following signatures\nand what they denote:\n\n=for code :preamble<my ($sig1, $sig2, $sig3, $sig4);>\n$sig1 = :($a);               # a positional argument\n$sig2 = :(:$a);              # a named argument of name 'a'\n$sig3 = :(*@a);              # a slurpy positional argument\n$sig4 = :(*%h);              # a slurpy named argument\n\nOn the caller side, positional arguments are passed in the same order as the\narguments are declared.\n\n    sub pos($x, $y) { \"x=$x y=$y\" }\n    pos(4, 5);                          # OUTPUT: «x=4 y=5»\n\nIn the case of named arguments and parameters, only the name is used for mapping\narguments to parameters. If a fat arrow is used to construct a\nL<C<Pair>|/type/Pair> only those with valid identifiers as keys are recognized as\nnamed arguments.\n\n=for code\nsub named(:$x, :$y) { \"x=$x y=$y\" }\nnamed( y => 5, x => 4);             # OUTPUT: «x=4 y=5»\n\nYou can invoke the routine using a variable with the same name as the named\nargument; in that case C<:> will be used for the invocation so that the name of\nthe variable is understood as the key of the argument.\n\n    sub named-shortcut( :$shortcut ) {\n        say \"Looks like $shortcut\"\n    }\n    named-shortcut( shortcut => \"to here\"); # OUTPUT: «Looks like to here␤»\n    my $shortcut = \"Þor is mighty\";\n    named-shortcut( :$shortcut );           # OUTPUT: «Looks like Þor is mighty␤»\n\nIt is possible to have a different name for a named argument than the\nvariable name:\n\n    sub named(:official($private)) { \"Official business!\" if $private }\n    named :official;\n\n\nX<|Syntax,*@>\nX<|Syntax,*%>\nX<|Language,slurpy argument>\n=head1 Slurpy parameters\n\nA function is X<variadic|Reference,variadic> if it can take a varying number of arguments; that is,\nits arity is not fixed. Therefore,\nL<optional|/language/signatures#Optional_and_mandatory_arguments>,\nnamed, and slurpy parameters\nmake routines that use them I<variadic>, and by extension are called variadic\narguments. Here we will focus on slurpy parameters, or simply I<slurpies>.\n\nAn array or hash parameter can be\nmarked as I<slurpy> by a leading single (C<*>) or double asterisk (C<**>) or a\nleading plus (C<+>). A slurpy parameter can bind to an arbitrary number of\narguments (zero or more), and it will result in a type that is compatible\nwith the sigil.\n\nThese are called \"slurpy\" because they slurp up any remaining arguments\nto a function, like someone slurping up noodles.\n\n=begin code\nmy $sig1 = :($a, @b);  # exactly two arguments, second must be Positional\nmy $sig2 = :($a, *@b); # at least one argument, @b slurps up any beyond that\nmy $sig3 = :(*%h);     # no positional arguments, but any number\n                       # of named arguments\n\nsub one-arg (@)  { }\nsub slurpy  (*@) { }\none-arg (5, 6, 7); # ok, same as one-arg((5, 6, 7))\nslurpy  (5, 6, 7); # ok\nslurpy   5, 6, 7 ; # ok\n# one-arg(5, 6, 7) ; # X::TypeCheck::Argument\n# one-arg  5, 6, 7 ; # X::TypeCheck::Argument\n\nsub named-names (*%named-args) { %named-args.keys };\nsay named-names :foo(42) :bar<baz>; # OUTPUT: «foo bar␤»\n=end code\n\nPositional and named slurpies can be combined; named arguments (i.e., L<C<Pair>|/type/Pair>s)\nare collected in the specified hash, positional arguments in the array:\n\n=begin code\nsub combined-slurpy (*@a, *%h) { { array => @a, hash => %h } }\n# or: sub combined-slurpy (*%h, *@a) { ... }\n\nsay combined-slurpy(one => 1, two => 2);\n# OUTPUT: «{array => [], hash => {one => 1, two => 2}}␤»\nsay combined-slurpy(one => 1, two => 2, 3, 4);\n# OUTPUT: «{array => [3 4], hash => {one => 1, two => 2}}␤»\nsay combined-slurpy(one => 1, two => 2, 3, 4, five => 5);\n# OUTPUT: «{array => [3 4], hash => {five => 5, one => 1, two => 2}}␤»\nsay combined-slurpy(one => 1, two => 2, 3, 4, five => 5, 6);\n# OUTPUT: «{array => [3 4 6], hash => {five => 5, one => 1, two => 2}}␤»\n=end code\n\nNote that positional parameters aren't allowed after slurpy (or, in\nfact, after any type of variadic) parameters:\n\n=begin code :skip-test<compile time error>\n:(*@args, $last);\n# ===SORRY!=== Error while compiling:\n# Cannot put required parameter $last after variadic parameters\n=end code\n\nNormally a slurpy parameter will create an L<C<Array>|/type/Array> (or compatible\ntype), create a new L<C<Scalar>|/type/Scalar> container for each argument, and\nassign the value from each argument to those L<C<Scalar>|/type/Scalar>s.  If the original\nargument also had an intermediary L<C<Scalar>|/type/Scalar> it is bypassed during this process,\nand is not available inside the called function.\n\nSigiled parameters will always impose a L<context|/language/contexts> on the collected arguments.\nSigilless parameters can also be used slurpily, preceded by a + sign, to\nwork with whatever initial type they started with:\n\n=for code\nsub zipi( +zape ) {\n    zape.^name => zape\n};\nsay zipi( \"Hey \"); # OUTPUT: «List => (Hey )␤»\nsay zipi( 1...* ); # OUTPUT: «Seq => (...)␤»\n\nSlurpy parameters have special behaviors when combined with some\nL<traits and modifiers|#Parameter_traits_and_modifiers>,\nas described in\nL<the section on slurpy array parameters|/language/signatures#Types_of_slurpy_array_parameters>.\n\nL<Methods|/type/Method> automatically get a C<*%_> slurpy named parameter added if they\ndon't have one declared.\n\n=head1 Types of slurpy array parameters\n\nThere are three variations to slurpy array parameters.\n\n=item The single-asterisk form C<*@> flattens passed arguments.\n\n=item The double-asterisk form C<**@> does not flatten arguments.\n\n=item The plus form C<+@> flattens according to the L<single argument rule|/language/list#Single_Argument_Rule>.\n\nWe now describe each of them in detail.\n\n=head2 X<Flattening slurpy: C<*@>|Syntax,*@>\n\nSlurpy parameters declared with one asterisk will flatten arguments by\ndissolving one or more layers of bare L<C<Iterable>|/type/Iterable>s.\n\n=begin code\nmy @array = <a b c>;\nmy $list := <d e f>;\nsub a(*@a)  { @a.raku.say };\na(@array);                 # OUTPUT: «[\"a\", \"b\", \"c\"]␤»\na(1, $list, [2, 3]);       # OUTPUT: «[1, \"d\", \"e\", \"f\", 2, 3]␤»\na([1, 2]);                 # OUTPUT: «[1, 2]␤»\na(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, 1, 2, 3, 4, 5]␤»\na(($_ for 1, 2, 3));       # OUTPUT: «[1, 2, 3]␤»\n=end code\n\nA single-asterisk slurpy flattens all given iterables, effectively hoisting any\nobject created with commas up to the top level.\n\nSuch flattening can be prevented for individual arguments\nby putting them in an L<item context|/type/List#Items,_flattening_and_sigils>.\nThis can be done by prepending a C<$> sigil or by applying the C<.item> method:\n\n=begin code\nsub normally-this-flattens(*@pos) { say @pos; }\nmy @array = [5,6];\nnormally-this-flattens([1,2], $[3,4], $@array);        # OUTPUT: «[1 2 [3 4] [5 6]]␤»\nnormally-this-flattens([1,2], [3,4].item, @array.item) # OUTPUT: «[1 2 [3 4] [5 6]]␤»\n=end code\n\n=head2 X<Non-flattening slurpy: C<**@>|Syntax,**@>\n\nSlurpy parameters declared with two stars do not flatten any\nL<C<Iterable>|/type/Iterable> arguments within the list, but keep the arguments\nmore or less as-is:\n\n=begin code\nmy @array = <a b c>;\nmy $list := <d e f>;\nsub b(**@b) { @b.raku.say };\nb(@array);                 # OUTPUT: «[[\"a\", \"b\", \"c\"],]␤»\nb(1, $list, [2, 3]);       # OUTPUT: «[1, (\"d\", \"e\", \"f\"), [2, 3]]␤»\nb([1, 2]);                 # OUTPUT: «[[1, 2],]␤»\nb(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, [1, 2], ([3, 4], 5)]␤»\nb(($_ for 1, 2, 3));       # OUTPUT: «[(1, 2, 3),]␤»\n=end code\n\nThe double-asterisk slurpy hides the nested comma objects and leaves them as-is\nin the slurpy array.\n\nX<|Syntax,+ (Single argument rule slurpy)>\n=head2 Single argument rule slurpy: C<+@>\n\nA slurpy parameter created using a plus engages the L<single argument rule|/language/list#Single_Argument_Rule>,\nwhich decides how to handle the slurpy argument based on context. Basically,\nif only a single argument is passed and that argument is\nL<C<Iterable>|/type/Iterable>, that argument is used to fill the slurpy parameter\narray. In any other case, C<+@> works like C<**@>.\n\n=begin code\nmy @array = <a b c>;\nmy $list := <d e f>;\nsub c(+@b) { @b.raku.say };\nc(@array);                 # OUTPUT: «[\"a\", \"b\", \"c\"]␤»\nc(1, $list, [2, 3]);       # OUTPUT: «[1, (\"d\", \"e\", \"f\"), [2, 3]]␤»\nc([1, 2]);                 # OUTPUT: «[1, 2]␤»\nc(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, [1, 2], ([3, 4], 5)]␤»\nc(($_ for 1, 2, 3));       # OUTPUT: «[1, 2, 3]␤»\n=end code\n\nFor additional discussion and examples, see L<Slurpy Conventions for Functions|/language/functions#Slurpy_conventions>.\n\n\nX<|Language,argument aliases>\n=head1 Argument aliases\n\nThe L<colon-pair|/type/Pair> syntax can be used to provide aliases for\narguments:\n\n    sub alias-named(:color(:$colour), :type(:class($kind))) {\n        say $colour ~ \" \" ~ $kind\n    }\n    alias-named(color => \"red\", type => \"A\");    # both names can be used\n    alias-named(colour => \"green\", type => \"B\"); # more than two names are ok\n    alias-named(color => \"white\", class => \"C\"); # every alias is independent\n\nThe presence of the colon C<:> will decide whether we are creating a new named\nargument or not. C<:$colour> will not only be the name of the aliased variable,\nbut also a new named argument (used in the second invocation). However,\nC<$kind> will just be the name of the aliased variable, that does not create a\nnew named argument. More uses of aliases can be found in\nL<sub MAIN|/language/create-cli#Aliases_for_named_parameters>.\n\nA function with named arguments can be called dynamically, dereferencing a\nL<C<Pair>|/type/Pair> with C<|> to turn it into a named argument.\n\n    multi f(:$named) { note &?ROUTINE.signature };\n    multi f(:$also-named) { note &?ROUTINE.signature };\n    for 'named', 'also-named' -> $n {\n        f(|($n => rand))                # OUTPUT: «(:$named)␤(:$also-named)␤»\n    }\n\n    my $pair = :named(1);\n    f |$pair;                           # OUTPUT: «(:$named)␤»\n\nThe same can be used to convert a L<C<Hash>|/type/Hash> into named arguments.\n\n    sub f(:$also-named) { note &?ROUTINE.signature };\n    my %pairs = also-named => 4;\n    f |%pairs;                              # OUTPUT: «(:$also-named)␤»\n\nA L<C<Hash>|/type/Hash> that contains a list may prove problematic when slipped into named\narguments. To avoid the extra layer of containers coerce to L<C<Map>|/type/Map>\nbefore slipping.\n\n    class C { has $.x; has $.y; has @.z };\n    my %h = <x y z> Z=> (5, 20, [1,2]);\n    say C.new(|%h.Map);\n    # OUTPUT: «C.new(x => 5, y => 20, z => [1, 2])␤»\n\nYou can create as many aliases to a named argument as you want:\n\n=for code\nsub alias-named(:color(:$colour),\n                :variety(:style(:sort(:type(:class($kind)))))) {\n    return $colour ~ \" \" ~ $kind\n}\nsay alias-named(color => \"red\", style => \"A\");\nsay alias-named(colour => \"green\", variety => \"B\");\nsay alias-named(color => \"white\", class => \"C\");\n\nYou can create named arguments that do not create any variables by\nmaking the argument an alias for an\nL<anonymous argument|#index-entry-anonymous_arguments>. This can be\nuseful when using named arguments solely as a means of selecting a\nC<multi> candidate, which is often the case with traits, for instance:\n\n=begin code\n# Timestamps calls to a routine.\nmulti trait_mod:<is>(Routine:D $r is raw, :timestamped($)!) {\n    $r does my role timestamped { has Instant:D @.timestamps };\n    $r.wrap: -> | { ENTER $r.timestamps.push: now; callsame };\n}\n\nsub foo is timestamped { }\nfoo;\nsay +&foo.?timestamps; # OUTPUT: «1␤»\n=end code\n\nX<|Language,optional argument>\n=head1 Optional and mandatory arguments\n\nPositional parameters are mandatory by default, and can be made optional\nwith a default value or a trailing question mark:\n\n=for code :preamble<my ($sig1, $sig2, $sig3);>\n$sig1 = :(Str $id);         # required parameter\n$sig2 = :($base = 10);      # optional parameter, default value 10\n$sig3 = :(Int $x?);         # optional parameter, default is the Int type object\n\nX<|Language,mandatory named argument>\nNamed parameters are optional by default, and can be made mandatory with a\ntrailing exclamation mark:\n\n=for code :preamble<my ($sig1, $sig2, $sig3);>\n$sig1 = :(:%config);        # optional parameter\n$sig2 = :(:$debug = False); # optional parameter, defaults to False\n$sig3 = :(:$name!);         # mandatory 'name' named parameter\n\nDefault values can depend on previous parameters, and are (at least\nnotionally) computed anew for each call\n\n=begin code :preamble<my ($sig1, $sig2);>\n$sig1 = :($goal, $accuracy = $goal / 100);\n$sig2 = :(:$excludes = ['.', '..']);        # a new Array for every call\n=end code\n\n=head2 Was an argument passed for a parameter?\n\nTable showing checks of whether an argument was passed for a given parameter:\n\n=begin table\n Parameter kind | Example        | Comment                    | Check for no arg passed\n ===============|================|============================|========================\n Slurpy         | *@array        | Don't check using .defined | if not @array\n Required       | $foo           | Can't be omitted           | (not applicable)\n Optional       | @bar = default | Pick a suitable default¹   | if @bar === default\n=end table\n\n¹ A suitable default is an Object that has a distinct identity, as may be checked by the L<C<WHICH>|/type/Mu#method_WHICH> method.\n\nA parameter with a default is always I<optional>, so there is no need to mark it with a C<?>.\n\nThen you can use the C<===> L<value identity operator|/language/operators#infix_===> in the body of the routine to check\nwhether this exact default object was bound to the parameter. These examples use names like C<PositionalAt> to reflect that the C<.WHICH> test\ninvoked by C<===> returns an object of type L<C<ObjAt>|/type/ObjAt>.\n\nExample with a positional parameter:\n=begin code\nmy constant PositionalAt = Positional.new;\n\nsub a (@list = PositionalAt) { say @list === PositionalAt }\na;              # OUTPUT: «True␤»\na [1, 2, 3];    # OUTPUT: «False␤»\n=end code\n\nExample with some scalar parameters:\n=begin code\nmy constant AnyAt = Any.new;\n\nsub b ($x=AnyAt, :$y=AnyAt) { say $x === AnyAt; say $y === AnyAt }\nb 1;            # OUTPUT: «False␤True␤»\nb 1, :2y;       # OUTPUT: «False␤False␤»\n=end code\n\nIf your parameters are typed, then the L<type smileys|/language/glossary#Type_smiley> can be used with\nL<C<multi>|/language/functions#Multi-dispatch>s like this:\n\n=begin code\nmulti c (Int:U $z)  { say 'Undefined' }\nmulti c (Int:D $z)  { say 'Defined'   }\nmulti c (Int   $z?) { say 'Omitted'   }\nc;              #Omitted\nc (Int);        #Undefined\nc 42;           #Defined\n=end code\n\n=head1 Dynamic variables\n\nL<Dynamic variables|/language/variables#The_*_twigil> are allowed in signatures\nalthough they don't provide special behavior because argument binding does\nconnect two scopes anyway.\n\nX<|Language,destructuring arguments>\n=head1 Destructuring arguments\n\nNon-scalar parameters can be followed or substituted by a sub-signature in\nparentheses, which will destructure the argument given. The destructuring of a\nlist is just its elements:\n\n    sub first(@array ($first, *@rest)) { $first }\n\nor\n\n    sub first([$f, *@]) { $f }\n\nWhile the destructuring of a hash is its pairs:\n\n    sub all-dimensions(% (:length(:$x), :width(:$y), :depth(:$z))) {\n        $x andthen $y andthen $z andthen True\n    }\n\nPointy loops can also destructure hashes, allowing assignment to variables:\n\n    my %hhgttu = (:40life, :41universe, :42everything);\n    for %hhgttu -> (:$key, :$value) {\n      say \"$key → $value\";\n    }\n    # OUTPUT: «universe → 41␤life → 40␤everything → 42␤»\n\nIn general, an object is destructured based on its attributes. A common idiom\nis to unpack a L<C<Pair>|/type/Pair>'s key and value in a for loop:\n\n    for <Peter Paul Merry>.pairs -> (:key($index), :value($guest)) { }\n\nHowever, this unpacking of objects as their attributes is only the default\nbehavior. To make an object get destructured differently, change its\nL<C<Capture>|/routine/Capture> method.\n\nX<|Language,sub-signature>\n=head1 Sub-signatures\n\nTo match against a compound parameter use a sub-signature following the argument\nname in parentheses.\n\n    sub foo(\\p(Int, Str)){\n       put \"called with {p.raku}\"\n    };\n    foo((42, \"answer\"));\n    # OUTPUT: «called with (42, \"answer\")␤»\n\nSub-signatures can themselves use most of the syntax available for signatures.\n\n    sub bar(\\p(Int $y where * > 5, Str $s?, *%h)) { put p.raku; put $s // \"undefined\"; }\n    bar((42, life => 40, universe => 41));\n    # OUTPUT: «(42, :life(40), :universe(41))␤undefined␤»\n\n=head1 X<Capture parameters|Syntax,|>\n\nPrefixing a parameter with a vertical bar C<|> makes the parameter a\nL<C<Capture>|/type/Capture>, using up all the remaining positional and named\narguments.\n\n    sub a(Int $i, |cap) { say $i; say cap.gist }\n    a(42, universe => 41, 1, 2, 3);\n    # OUTPUT: ›42␤\\(1, 2, 3, :universe(41))␤»\n\nArguments captured to a variable can be forwarded as a whole using the slip\noperator C<|>.\n\n    sub b(Int $i, Str $s) { say $i.^name ~ ' ' ~ $s.^name }\n    sub c(|cap) { say cap.^name; b(|cap) }\n    c(42, \"answer\");\n    # OUTPUT: «Capture␤Int Str␤»\n\nOne can also constrain the arguments subject to a L<C<Capture>|/type/Capture> by using a sub-signature.\n\n    sub d(|cap(Int, Str, *%)) { put \"called with {cap.raku}\" };\n    d(41);\n    # OUTPUT: «Too few positionals passed to 'd'; expected 2 arguments but got 1 in sub-signature or parameter cap␤ ...»\n\nI<Unbound> L<C<Capture>|/type/Capture>s are often used in C<proto> definitions (like C<proto foo (|) {*}>) to\nindicate that the routine's L<C<multi> definitions|/syntax/multi> can have any L<type\nconstraints|#Type_constraints>. See L<proto|/language/functions#proto> for an\nexample.\n\n=head1 X<The C«;;» separator|Syntax,double-semicolon>\n\nX<|Language,Long names>\nIn L<multiple dispatch|/language/Functions#Multi-dispatch>, when more than one multi signature matches\nthe given input parameters, the narrowest signature wins.\n\nWhen a double semicolon C<;;> is present in a signature,\nonly parameters to the left of the C<;;> are considered in this narrowness analysis.\nIt can take the place of a comma, or be at the very beginning:\n\n    multi foo (;; Numeric $a) { say \"numeric\" };\n    multi foo (;; Int     $a) { say \"int\" };\n    foo(42);\n    # OUTPUT: «Ambiguous call to 'foo(Int)'; these signatures all match:\n    #           (;; Numeric $a) from <unknown file> line 1\n    #           (;; Int $a) from <unknown file> line 1␤...»\n    # (Without the ;; the output would have been «int».)\n\nThis can be useful when the usual order of precedence is undesired.\nConsider this example with a named parameter:\n\n    multi bar(Int $i) { say \"just $i\" };\n    multi bar(Int $i, Str :$s) { say \"both $i and ｢$s.raku｣\" };\n    bar(42);\n    # OUTPUT: «Use of uninitialized value of type Str in string context.␤(...)\n    #           both 42 and ｢｣␤  in sub e at <tmp> line 1␤»\n\nHere it was the I<second> multi that got executed,\nbecause its signature is narrower than the first and does in fact match C<bar(42)>, even though C<$s> then stays undefined.\nBy adding C<;;>, we can lower its precedence to match that of the first:\n\n    multi baz(Int $i) { say \"just $i\" };\n    multi baz(Int $i;; Str :$s) { say \"both $i and ｢$s｣\" };\n    baz(42);\n    # OUTPUT: «Ambiguous call to 'baz(Int)'; these signatures all match:\n    #           (Int $i) from <tmp> line 1␤  (Int $i;; Str :$s) from <tmp> line 1␤ ...»\n\nOne could then give the first multi the trait L<C<is default>|/type/Routine#trait_is_default>, whose exact effect is\nto break a tie between signatures of the same precedence.\n\nThere is more than one way to control the narrowness\n(and thereby, precedence) of signatures. Other options include\nmaking parameters optional via C<?> or required via C<!>.\n\nThe double semicolon C<;;> can also be used in signatures of L<parameterized roles|/language/typesystem#Parameterized>.\nParameterized roles have a so-called \"long name\" generated from their signature, which can be used for introspection.\nOnly parameters to the left of C<;;> contribute to it.\n\n=head1 Parameter traits and modifiers\n\nBy default, parameters are bound to their argument and marked as\nread-only. One can change that with traits on the parameter.\n\nX<|Traits,is copy>\nThe C<is copy> trait causes the argument to be copied, and allows it\nto be modified inside the routine\n\n    sub count-up($x is copy) {\n        $x = ∞ if $x ~~ Whatever;\n        .say for 1..$x;\n    }\n\nX<|Traits,is rw>\nThe C<is rw> trait, which stands for I<is read-write>,\nmakes the parameter bind to a variable (or other writable container). Assigning\nto the parameter changes the value of the variable at the caller side.\n\n    sub swap($x is rw, $y is rw) {\n        ($x, $y) = ($y, $x);\n    }\n\nOn slurpy parameters, C<is rw> is reserved for future use by language\ndesigners.\n\nX<|Traits,is raw>\nThe L<C<is raw> trait|/type/Parameter#method_raw> is automatically applied to\nparameters declared with a L<backslash|/language/variables#Sigilless_variables>\nor a L<plus sign|#Single_argument_rule_slurpy>\nas a \"sigil\", and may also be used to make normally sigiled parameters behave\nlike these do. In the special case of slurpies, which normally produce an\nL<C<Array>|/type/Array> full of L<C<Scalar>|/type/Scalar>s as described above, C<is raw> will instead cause\nthe parameter to produce a L<C<List>|/type/List>.  Each element of that list will be bound\ndirectly as raw parameter.\n\nX<|Traits,is readonly>\nTo explicitly ask for a read-only parameter use the C<is readonly> trait.\nPlease note that this applies only to the container. The object inside can very\nwell have mutator methods and Raku will not enforce immutability on the\nattributes of the object.\n\nTraits can be followed by the where clause:\n\n    sub ip-expand-ipv6($ip is copy where m:i/^<[a..f\\d\\:]>**3..39$/) { }\n\n\n=end pod\n"
  },
  {
    "path": "doc/Language/slangs.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"tutorial\")\n\n=TITLE Slangs\n\n=SUBTITLE Slangs in Raku\n\nThe term \"Slang\" is used two different ways within the Raku community:\n\n=item1 To refer to sublanguages within Raku, such as the quoting sublanguage\nor the regex sublanguage.\n\n=item1 To refer to variants of Raku that are created by adding in a slang\nmodule that modifies the grammar of the language.\n\n=head1 Sublanguages within Raku\n\nThe C<~> twigil is for referring to sublanguages (called slangs). The\nfollowing are useful:\n\nX<|Variables,$~MAIN>X<|Variables,$~Quote>X<|Variables,$~Quasi>\nX<|Variables,$~Regex>X<|Variables,$~Trans>X<|Variables,$~P5Regex>\n\n=begin table\n    $~MAIN       the current main language (e.g., Raku statements)\n    $~Quote      the current root of quoting language\n    $~Quasi      the current root of quasiquoting language\n    $~Regex      the current root of regex language\n    $~Trans      the current root of transliteration language\n    $~P5Regex    the current root of the Perl regex language\n=end table\n\nYou C<augment> these languages in your current lexical scope.\n\n=begin code\nuse MONKEY-TYPING;\naugment slang Regex {  # derive from $~Regex and then modify $~Regex\n    token backslash:std<\\Y> { YY };\n}\n=end code\n\nThe C<MONKEY-TYPING> pragma is a necessary prerequisite to using the\nC<augment> keyword.  It can be thought of as a reminder that the\nfollowing code is of a type that's usually discouraged.  More\ndocumentation on C<augment> is at\nL<the augment declarator|/language/variables#The_augment_declarator>.\n\n=head1 Slangs that Modify the Language\n\n=head2 Existing Slangs\n\nMany slangs are made available as modules through zef.  These are useful for:\n\n=item1 Using directly, so you don't have to write your own slang\n\n=item1 As examples, for inspiration in writing your own slangs\n\nTo see the existing Slang modules, we can look at:\n\n=item1 L<Everything tagged Slang|https://raku.land/tags/slang>\n\n=item1 L<A search for slang|https://raku.land/?q=slang>\n\n=head2 Avoiding Slangs\n\nWriting slangs is a beautiful and powerful tool, but sometimes, there's no point killing a mosquito with a flamethrower.\nSometimes, it's best to see if you can achieve something slang-like with\nsimpler tools.\n\nBefore diving into creating a slang, consider these alternatives:\n\n=item1 L<Custom Operators|/language/optut> allow you to define new operators\n(prefix, infix, postfix, circumfix, or postcircumfix) that can be used\nthroughout your code. This is often sufficient when you just need a new\nsyntactic construct for operations.\n\n=item1 L<Custom Traits|/type/Sub#Traits> (created using C<trait_mod>) let you\nadd compile-time behavior to declarations. Traits can modify classes,\nroutines, variables, and other constructs without changing the grammar.\n\n=item1 Custom Declarators (like the C<model> declarator used in Red ORM) allow\nyou to create new keywords that behave similarly to built-in declarators like\nC<class> or C<sub>. While this is a little advanced, it's still less complex\nthan creating a full slang, as it typically involves working with the grammar\nat a more focused level.\n\n=head3 Creating Custom Declarators\n\nThe most direct way to create a custom declarator that works like built-in\ndeclarators (such as C<class>, C<role>, or C<sub>) is to use the\nC<EXPORTHOW::DECLARE> mechanism. This is the approach used by Red ORM for its\nC<model> declarator.\n\n=head4 Using EXPORTHOW::DECLARE\n\nThe C<EXPORTHOW::DECLARE> mechanism allows you to register a custom HOW\n(Higher Order Workings) class that the compiler will use when it encounters\nyour declarator keyword. Here's a complete example:\n\n=begin code\n# lib/DeclaratorOne.rakumod\n# Custom declarator-one implementation\n# Similar to how Red ORM implements the \"model\" declarator\n\nclass MetamodelX::DeclaratorOne is Metamodel::ClassHOW {}\n\nmy package EXPORTHOW {\n    package DECLARE {\n        constant declarator-one = MetamodelX::DeclaratorOne;\n    }\n}\n=end code\n\nTo use this declarator:\n\n=begin code :skip-test<needs module>\nuse DeclaratorOne;\n\ndeclarator-one Foo {\n    has $.name;\n    method greet { say \"Hello from $.name()!\" }\n}\n\nmy $foo = Foo.new(name => \"World\");\n$foo.greet;  # OUTPUT: «Hello from World!␤»\n=end code\n\nHow it works:\n\n=item1 You create a HOW class that extends an appropriate base HOW (such as\nC<Metamodel::ClassHOW> for class-like declarators, or C<Metamodel::ParametricRoleHOW>\nfor role-like declarators).\n\n=item1 You export it via the C<EXPORTHOW::DECLARE> package, where the constant\nname matches your desired declarator keyword.\n\n=item1 When the compiler encounters your declarator keyword, it uses your HOW\nto construct the type, just as it would use C<Metamodel::ClassHOW> for C<class>\ndeclarations.\n\nThis approach integrates seamlessly with Raku's grammar and type system, making\nyour custom declarator work exactly like built-in declarators.\n\nFor a real-world example, see how Red ORM implements the C<model> declarator\nin L<its source code|https://github.com/FCO/Red/blob/master/lib/Red/Model.rakumod>.\n\n=head4 Custom Attribute Classes\n\nYou can also customize what class is used when attributes are created with C<has>.\nThis is done by exporting a custom attribute class via C<EXPORTHOW::DECLARE>.\nUnlike class declarators which extend a HOW class, custom attribute classes extend\nthe L<C<Attribute>|/type/Attribute> class itself.\n\nThis allows you to change the behavior of C<has> attributes within classes that use\nyour custom class declarator. You still use C<has> to declare attributes, but they\nwill be instantiated as instances of your custom attribute class instead of the\ndefault C<Attribute> class.\n\nHere's an example showing just the custom attribute class part (based on\nL<ValueClass|https://github.com/FCO/ValueClass>):\n\n=begin code :skip-test<needs module>\n# Custom attribute class example\n# Note: This is just the attribute class part. You would also need to define\n# a HOW class for the class declarator (like MetamodelX::ValueClassHOW).\n\nclass ValueClass::Attribute is Attribute {\n    method compose(|) {\n        # Custom behavior during attribute composition\n        # For example, validate that attributes can't be rw\n        die \"Attributes { $.name } can't be rw on a value-class\" if $.rw;\n        nextsame\n    }\n\n    method container_initializer(|c) {\n        # Custom initialization logic\n        # This can change default values or types\n        if $.name.starts-with: '@' {\n            return -> { Tuple.new }\n        } elsif $.name.starts-with: '%' {\n            return -> { ValueMap.new }\n        }\n        nextsame\n    }\n}\n\n# Export the attribute class via EXPORTHOW::DECLARE\n# (The class declarator would also be exported here)\nmy package EXPORTHOW {\n    package DECLARE {\n        # constant value-class = MetamodelX::ValueClassHOW;  # Not shown here\n        constant value-class-attr = ValueClass::Attribute;\n    }\n}\n=end code\n\nTo use this:\n\n=begin code :skip-test<needs module>\nuse ValueClass;\n\nvalue-class MyClass {\n    has $.name;    # Regular scalar attribute (with ValueClass validation)\n    has @.items;   # This becomes a Tuple\n    has %.data;    # This becomes a ValueMap\n}\n\nmy $obj = MyClass.new(name => \"Test\", items => [1,2,3]);\nsay $obj.name;   # OUTPUT: «Test␤»\n=end code\n\nHow it works:\n\n=item1 You create a class that extends L<C<Attribute>|/type/Attribute>, which is the\nbase class for all attributes in Raku.\n\n=item1 You can override methods like C<compose> and C<container_initializer> to\ncustomize the behavior of attributes created with C<has>.\n\n=item1 You export it via the C<EXPORTHOW::DECLARE> package, where the constant\nname (typically ending in C<-attr>) maps to your custom attribute class.\n\n=item1 When you use your custom class declarator (like C<value-class>), any C<has>\nattributes declared within that class will be instantiated as instances of your\ncustom attribute class instead of the default C<Attribute> class.\n\n=item1 You still use C<has> to declare attributes; the custom attribute class\nsimply changes what class those attributes are instantiated as.\n\nFor a real-world example, see how L<ValueClass|https://github.com/FCO/ValueClass>\nimplements custom attributes in L<its source code|https://github.com/FCO/ValueClass/blob/master/lib/ValueClass/Attribute.rakumod>.\n\n=head2 Prerequisites for Understanding Slangs\n\nIf all you wish to do is use existing Slangs, you can stop reading now.\nHowever, if you wish to understand better how to make or modify Slangs, then\nthe recommended reading before continuing is:\n\n=item1 L<Grammar tutorial|/language/grammar_tutorial>\n\n=item1 L<Grammars|/language/grammars>\n\n=item1 Not required, but helpful:\nL<class Grammar|/type/Grammar>\n\n\n=head2 A Slang Example\n\nTo get a good view of a nice, simple Slang, the best candidate would be the\nsource for L<Slang::Lambda|https://raku.land/zef:lizmat/Slang::Lambda>.\n\nSlang::Lambda modifies the Raku grammar to make it possible to use\nthe C<λ> (lambda) symbol as the starter symbol of a pointy block (which is\nusually C«->»).  The source is so short we can include it here:\n\n=begin code :skip-test<needs module>\nmy role RakuLambda {\n    token pointy-block-starter { '->' | '→' | '<->' | '↔' | 'λ' }\n}\n\nmy role LegacyLambda {\n    token lambda { '->' | '<->' | 'λ' }\n}\n\nuse Slangify:ver<0.0.4+>:auth<zef:lizmat> RakuLambda, Mu, LegacyLambda;\n=end code\n\nThen to use it, we do:\n\n=begin code :skip-test<needs module>\nuse Slang::Lambda;\n\nsay (1,2,3).map: λ $x { $x+1 }  # (2 3 4)\n\n=end code\n\nThe code is self-evident to those familiar with Raku's grammars.\nThis is all well and good, but sometimes there's a large gap between\nbeing able to read code, and being able to write it.  How did Elizabeth (the\nauthor of Slang::Lambda) know to use Slangify?  How did she know what token\nnames to declare?  In her case, it was through extensive study of Raku and\nhow it works, but in order to avoid this, we're going to step through some\nof these things now.\n\n=head2 Slangify\n\nTo ease the process of creating Slangs, Elizabeth Mattijsen also created\nthe L<Slangify|https://raku.land/zef:lizmat/Slangify> module (that's how\nshe knew about it!)  The Slangify module is a module intended for slang\ndevelopers.\n\nIt abstracts the internals of slang creation and activation so that module\ndevelopers of slangs have a consistent interface they can work with across\ncurrent and future versions of the Raku Programming Language.\n\nTo use it you do the following:\n\n=begin code :skip-test<needs module>\nuse Slangify Foo::Grammar, Foo::Actions;\n=end code\n\nEither the Grammar or the Actions can be replaced with L<C<Mu>|/type/Mu> to indicate that\nthey should remain unchanged.\n\nTwo additional parameters, for legacy grammars and legacy actions, are also\naccepted.\n\nWhile using Slangify is logically the last step in your code, it's worth\nunderstanding it somewhat before you begin, so that you can align your\ncode with it.  For further details, read the documentation for\nL<Slangify|https://raku.land/zef:lizmat/Slangify>.\n\n=head2 The Raku Grammar\n\nThis is the point where you need to do the most digging.  The Raku grammar\nis not small, and nor is it simple; its extensive error messages, which\nare great when programming, hinder the readability.\n\nThe sources for the Raku grammar are:\n\n=item1 L<The new AST grammar|https://github.com/rakudo/rakudo/blob/main/src/Raku/Grammar.nqp>\n\n=item1 L<The old, pre-AST grammar|https://github.com/rakudo/rakudo/blob/main/src/Perl6/Grammar.nqp>\n\nUnfortunately there's no substitute for digging through the grammar and\nlocating the tokens/rules which you wish to override.\n\n=head2 The Slang Grammar\n\nNow you need to write the slang grammar, much like Slang::Lambda.  The\nlinks above to the grammar documentation should help here.\n\n=head2 The Slang Actions\n\nMany slangs will also need an Actions class backing them.  This is also\ndocumented in the grammar documentation linked above.\n\n=head2 Publishing the module\n\nYou'll want to get your module published too.  To do this, follow the\ninstructions under L<Distributions: An Introduction|/language/distributions/introduction>\nand related pages.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/statement-prefixes.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Statement prefixes\n\n=SUBTITLE Prefixes that alter the behavior of a statement or a set of them\n\nStatement prefixes are written in front of a\nstatement, and change their meaning, their output, or the moment they are going\nto be run. Since they have a specific behavior, they are also sometimes specific\nto some statement or group of statements.\n\n=head2 X<C<lazy>|Syntax,lazy (statement prefix)>\n\nAs a statement prefix, C<lazy> acts in front of any statement, including C<for>\nloops, saving the execution for when the variable they are assigned to is\nactually needed.\n\n=for code\nmy $incremented = 0;\nmy $var = lazy for <1 2 3 4> -> $d {\n    $incremented++\n};\nsay $incremented; # OUTPUT: «0␤»\nsay eager $var;   # OUTPUT: «(0 1 2 3)␤»\nsay $incremented; # OUTPUT: «4␤»\n\nThe C<$incremented> variable is only incremented, that is, the internal part of\nthe loop is only run when we eagerly evaluate the variable C<$var> that\ncontains the lazy loop. Eagerness can be applied on a variable in other ways,\nsuch as calling the C<.eager> method on it.\n\n=for code\nmy @array = lazy { (^3).map( *² )  };\nsay @array;       # OUTPUT: «[...]␤»\nsay @array.eager; # OUTPUT: «[0 1 4]␤»\n\nThis prefix can also be used L<in front of\nC<gather>|/language/control#gather/take> to make the inner statements behave\nlazily; in general, any set of statements that returns a value will be made\nlazy using this.\n\n=head2 X<C<eager>|Syntax,eager (statement prefix)>\n\nThe C<eager> statement prefix will eagerly return the result of the statements\nbehind, throwing away laziness and returning the result.\n\n=for code\nmy $result := eager gather { for 1..3 { say \"Hey\"; take $_² } };\nsay $result[0]; # OUTPUT: «Hey␤Hey␤Hey␤1␤»\n\nC<gather> is L<implicitly lazy when bound to a scalar|/syntax/gather%20take>.\nHowever, with C<eager> as a statement prefix it will run all three iterations in\nthe loop, as shown by the printed \"Hey\", even if we are just requesting the\nfirst one in a row.\n\n=head2 X<C<hyper>|Syntax,hyper (statement prefix)>, X<C<race>|Syntax,race (statement prefix)>\n\nA C<for> loop will automatically serialize any L<C<HyperSeq>|/type/HyperSeq> or\nL<C<RaceSeq>|/type/RaceSeq> used in it; on the other hand C<hyper> and C<race>\nuse (maybe simultaneous) threads to run different iterations in a loop:\n\n=for code\nmy @a = hyper for ^100_000 { .is-prime }\n\nThis code is around 3x faster than the bare C<for>. But there are a couple of\ncaveats here:\n\n=item The operation inside the loop should take enough time for threading\nto make sense.\n\n=item There should be no read or write access to the same data structure inside\nthe loop. Let the loop produce a result, and assign it.\n\n=item If there's an I/O operation inside the loop, there might be some contention\nso please avoid it.\n\nMain difference between C<hyper> and C<race> is the ordering of results. Use\nC<hyper> if you need the loop results to be produced in order, C<race> if you\ndon't care.\n\n=head2 X<C<quietly>|Syntax,quietly (statement prefix)>\n\nAs a prefix, C<quietly> suppresses all runtime warnings produced by the\nblock or statement it precedes.\n\n=for code\nsub marine() {};\nquietly say ~&marine; # OUTPUT: «marine␤»\nsub told-you { warn 'hey...' };\nquietly { told-you; warn 'kaput!' };\nwarn 'Telling you now!';  # OUTPUT: «Telling you now!␤ [...] ␤»\n\nCalling L<C<.Str> on C<code> produces a warning|/type/Code#method_Str>.\nPreceding the code with C<quietly> will just produce the output without warning.\n\n=head2 X<C<try>|Syntax,try (statement prefix)>\n\nIf you use C<try> in front of a statement, it will contain the exception\nproduced in it and store it in the C<$!> variable, just like when L<it's used in\nfront of a block|/language/exceptions#try_blocks>.\n\n=for code\ntry [].pop;\nsay $!; # OUTPUT: «Cannot pop from an empty Array␤..»\n\nNote that if no L<C<Exception>|/type/Exception> had been thrown\nin the C<try> block, then C<$!> will be undefined.\n\n=head2 X<C<do>|Syntax,do (statement prefix)>\n\nC<do> can be used as a statement prefix to disambiguate the statement they\nprecede; this is needed, for instance, if you want to assign the result of a\nC<for> statement. A bare C<for> will fail, but this will work:\n\n=for code\nmy $counter = 0;\nmy $result = do for ^5 { $counter++ };\nsay $counter; # OUTPUT: «5␤»\nsay $result;  # OUTPUT: «(0 1 2 3 4)␤»\n\nC<do> is equivalent, as in other cases, to surrounding a statement with a\nparenthesis. It can be used as an alternative with a (possibly more)\nstraightforward syntax.\n\n=head2 X<C<sink>|Syntax,sink (statement prefix)>\n\nAs in the L<case of the routine|/routine/sink>, C<sink> will run the statement,\nthrowing away the result. Use it in case you want to run some statement for the\nside effects it produces.\n\n=for code\nmy $counter = 0;\nmy $result = sink for ^5 { $counter++ };\nsay $counter; #  OUTPUT: «5␤»\nsay $result;  #  OUTPUT: «(Any)␤»\n\nThe C<sink> statement prefix will also convert L<C<Failure>|/type/Failure>s into exceptions:\n\n=for code\nsub find-the-number ( Int $n where $n < 10 ) {\n    if $n == 7 {\n        return True;\n    } else {\n        fail \"Not that number\" ;\n    }\n}\nfor 1..^10 {\n    try {\n        sink find-the-number($_);\n    };\n    say \"Found $_\" unless $!;\n}\n\nIn this case, we will know that the number has been found only when the\nC<try> block is not catching an exception.\n\n=head2 X<C<react>|Syntax,react (statement prefix)>\n\nC<react> can be used in concurrent programs to create blocks of code that run\nwhenever some event occurs. It L<works with blocks|/syntax/react>, and also as a\nstatement prefix.\n\n=begin code\nmy Channel $KXGA .= new;\nfor ^100 {\n    $KXGA.send( (100000..200000).pick );\n}\n\nmy @sums = ( start react whenever $KXGA -> $number {\n    say \"In thread \", $*THREAD.id;\n    say \"→ \", (^$number).sum;\n} ) for ^10;\n\nstart { sleep 10; $KXGA.close(); }\n\nawait @sums;\n=end code\n\nIn this case C<react> prefixes C<whenever>, which makes a long sum with every\nnumber read from a channel.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/structures.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Data structures\n\n=SUBTITLE How Raku deals with data structures and what we can expect from them\n\n=head1 Scalar structures\n\nSome classes do not have any I<internal> structure and to access parts\nof them, specific methods have to be used. Numbers, strings, and some\nother monolithic classes are included in that class. They use the C<$>\nsigil, although complex data structures can also use it.\n\n    my $just-a-number = 7;\n    my $just-a-string = \"8\";\n\nThere is a L<C<Scalar>|/type/Scalar> class, which is used internally to assign a default\nvalue to variables declared with the C<$> sigil.\n\n    my $just-a-number = 333;\n    say $just-a-number.VAR.^name; # OUTPUT: «Scalar␤»\n\nAny complex data structure can be I<scalarized> by using the L<item\ncontextualizer C<$>|/type/Any#index-entry-%24_(item_contextualizer)>:\n\n    (1, 2, 3, $(4, 5))[3].VAR.^name.say; # OUTPUT: «Scalar␤»\n\nHowever, this means that it will be treated as such in the context they are. You\ncan still access its internal structure.\n\n    (1, 2, 3, $(4, 5))[3][0].say; # OUTPUT: «4␤»\n\nAn interesting side effect, or maybe intended feature, is that scalarization\nconserves identity of complex structures.\n\n    for ^2 {\n         my @list = (1, 1);\n         say @list.WHICH;\n    } # OUTPUT: «Array|93947995146096␤Array|93947995700032␤»\n\nEvery time C<(1, 1)> is assigned, the variable created is going to be different\nin the sense that C<===> will say it is; as it is shown, different values of the\ninternal pointer representation are printed. However\n\n    for ^2 {\n      my $list = (1, 1);\n      say $list.WHICH;\n    } # OUTPUT: «List|94674814008432␤List|94674814008432␤»\n\nIn this case, C<$list> is using the Scalar sigil and thus will be a L<C<Scalar>|/type/Scalar>. Any scalar with the same value will be exactly the same, as shown when printing the pointers.\n\n=head1 Complex data structures\n\nComplex data structures fall in two different broad categories:\nL<C<Positional>|/type/Positional> or list-like on the one hand, and\nL<C<Associative>|/type/Associative> or key-value pair like on the other hand,\naccording to how you access its first-level elements.\nIn general, complex data structures, including\nobjects, will be a combination of both, with object properties assimilated to\nkey-value pairs. While all objects subclass L<C<Mu>|/type/Mu>, in general complex objects\nare instances of subclasses of L<C<Any>|/type/Any>. While it is theoretically possible to mix\nin L<C<Positional>|/type/Positional> or L<C<Associative>|/type/Associative> without doing so, most methods applicable to\ncomplex data structures are implemented in L<C<Any>|/type/Any>.\n\nNavigating these complex data structures is a challenge, but Raku provides a\ncouple of functions that can be used on them: L<C<deepmap>|/routine/deepmap> and\nL<C<duckmap>|/routine/duckmap>. While the former will go to every single\nelement, in order, and do whatever the block passed requires,\n\n    say [[1, 2, [3, 4]],[[5, 6, [7, 8]]]].deepmap( *.elems );\n    # OUTPUT: «[[1 1 [1 1]] [1 1 [1 1]]]␤»\n\nwhich returns C<1> because it goes to the deeper level and applies C<elems> to\nthem, C<duckmap> can perform more complicated operations:\n\n    say [[1, 2, [3, 4]], [[5, 6, [7, 8]]]].duckmap:\n       -> $array where .elems == 2 { $array.elems };\n    # OUTPUT: «[[1 2 2] [5 6 2]]␤»\n\nIn this case, it dives into the structure, but returns the element itself if it\ndoes not meet the condition in the block (C<1, 2>), returning the number of\nelements of the array if it does (the two C<2>s at the end of each subarray).\n\nSince C<deepmap> and C<duckmap> are L<C<Any>|/type/Any> methods, they also apply to Associative\narrays:\n\n    say %( first => [1, 2], second => [3,4] ).deepmap( *.elems );\n    # OUTPUT: «{first => [1 1], second => [1 1]}␤»\n\nOnly in this case, they will be applied to every list or array that is a value,\nleaving the keys alone.\n\nL<C<Positional>|/type/Positional> and L<C<Associative>|/type/Associative> can be turned into each other.\n\n    say %( first => [1, 2], second => [3,4] ).list[0];\n    # OUTPUT: «second => [3 4]␤»\n\nHowever, in this case, and for Rakudo >= 2018.05, it will return a different\nvalue every time it runs. A hash will be turned into a list of the key-value\npairs, but it is guaranteed to be disordered. You can also do the operation in\nthe opposite direction, as long as the list has an even number of elements (odd\nnumber will result in an error):\n\n    say <a b c d>.Hash # OUTPUT: «{a => b, c => d}␤»\n\nBut\n\n    say <a b c d>.Hash.kv # OUTPUT: «(c d a b)␤»\n\nwill obtain a different value every time you run it;\nL<C<kv>|/type/Pair#method_kv> turns every L<C<Pair>|/type/Pair> into a list.\n\nComplex data structures are also generally L<C<Iterable>|/type/Iterable>. Generating an\nL<iterator|/routine/iterator> out of them will allow the program to visit the first level of the\nstructure, one by one:\n\n    .say for 'א'..'ס'; # OUTPUT: «א␤ב␤ג␤ד␤ה␤ו␤ז␤ח␤ט␤י␤ך␤כ␤ל␤ם␤מ␤ן␤נ␤ס␤»\n\nC<'א'..'ס'> is a L<C<Range>|/type/Range>, a complex data structure, and with C<for> in front it\nwill iterate until the list is exhausted. You can use C<for> on your complex\ndata structures by overriding the L<iterator|/routine/iterator> method (from role L<C<Iterable>|/type/Iterable>):\n\n    class SortedArray is Array {\n      method iterator() {\n        self.sort.iterator\n      }\n    };\n    my @thing := SortedArray.new([3,2,1,4]);\n    .say for @thing; # OUTPUT: «1␤2␤3␤4␤»\n\nC<for> calls directly the C<iterator> method on C<@thing> making it return the\nelements of the array in order. Much more on L<iterating on the page devoted to it|/language/iterating>.\n\n=head1 Functional structures\n\nRaku is a functional language and, as such, functions are first-class I<data>\nstructures. Functions follow the L<C<Callable>|/type/Callable> role, which is the 4th element in\nthe quartet of fundamental roles. L<C<Callable>|/type/Callable> goes with the C<&> sigil, although\nin most cases it is elided for the sake of simplicity; this sigil elimination is\nalways allowed in the case of L<C<Callable>|/type/Callable>s.\n\n    my &a-func= { (^($^þ)).Seq };\n    say a-func(3), a-func(7); # OUTPUT: «(0 1 2)(0 1 2 3 4 5 6)␤»\n\nL<C<Block>|/type/Block>s are the simplest callable structures, since L<C<Callable>|/type/Callable>s cannot be\ninstantiated. In this case we implement a block that logs events and can\nretrieve them:\n\n    my $logger = -> $event, $key = Nil  {\n      state %store;\n      if ( $event ) {\n        %store{ DateTime.new( now ) } = $event;\n      } else {\n        %store.keys.grep( /$key/ )\n      }\n    }\n    $logger( \"Stuff\" );\n    $logger( \"More stuff\" );\n    say $logger( Nil, \"2018-05-28\" ); # OUTPUT: «(Stuff More stuff)␤»\n\n\nA L<C<Block>|/type/Block> has a L<C<Signature>|/type/Signature>, in this case two arguments, the first of\nwhich is the event that is going to be logged, and the second is the key\nto retrieve the events. They will be used in an independent way, but its\nintention is to showcase the use of a L<state variable|/syntax/state>\nthat is kept from every invocation to the next. This state variable is\nencapsulated within the block, and cannot be accessed from outside\nexcept by using the simple API the block provides: calling the block\nwith a second argument. The two first invocations log two events, the\nthird invocation at the bottom of the example use this second type of\ncall to retrieve the stored values. L<C<Block>|/type/Block>s can be cloned:\n\n=begin code :preamble<my $logger = sub ( $a, $b ){ return $a, $b }>\nmy $clogger = $logger.clone;\n$clogger( \"Clone stuff\" );\n$clogger( \"More clone stuff\" );\nsay $clogger( Nil, \"2018-05-28\" );\n# OUTPUT: «(Clone stuff More clone stuff)␤»\n=end code\n\nAnd cloning will reset the state variable; instead of cloning, we can create\nI<façades> that change the API. For instance, eliminate the need to use L<C<Nil>|/type/Nil>\nas first argument to retrieve the log for a certain date:\n\n=begin code :preamble<my $logger = sub ( $a, $b ){ return $a, $b }>\nmy $gets-logs = $logger.assuming( Nil, * );\n$logger( %(changing => \"Logs\") );\nsay $gets-logs( \"2018-05-28\" );\n# OUTPUT: «({changing => Logs} Stuff More stuff)␤»\n=end code\n\nL<C<assuming>|/type/Code#method_assuming> wraps around a block\ncall, giving a value (in this case, L<C<Nil>|/type/Nil>) to the arguments we need,\nand passing on the arguments to the other arguments we represent using\nC<*>. In fact, this corresponds to the natural language statement \"We\nare calling C<$logger> I<assuming> the first argument is L<C<Nil>|/type/Nil>\". We can\nslightly change the appearance of these two Blocks to clarify they are\nactually acting on the same block:\n\n=begin code :preamble<my $logger = sub ( $a, $b ){ return $a, $b }>\nmy $Logger = $logger.clone;\nmy $Logger::logs = $Logger.assuming( *, Nil );\nmy $Logger::get = $Logger.assuming( Nil, * );\n$Logger::logs( <an array> );\n$Logger::logs( %(key => 42) );\nsay $Logger::get( \"2018-05-28\" );\n=end code\n\nAlthough C<::> is generally used for invocation of class methods, it is\nactually a valid part of the name of a variable. In this case we use\nthem conventionally to simply indicate C<$Logger::logs> and\nC<$Logger::get> are actually calling C<$Logger>, which we have\ncapitalized to use a class-like appearance. The point of this tutorial\nis that using functions as first-class citizens, together with the use\nof state variables, allows the use of certain interesting design\npatterns such as this one.\n\nAs such first class data structures, callables can be used anywhere another type of data can.\n\n    my @regex-check = ( /<alnum>/, /<alpha>/, /<punct>/ );\n    say @regex-check.map: \"33af\" ~~ *;\n    # OUTPUT: «(｢3｣␤ alnum => ｢3｣ ｢a｣␤ alpha => ｢a｣ Nil)␤»\n\nRegexes are actually a type of callable:\n\n    say /regex/.does( Callable ); # OUTPUT: «True␤»\n\nAnd in the example above we are calling regexes stored in an array, and\napplying them to a string literal.\n\nCallables are composed by using the L<function composition operator ∘|/language/operators#infix_o,_infix_%E2%88%98>:\n\n=begin code :preamble<my $Logger::logs = sub ( $a ) { $a }>\nmy $typer = -> $thing { $thing.^name ~ ' → ' ~ $thing };\nmy $Logger::withtype = $Logger::logs ∘ $typer;\n$Logger::withtype( Pair.new( 'left', 'right' ) );\n$Logger::withtype( ¾ );\nsay $Logger::get( \"2018-05-28\" );\n# OUTPUT: «(Pair → left right Rat → 0.75)␤»\n=end code\n\nWe are composing C<$typer> with the C<$Logger::logs> function defined\nabove, obtaining a function that logs an object preceded by its type,\nwhich can be useful for filtering, for instance. C<$Logger::withtype>\nis, in fact, a complex data structure composed of two functions which\nare applied in a serial way, but every one of the callables composed can\nkeep state, thus creating complex transformative callables, in a design\npattern that is similar to object composition in the object oriented\nrealm. You will have to choose, in every particular case, what is the programming style which is most suitable for your problem.\n\n=head1 Defining and constraining data structures\n\nRaku has different ways of defining data structures, but also many\nways to constrain them so that you can create the most adequate data\nstructure for every problem domain. L<C<but>|/routine/but>, for example,\nmixes roles or values into a value or a variable:\n\n=begin code\nmy %not-scalar := %(2 => 3) but Associative[Int, Int];\nsay %not-scalar.^name; # OUTPUT: «Hash+{Associative[Int, Int]}␤»\nsay %not-scalar.of;    # OUTPUT: «Associative[Int, Int]␤»\n%not-scalar{3} = 4;\n%not-scalar<thing> = 3;\nsay %not-scalar;       # OUTPUT: «{2 => 3, 3 => 4, thing => 3}␤»\n=end code\n\nIn this case, C<but> is mixing in the C<Associative[Int, Int]> role;\nplease note that we are using binding so that the type of the variable\nis the one defined, and not the one imposed by the C<%> sigil; this\nmixed-in role shows in the C<name> surrounded by curly braces. What does\nthat really mean? That role includes two methods, C<of> and C<keyof>; by\nmixing the role in, the new C<of> will be called (the old C<of> would\nreturn L<C<Mu>|/type/Mu>, which is the default value type for Hashes). However, that\nis all it does. It is not really changing the type of the variable, as\nyou can see since we are using any kind of key and values in the next\nfew statements.\n\nHowever, we can provide new functionality to a variable using this type\nof mixin:\n\n=begin code\nrole Lastable {\n  method last() {\n    self.sort.reverse[0]\n  }\n}\nmy %hash-plus := %( 3 => 33, 4 => 44) but Lastable;\nsay %hash-plus.sort[0]; # OUTPUT: «3 => 33␤»\nsay %hash-plus.last;    # OUTPUT: «4 => 44␤»\n=end code\n\nIn C<Lastable> we use the universal C<self> variable to refer to whatever object\nthis particular role is mixed in; in this case it will contain the hash it is\nmixed in with; it will contain something else (and possibly work some other way)\nin another case. This role will provide the C<last> method to any variable it's\nmixed with, providing new, attachable, functionalities to I<regular> variables.\nRoles can even be L<added to existing variables using the C<does> keyword|/language/objects#Mixins_of_roles>.\n\nL<Subsets|/language/typesystem#subset> can also be used to constrain the\npossible values a variable might hold; they are Raku attempt at\nL<gradual typing|https://en.wikipedia.org/wiki/Gradual_typing>; it is\nnot a full attempt, because subsets are not really types in a strict\nsense, but they allow runtime type checking. It adds type-checking\nfunctionality to regular types, so it helps create a richer type system,\nallowing things like the one shown in this code:\n\n=begin code\nsubset OneOver where (1/$_).Int == 1/$_;\nmy OneOver $one-fraction = ⅓;\nsay $one-fraction; # OUTPUT: «0.333333␤»\n=end code\n\nOn the other hand, C<my OneOver $ = ⅔;> will cause a type-check error.\nSubsets can use L<C<Whatever>|/type/Whatever>, that is, C<*>, to refer to the argument;\nbut this will be instantiated every time you use it to a different\nargument, so if we use it twice in the definition we would get an\nerror. In this case we are using the topic single variable, C<$_>, to\ncheck the instantiation. Subsetting can be done directly, without the\nneed of declaring it, in L<signatures|/language/typesystem#subset>.\n\n\n=head1 Infinite structures and laziness\n\nIt might be assumed that all the data contained in a data structure is actually\nI<there>. That is not necessarily the case: in many cases, for efficiency\nreasons or simply because it is not possible, the elements contained in a data\nstructure only jump into existence when they are actually needed. This\ncomputation of items as they are needed is called\nL<reification|/language/glossary#Reify> or vivification.\n\n=begin code\n# A list containing infinite number of un-reified Fibonacci numbers:\nmy @fibonacci = 1, 1, * + * … ∞;\n\n# We reify 10 of them, looking up the first 10 of them with array index:\nsay @fibonacci[^10]; # OUTPUT: «(1 1 2 3 5 8 13 21 34 55)␤»\n\n# We reify 5 more: 10 we already reified on previous line, and we need to\n# reify 5 more to get the 15th element at index 14. Even though we need only\n# the 15th element, the original Seq still has to reify all previous elements:\nsay @fibonacci[14]; # OUTPUT: «987␤»\n=end code\n\nAbove we were reifying a L<C<Seq>|/type/Seq> we created with the L<sequence\noperator|/language/operators#infix_...>, but other data\nstructures use the concept as well. For example, an un-reified\nL<C<Range>|/type/Range> is just the two end points. In some languages, calculating\nthe sum of a huge range is a lengthy and memory-consuming process, but Raku\ncalculates it instantly:\n\n    say sum 1 .. 9_999_999_999_999; # OUTPUT: «49999999999995000000000000␤»\n\nWhy? Because the sum can be calculated I<without> vivifying the Range; that is,\nwithout figuring out all the elements it contains. This is why this feature\nexists. You can even make your own things reify-on-demand, using\nL«C<gather> and C<take>|/syntax/gather%20take»:\n\n    my $seq = gather {\n        say \"About to make 1st element\"; take 1;\n        say \"About to make 2nd element\"; take 2;\n    }\n    say \"Let's reify an element!\";\n    say $seq[0];\n    say \"Let's reify more!\";\n    say $seq[1];\n    say \"Both are reified now!\";\n    say $seq[^2];\n\n    # OUTPUT:\n    # Let's reify an element!\n    # About to make 1st element\n    # 1\n    # Let's reify more!\n    # About to make 2nd element\n    # 2\n    # Both are reified now!\n    # (1 2)\n\nFollowing the output above, you can see the print statements I<inside> the\nC<gather> got executed only when we reified the individual elements while\nlooking up an element. Also note that the elements got reified just once. When\nwe printed the same elements again on the last line of the example, the messages\ninside C<gather> was no longer printed. This is because the construct used\nalready-reified elements from the L<C<Seq>|/type/Seq>'s cache.\n\nNote that above we assigned the C<gather> to a L<C<Scalar>|/type/Scalar> container\n(the C<$> sigil), not the L<C<Positional>|/type/Positional> one (the C<@> sigil).\nThe reason is that the C<@>-sigiled variables are I<mostly eager>. What this\nmeans is they I<reify the stuff assigned to them> right away I<most of the\ntime>. The only time they don't do it is when the items are known to be\nL«C<is-lazy>|/routine/is-lazy», like our sequence generated with infinity as the\nend point. Were we to assign the C<gather> to an C<@>-variable, the C<say>\nstatements inside of it would've been printed right away.\n\nAnother way to vivify the list fully is by calling L«C<.elems>|/routine/elems»\non it. This is the reason why checking whether a list contains any items is best\ndone by using C<.Bool> method (or just using C<if @array { … }>), since you\ndon't need to reify I<all> the elements to find out if there are C<any> of them.\n\nThere are times where you I<do> want to fully-reify a list before doing\nsomething. For example, the L«C<IO::Handle.lines>|/type/IO::Handle#routine_lines»\nreturns a L<C<Seq>|/type/Seq>. The following code contains a bug; keeping\nreification in mind, try to spot it:\n\n=for code\nmy $fh = \"/tmp/bar\".IO.open;\nmy $lines = $fh.lines;\nclose $fh;\nsay $lines[0];\n\nWe open a L<filehandle|/type/IO::Handle>, then assign return of\nL«C<.lines>|/type/IO::Handle#routine_lines» to a L<C<Scalar>|/type/Scalar> variable,\nso the returned L<C<Seq>|/type/Seq> does not get reified right away. We then\nL«C<close>|/routine/close» the filehandle, and try to print an element from\nC<$lines>.\n\nThe bug in the code is by the time we reify the C<$lines> L<C<Seq>|/type/Seq> on\nthe last line, we've I<already closed> the filehandle. When the L<C<Seq>|/type/Seq>'s\niterator tries to generate the item we've requested, it results in the error\nabout attempting to read from a closed handle. So, to fix the bug we can either\nassign to an C<@>-sigiled variable or call L«C<.elems>|/routine/elems» on\nC<$lines> before closing the handle:\n\n=for code\nmy $fh = \"/tmp/bar\".IO.open;\nmy @lines = $fh.lines;\nclose $fh;\nsay @lines[0]; # no problem!\n\nWe can also use any function whose side effect is reification, like C<.elems>\nmentioned above:\n\n=for code\nmy $fh = \"/tmp/bar\".IO.open;\nmy $lines = $fh.lines;\nsay \"Read $lines.elems() lines\"; # reifying before closing handle\nclose $fh;\nsay $lines[0]; # no problem!\n\nUsing L<eager|/routine/eager> will also reify the whole sequence:\n\n=for code\nmy $fh = \"/tmp/bar\".IO.open;\nmy $lines = eager $fh.lines; # Uses eager for reification.\nclose $fh;\nsay $lines[0];\n\n=head1 Introspection\n\nLanguages that allow\nL<introspection|https://en.wikipedia.org/wiki/Type_introspection> like Raku\nhave functionalities attached to the type system that let the developer\naccess container and value metadata. This metadata can be used in a\nprogram to carry out different actions depending on their value. As it is\nobvious from the name, metadata are extracted from a value or container\nvia the metaclass.\n\n    my $any-object = \"random object\";\n    my $metadata = $any-object.HOW;\n    say $metadata.^mro;                   # OUTPUT: «((ClassHOW) (Any) (Mu))␤»\n    say $metadata.can( $metadata, \"uc\" ); # OUTPUT: «(uc uc)␤»\n\nWith the first C<say> we show the class hierarchy of the metamodel class, which\nin this case is L<C<Metamodel::ClassHOW>|/type/Metamodel::ClassHOW>. It inherits directly from L<C<Any>|/type/Any>,\nmeaning any method there can be used; it also mixes in several roles which can\ngive you information about the class structure and functions. But one of the\nmethods of that particular class is L<C<can>|/type/Metamodel::ClassHOW#method_can>,\nwhich we can use to look up whether the object can use the C<uc> (uppercase)\nmethod, which it obviously can. However, it might not be so obvious in some\nother cases, when roles are mixed in directly into a variable. For instance, in\nthe L<case of C<%hash-plus> defined above|#Defining_and_constraining_data_structures>:\n\n=for code :preamble<my %hash-plus>\nsay %hash-plus.^can(\"last\"); # OUTPUT: «(last)␤»\n\nIn this case we are using the I<syntactic sugar> for C<HOW.method>, C<^method>,\nto check if your data structure responds to that method; the output, which shows\nthe name of the methods that match, certifies that we can use it.\n\nSee also L<this article on class introspection|https://perl6advent.wordpress.com/2015/12/19/day-19-introspection/>\non how to access class properties and methods, and use it to generate test data\nfor a class; this L<Advent Calendar article describes the metaobject protocol|https://perl6advent.wordpress.com/2010/12/22/day-22-the-meta-object-protocol/>\nextensively.\n\n\n=end pod\n"
  },
  {
    "path": "doc/Language/subscripts.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Subscripts\n\n=SUBTITLE Accessing data structure elements by index or key\n\nOne often needs to refer to a specific element (or slice of elements) from a\ncollection or data structure. Borrowing from mathematical notation where the\ncomponents of a vector I<v> would be referred to as I<v₁, v₂, v₃>, this concept\nis called \"subscripting\" (or \"indexing\") in Raku.\n\n=head1 Basics\n\nRaku provides two universal subscripting interfaces:\n\n=begin table\n         elements are           interface      supported by\n         identified by          name\n    ===  ==================     =============  ============================\n    [ ]  zero-based indices     Positional     Array, List, Buf, Match, ...\n    { }  string or object keys  Associative    Hash, Bag, Mix, Match, ...\n=end table\n\n=head2 L<C<Positional>|/type/Positional> subscripting\n\nL<C<Positional>|/type/Positional> subscripting (via L<C<postcircumfix [\n]>|/language/operators#postcircumfix_[_]>) addresses elements of an ordered\ncollection by their position. Index 0 refers to the first element, index 1 to\nthe second, and so on:\n\n    my @chores = \"buy groceries\", \"feed dog\", \"wash car\";\n    say @chores[0];  # OUTPUT: «buy groceries␤»\n    say @chores[1];  # OUTPUT: «feed dog␤»\n    say @chores[2];  # OUTPUT: «wash car␤»\n\nNote that Rakudo's implementation of subscripting allows only 63 bits on\n64 bit builds. See\nL<Stack Overflow|https://stackoverflow.com/questions/61031107/do-array-indices-need-to-be-native-ints/61031617#61031617>.\nIf larger subscripts are required, one may use L<Array::Sparse|https://raku.land/zef:lizmat/Array::Sparse>\nor alternatively, use a L<C<Hash>|/type/Hash> with L<C<Associative>|/type/Associative> subscripting (see below).\n\n=head2 L<C<Associative>|/type/Associative> subscripting\n\nL<C<Associative>|/type/Associative> subscripting (via L<C<postcircumfix { }>|\n/language/operators#postcircumfix_{_}>), does not require the collection to\nkeep its elements in any particular order - instead, it uses a unique key to\naddress each value. The nature of the keys depends on the collection in\nquestion: For example a standard L<C<Hash>|/type/Hash> uses string keys, whereas\na L<C<Mix>|/type/Mix> allows arbitrary objects as keys, etc.:\n\n    my %grade = Zoe => \"C\", Ben => \"B+\";\n    say %grade{\"Zoe\"};  # OUTPUT: «C␤»\n    say %grade{\"Ben\"};  # OUTPUT: «B+␤»\n\n    my $stats = ( Date.today => 4.18, Date.new(2015,  4,  5) => 17.253 ).Mix;\n    say $stats{ Date.new(2015, 4, 4) + 1 };  # OUTPUT: «17.253␤»\n\nFor passing single-word string keys to C<{ }>, you can also use the\nL<angle bracketed word quoting constructs|/language/quoting#Word_quoting:_qw>\nas if they were postcircumfix operators:\n\n    my %grade = Zoe => \"C\", Ben => \"B+\";\n    say %grade<Zoe>;    # OUTPUT: «C␤»\n    say %grade<Ben>;    # OUTPUT: «B+␤»\n\nThis is really just syntactic sugar that gets turned into the corresponding\nC<{ }> form at compile-time:\n\n    =begin code :preamble<my %hash;my $var>\n    %hash<foo bar>;       # same as %hash{ <foo bar> }\n    %hash«foo \"$var\"»;    # same as %hash{ «foo \"$var\"» }\n    %hash<<foo \"$var\">>;  # same as %hash{ <<foo \"$var\">> }\n    =end code\n\nYou may have noted above that we avoided having to quote C<Zoe> by using\nthe C«=>» operator, but that same operator did not just put invisible\nquotes around C<Date.new(2015, 4, 5)>, and we were able to find the\nsame element using C<$stats{ Date.new(2015, 4, 4) + 1 }>.  This is because\nC«=>» only puts invisible quotes around single words, and by \"word\" we\nmean an identifier/name.  The C«=>» operator is there to prevent us from\naccidentally calling functions or using constants with that name.\n\nHash subscripts do not do the same thing as C«=>».  The default L<C<Hash>|/type/Hash>\nhas been made to behave the way new users have come to expect\nfrom using other languages, and for general ease of use.  On a\ndefault L<C<Hash>|/type/Hash>, subscripts coerce keys into strings, as long as\nthose keys produce something L<C<Cool>|/type/Cool>.  You can use C<.raku> on a\ncollection to be sure whether the keys are strings or objects:\n\n    ( 1  => 1 ).raku.say;            # OUTPUT: «1 => 1␤»\n    my %h; %h{1}   = 1; say %h.raku; # OUTPUT: «{ \"1\" => 1 }␤»\n    ( 1/2 => 1 ).raku.say;           # OUTPUT: «0.5 => 1␤»\n    my %h; %h{1/2} = 1; say %h.raku; # OUTPUT: «{ \"0.5\" => 1 }␤»\n    ( pi => 1 ).raku.say;            # OUTPUT: «:pi(1)␤»\n    my %h; %h{pi}  = 1; say %h.raku; # OUTPUT: «{ \"3.14159265358979\" => 1 }␤»\n\nWhile the invisible quotes around single names is built into C«=>»,\nstring conversion is not built into the curly braces: it is a behavior\nof the default L<C<Hash>|/type/Hash>.  Not all types of hashes or collections\ndo so:\n\n=for code\nmy %h := MixHash.new;\n%h{pi} = 1; %h.raku.say;         # OUTPUT: «(3.14159265358979e0=>1).MixHash␤»\n\n(Any name that C«=>» would convert to a string can also be used to build\na pair using \"adverbial notation\" and will appear that way when viewed\nthrough C<.raku>, which is why we see C<:pi(1)> above.)\n\n\n=head2 Applying subscripts\n\nSubscripts can be applied to any expression that returns a subscriptable\nobject, not just to variables:\n\n    say \"__Hello__\".match(/__(.*)__/)[0];   # OUTPUT: «｢Hello｣␤»\n    say \"__Hello__\".match(/__(.*)__/).[0];  # same, in method notation\n\nPositional and associative subscripting are not mutually exclusive - for\nexample, L<C<Match>|/type/Match> objects support both (each accessing a different\nset of data). Also, to make list processing more convenient, class\nL<C<Any>|/type/Any> provides a fallback implementation for positional subscripts\nwhich simply treats the invocant as a list of one element. (But there's no such\nfallback for associative subscripts, so they throw a runtime error when applied\nto an object that does not implement support for them.)\n\n    =begin code\n    say 42[0];    # OUTPUT: «42␤»\n    say 42<foo>;  # ERROR: Type Int does not support associative indexing.\n    =end code\n\n=head1 Nonexistent elements\n\nWhat happens when a I<nonexistent> element is addressed by a subscript is up to\nthe collection type in question. Standard L<C<Array>|/type/Array> and\nL<C<Hash>|/type/Hash> collections return the type object of their L<value type\nconstraint|/routine/of> (which, by default, is L<C<Any>|/type/Any>) unless the collection\nhas been declared with the L<C<is default>|/type/Variable#trait_is_default>\ntrait in which case the returned value will be whatever the programmer declared\nit to be:\n\n    # no default values specified\n    my @array1;     say @array1[10];                   # OUTPUT: «(Any)␤»\n    my Int @array2; say @array2[10];                   # OUTPUT: «(Int)␤»\n\n    my %hash1;      say %hash1<foo>;                   # OUTPUT: «(Any)␤»\n    my Int %hash2;  say %hash2<foo>;                   # OUTPUT: «(Int)␤»\n\n    # default values specified\n    my @array3 is default('--');     say @array3[10];  # OUTPUT: «--␤»\n    my Int @array4 is default(17);   say @array4[10];  # OUTPUT: «17␤»\n\n    my %hash3 is default('Empty');   say %hash3<foo>;  # OUTPUT: «Empty␤»\n    my Int %hash4 is default(4711);  say %hash4<foo>;  # OUTPUT: «4711␤»\n\nHowever, other types of collections may react differently to subscripts that\naddress nonexistent elements:\n\n    say (0, 10, 20)[3];           # OUTPUT: «Nil␤»\n    say bag(<a a b b b>)<c>;      # OUTPUT: «0␤»\n    say array[uint8].new(1, 2)[2] # OUTPUT: «0␤»\n\nTo silently skip nonexistent elements in a subscripting operation, see\nL<Truncating slices|#Truncating slices> and the L<C<:v>|#:v> adverb.\n\n=head1 From the end\n\nPositional indices are counted from the start of the collection, but there's\nalso a notation for addressing elements by their position relative to the end:\nC<*-1> refers to the last element, C<*-2> to the second-to-last element, and so\non. From version 6.d, C<*-0> refers to the element just beyond the last one\n\n    my @alphabet = 'A' .. 'Z';\n    say @alphabet[*-1];  # OUTPUT: «Z␤»\n    say @alphabet[*-2];  # OUTPUT: «Y␤»\n    say @alphabet[*-3];  # OUTPUT: «X␤»\n    @alphabet[*-0] = 'þ';\n    say @alphabet;\n    #  OUTPUT: «[A B C D E F G H I J K L M N O P Q R S T U V W X Y Z þ]␤»\n\nB<Note>: The asterisk, which is actually a L<C<Whatever>|/type/Whatever>, is\nimportant. Passing a bare negative integer (e.g. C<@alphabet[-1]>) like you\nwould do in many other programming languages, throws an error in Raku.\n\nWhat actually happens here, is that an expression like C<*-1> declares a code\nobject via L<C<Whatever>|/type/Whatever>-priming - and the C<[ ]> subscript reacts\nto being given a code object as an index, by calling it with the length of the\ncollection as argument and using the result value as the actual index. In other\nwords, C<@alphabet[*-1]> becomes C<@alphabet[@alphabet.elems - 1]>.\n\nThis means that you can use arbitrary expressions which depend on the size of\nthe collection:\n\n=begin code :preamble<my @array; my $size;my $i;>\nsay @array[* div 2];  # select the middlemost element\nsay @array[$i % *];   # wrap around a given index (\"modular arithmetic\")\nsay @array[ -> $size { $i % $size } ];  # same as previous\n=end code\n\n=head1 Slices\n\nWhen multiple elements of a collection need to be accessed, there's a shortcut\nto doing multiple separate subscripting operations: Simply specify a I<list> of\nindices/keys in the subscript, to get back a I<list> of elements - also called\na \"slice\" - in the same order.\n\nFor positional slices, you can mix normal indices with\nL<from-the-end|#From the end> ones:\n\n    my @alphabet = 'a' .. 'z';\n    say @alphabet[15, 4, *-9, 11].raku;  # OUTPUT: «(\"p\", \"e\", \"r\", \"l\")␤»\n\nIn the C<*-number> construct above, C<*> indicates the end of the\narray as explained above in the L<From the end|#From the end>\nsection. So if you want to take the last N elements of the array, you\nwill have to create a L<C<Range>|/type/Range> that includes it.\n\n     (5802..5830).map( {.chr} )[*-10..*-5] # OUTPUT:  «(ᚽ ᚾ ᚿ ᛀ ᛁ ᛂ)␤»\n\nUsing C<*> as the last element of the range will, effectively, return\nthe last elements of the collection.\n\nFor associative slices, the angle brackets form often comes in handy:\n\n    my %color = kiwi => \"green\", banana => \"yellow\", cherry => \"red\";\n    say %color{\"cherry\", \"kiwi\"};  # OUTPUT: «(red green)␤»\n    say %color<cherry kiwi>;       # OUTPUT: «(red green)␤»\n    say %color{*};                 # OUTPUT: «(red yellow green)␤»\n\nBe aware that slices are controlled by the I<type> of what is passed to\n(L<one dimension of|#Multiple dimensions>) the subscript, not its length.\nIn particular the I<type> can be any of the following:\n\n=item a lazy Iterable, that L<truncates|#Truncating slices> in [ ]\n\n=item accordingly, an infinite Range will truncate, but a finite one produces a normal slice\n\n=item '*' (whatever-star), that returns the full slice (as if all keys/indices were specified)\n\n=item '**' (hyperwhatever-star), that returns the full slice (as if all keys/indices were specified), with any lists flattened recursively (since Rakudo Release 2024.08)\n\n=item any other object, that provides a single-element access rather than a slice\n\n=item Callable,  whatever is returned by the callable (this can lead to recursion)\n\n=item empty, the full slice known as L<Zen slice|#Zen slices>\n\n=item any iterable different from the above ones, normal slice\n\nThe notable difference between C<*> and Zen slice (empty) is that the\nL<C<Whatever>|/type/Whatever> star will cause full\nL<reification|/language/glossary#Reify> or itemization, while Zen\nslice won't. Both versions also\nL<de-cont|https://perl6advent.wordpress.com/2017/12/02/perl-6-sigils-variables-and-containers/#decont>.\n\nSo even a one-element list returns a slice, whereas a bare scalar value doesn't:\n\n    =begin code :preamble<my @alphabet = 'a' .. 'z'>\n    say @alphabet[2,];        # OUTPUT: «(c)␤»\n    say @alphabet[2,].^name;  # OUTPUT: «List␤»\n\n    say @alphabet[2];         # OUTPUT: «c␤»\n    say @alphabet[2].^name;   # OUTPUT: «Str␤»\n    =end code\n\n(The angle bracket form for associative subscripts works out because\nL<word quoting|/language/quoting#Word_quoting:_qw> conveniently returns a\nL<C<Str>|/type/Str> in case of a single word, but a L<C<List>|/type/List> in case\nof multiple words.)\n\nIn fact, the list structure of (L<the current dimension of|#Multiple\ndimensions>) the subscript is preserved across the slice operation\n(but the kind of Iterable is not – the result is always just lists.)\n\n    =begin code :preamble<my @alphabet = 'a' .. 'z'>\n    say @alphabet[0, (1..2, (3,))];       # OUTPUT: «(a ((b c) (d)))␤»\n    say @alphabet[0, (1..2, [3,])];       # OUTPUT: «(a ((b c) (d)))␤»\n    say @alphabet[flat 0, (1..2, (3,))];  # OUTPUT: «(a b c d)␤»\n    say flat @alphabet[0, (1..2, (3,))];  # OUTPUT: «(a b c d)␤»\n    =end code\n\n=head2 Truncating slices\n\nReferring to nonexistent elements in a slice subscript causes the output L<C<List>|/type/List>\nto contain undefined values (or L<whatever else|#Nonexistent elements> the\ncollection in question chooses to return for nonexistent elements):\n\n    =begin code\n    my  @letters = <a b c d e f>;\n    say @letters[3..7];  # OUTPUT: «(d e f (Any) (Any))␤»\n    =end code\n\nThis behavior, while at first glance may seem unintuitive, is desirable in\ninstances when you want to assign a value at an index in which a value does\nnot currently exist.\n\n    =begin code\n    my  @letters;\n    say @letters; # OUTPUT: «[]␤»\n\n    @letters[^10] = 'a'..'z';\n    say @letters; # OUTPUT: «[a b c d e f g h i j]␤»\n    =end code\n\nIf you want the resulting slice to only include existing elements, you can\nsilently skip the non-existent elements using the L<C<:v>|#:v> adverb.\n\n    =begin code\n    my  @letters = <a b c d e f>;\n    say @letters[3..7]:v;  # OUTPUT: «(d e f)␤»\n    =end code\n\nThe behavior when indexing a collection via L<lazy|/language/list#Lazy_lists>\nsubscripts is different than when indexing with their eager counterparts.\nWhen accessing via a lazy subscript, the resulting slice will be truncated.\n\n    =begin code :preamble<my @letters>\n    say @letters[lazy 3..7]; # OUTPUT: «(d e f)␤»\n    say @letters[     3..*]; # OUTPUT: «(d e f)␤»\n    =end code\n\nThis behavior exists as a precaution to prevent runaway generation of massive,\npotentially infinite L<C<List>|/type/List>s and the out-of-memory issues that occur as a\nresult.\n\n=head2 X<Zen slices|Language,Zen slices>\n\nIf you put the subscript operator behind an object without specifying any\nindices/keys at all, it simply returns the subscripted object itself. Since it\nis empty but returns everything, it is known as a I<Zen slice>.\n\nZen slicing is different from passing a L<C<Whatever>|/type/Whatever>-star (which, like a normal\nslice, always returns a List of elements no matter the type of the original\nobject) or an empty list (which returns an empty slice):\n\n    my %bag := (orange => 1, apple => 3).Bag;\n    say %bag<>;    # OUTPUT: «Bag(apple(3) orange)␤»\n    say %bag{};    # OUTPUT: «Bag(apple(3) orange)␤»\n    say %bag{*};   # OUTPUT: «(1 3)␤»\n    say %bag{()};  # OUTPUT: «()␤»\n\nZen slicing does not L<reify|/language/glossary#Reify> or\nL<cache|/routine/cache> (not even L<C<Seq>|/type/Seq>s) and merely returns the invocant. It\nis usually used to\nL<interpolate|/language/quoting#Interpolation:_qq> entire arrays / hashes into\nstrings or to L<decont|/language/glossary#decont>.\n\n    my @words = \"cruel\", \"world\";\n    say \"Hello, @words[]!\";  # OUTPUT: «Hello, cruel world!␤»\n\n    my $list = <a b c>;\n    .say for $list;   # OUTPUT: «(a b c)␤»\n    .say for $list<>; # OUTPUT: «a␤b␤c␤»\n    .say for $list[]; # OUTPUT: «a␤b␤c␤»\n\n    my @fib = 1,1, * + * … *;\n    say @fib[];                 # OUTPUT: «[...]␤»\n\n=head1 Multiple dimensions\n\nDimensions in subscripts are separated by a semicolon, allowing to mix lists of\nelements and dimensions.\n\n    my @twodim = (<a b c>, (1, 2, 3));\n    say @twodim;\n    # OUTPUT: «[(a b c) (1 2 3)]␤»\n\n    say @twodim[0,1;1]; # 2nd element of both lists\n    # OUTPUT: «(b 2)␤»\n\n    my %pantheon = %('Baldr' => 'consort' => 'Nanna' ,\n                     'Bragi' => 'consort' => 'Iðunn' ,\n                     'Nótt'  => 'consort' => 'Dellingr' );\n    say %pantheon{'Bragi','Nótt';'consort'}; # 'consort' value for both keys\n    # OUTPUT: «(Iðunn Dellingr)␤»\n\nX<|Syntax,flattening>\n\nMultidimensional subscripts can be used to flatten nested lists when combined\nwith L<C<Whatever>|/type/Whatever>.\n\n    my @toomany = [[<a b>], [1, 2]];\n    say @toomany;\n    # OUTPUT: «[[a b] [1 2]]␤»\n\n    say @toomany[*;*];\n    # OUTPUT: «(a b 1 2)␤»\n\nYou can use as many I<flattening semicolons> as you want; there will be, at\nmost, as many nesting levels flattened as the number of semicolons:\n\n    say [[1,2,[3,4]],[4,5]][*;*];     # OUTPUT: «(1 2 [3 4] 4 5)␤»\n    say [[1,2,[3,4]],[4,5]][*;*;*;*]; # OUTPUT: «(1 2 3 4 4 5)␤»\n\nIn the first example, with one L<C<Whatever>|/type/Whatever> less than the number of levels, the\ndeepest one will not be flattened; in the second case it is, since it's greater\nthan the number of levels.\n\nYou can use L<C<Whatever>|/type/Whatever> to select ranges or \"rows\" in\nmultidimensional subscripts.\n\n    my @a = [[1,2], [3,4]];\n    say @a[*;1]; # 2nd element of each sub list\n    # OUTPUT: «(2 4)␤»\n    my @a = (<1 c 6>, <2 a 4>, <5 b 3>);\n    say @a.sort( { $_[1] } ); # sort by 2nd column\n    # OUTPUT: «((2 a 4) (5 b 3) (1 c 6))␤»\n\n=head1 Modifying elements\n\n=head1 Autovivification\n\nSubscripts participate in \"autovivification\", i.e. the process by which arrays\nand hashes automatically spring into existence when needed, so that you can\nbuild nested data structures without having to pre-declare the collection type\nat each level:\n\n=begin code\nmy $beatles;\n\n$beatles{\"White Album\"}[0] = \"Back in the U.S.S.R.\";  # autovivification!\n\nsay $beatles.raku;  # OUTPUT: «${\"White Album\" => $[\"Back in the U.S.S.R.\"]}␤»\n=end code\n\nC<$beatles> started out undefined, but became a L<C<Hash>|/type/Hash> object\nbecause it was subscripted with C<{ }> in the assignment. Similarly,\nC<$beatles{\"White Album\"}> became an L<C<Array>|/type/Array> object due to being\nsubscripted with C<[ ]> in the assignment.\n\nNote that the subscripting itself does not cause autovivification: It only\nhappens when the result of the subscripting chain is I<assigned> to (or\notherwise mutated).\n\n=comment TODO: Add expanded documentation on autovivification (which affects\n               more than just subscripts, i.e. also routines like C<push>), at\n               /language/datastructures.html, and link to it from here.\n\n\n=head1 Binding\n\nA subscripting expression may also be used as the left-hand-side of a binding\nstatement. If supported by the subscripted collection's type, this replaces\nwhatever value container would be naturally found at that \"slot\" of the\ncollection, with the specified container.\n\nThe built-in L<C<Array>|/type/Array> and L<C<Hash>|/type/Hash> types support this in\norder to allow building complex linked data structures:\n\n    my @a = 10, 11, 12, 13;\n    my $x = 1;\n\n    @a[2] := $x;  # Bound! (@a[2] and $x refer to the same container now.)\n\n    $x++; @a[2]++;\n\n    say @a;  # OUTPUT: «[10 11 3 13]␤»\n    say $x;  # OUTPUT: «3␤»\n\nThis can be specially useful when lazy data structures are part of a bigger one.\n\n=begin code\nmy @fib = 1,1, * + * … ∞;\nmy @lucas = 1,3, * + * … ∞;\nmy %sequences;\n%sequences<f> := @fib;\n%sequences<l> := @lucas;\nfor %sequences.keys -> $s {\n    for ^10 -> $n {\n        say %sequences{$s}[100+$n*10]/%sequences{$s}[101+$n*10];\n    }\n}\n# OUTPUT: 0.6180339887498949 times 20.\n=end code\n\nIn this case, hash keys are bound to lazily generated sequences. The fact that\nthey are bound means that whatever state has been computed is shared by the hash\nvalue and the sequence it's bound to, making computations of subsequent elements\nfaster.\n\n=comment TODO: Add expanded documentation on building complex data structures\n               at /language/datastructures.html, and link to it from here.\n\nSee L<method C<BIND-POS>|#method BIND-POS> and L<method C<BIND-KEY>|#method\nBIND-KEY> for the underlying mechanism.\n\n\n=head1 Adverbs\n\nThe return value and possible side-effect of a subscripting operation can be\ncontrolled using adverbs; these are defined on the relevant subscript\nL<operators|/language/operators#Method_postfix_precedence>.\n\nBeware of the relatively loose precedence of operator adverbs, which may\nrequire you to add parentheses in compound expressions:\n\n=for code :skip-test<illustrates error>\nif $foo || %hash<key>:exists { ... }    # WRONG, tries to adverb the || op\n=for code :preamble<my $foo; my %hash;>\nif $foo || (%hash<key>:exists) { ... }  # correct\nif $foo or %hash<key>:exists { ... }    # also correct\n\nThe supported adverbs are:\n\nX<|Adverbs,:exists (subscript adverb)>\n=head2 C<:exists>\n\nReturns whether or not the requested element exists, instead of returning the\nelement's actual value. This can be used to distinguish between elements with\nan undefined value, and elements that aren't part of the collection at all:\n\n    my @foo = Any, 10;\n    say @foo[0].defined;    # OUTPUT: «False␤»\n    say @foo[0]:exists;     # OUTPUT: «True␤»\n    say @foo[2]:exists;     # OUTPUT: «False␤»\n    say @foo[0, 2]:exists;  # OUTPUT: «(True False)␤»\n\n    my %fruit = apple => Any, orange => 10;\n    say %fruit<apple>.defined;       # OUTPUT: «False␤»\n    say %fruit<apple>:exists;        # OUTPUT: «True␤»\n    say %fruit<banana>:exists;       # OUTPUT: «False␤»\n    say %fruit<apple banana>:exists; # OUTPUT: «(True False)␤»\n\nMay also be negated to test for non-existence:\n\n    =begin code :preamble<my %fruit = :apple(Any), :orange(10)>\n    say %fruit<apple banana>:!exists; # OUTPUT: «(False True)␤»\n    =end code\n\nTo check if I<all> elements of a slice exist, use an L<all|/routine/all>\njunction:\n\n    =begin code :preamble<my %fruit;>\n    if all %fruit<apple orange banana>:exists { ... }\n    =end code\n\nIt can be used on multi-dimensional arrays and hashes:\n\n    my @multi-dim = 1, [2, 3, [4, 5]];\n    say @multi-dim[1;2;0]:exists;                # OUTPUT: «True␤»\n    say @multi-dim[1;2;5]:exists;                # OUTPUT: «False␤»\n\n    my %multi-dim = 1 => { foo => { 3 => 42 } };\n    say %multi-dim{1;'foo';3}:exists;            # OUTPUT: «True␤»\n    say %multi-dim{1;'bar';3}:exists;            # OUTPUT: «False␤»\n\n\nC<:exists> can be combined with the L<C<:delete>|#:delete> and\nL<C<:p>|#:p>/L<C<:kv>|#:kv> adverbs - in which case the behavior is determined\nby those adverbs, except that any returned element I<value> is replaced with the\ncorresponding L<C<Bool>|/type/Bool> indicating element I<existence>.\n\nSee L<method C<EXISTS-POS>|#method EXISTS-POS> and L<method\nC<EXISTS-KEY>|#method EXISTS-KEY> for the underlying mechanism.\n\nX<|Adverbs,:delete (subscript adverb)>\n=head2 C<:delete>\n\nDelete the element from the collection or, if supported by the collection,\ncreates a hole at the given index, in addition to returning its value.\n\n    my @tens = 0, 10, 20, 30;\n    say @tens[3]:delete;     # OUTPUT: «30␤»\n    say @tens;               # OUTPUT: «[0 10 20]␤»\n\n    my %fruit = apple => 5, orange => 10, banana => 4, peach => 17;\n    say %fruit<apple>:delete;         # OUTPUT: «5␤»\n    say %fruit<peach orange>:delete;  # OUTPUT: «(17 10)␤»\n    say %fruit;                       # OUTPUT: «{banana => 4}␤»\n\nNote that assigning L<C<Nil>|/type/Nil> will revert the container at the given index to its\ndefault value. It will not create a hole. The created holes can be tested for\nwith C<:exists> but iteration will not skip them and produce undefined values\ninstead.\n\n    my @a = 1, 2, 3;\n    @a[1]:delete;\n    say @a[1]:exists;\n    # OUTPUT: «False␤»\n    .say for @a;\n    # OUTPUT: «1␤(Any)␤3␤»\n\nWith the negated form of the adverb, the element is not actually deleted. This\nmeans you can pass a flag to make it conditional:\n\n=begin code :preamble<my %fruit = :10apple; my $flag = True>\nsay %fruit<apple> :delete($flag);  # deletes the element only if $flag is\n                                   # true, but always returns the value.\n=end code\n\nIt can be combined with the L<C<:exists>|#:exists> and\nL<C<:p>|#:p>/L<C<:kv>|#:kv>/L<C<:k>|#:k>/L<C<:v>|#:v> adverbs -\nin which case the return value will be determined by those adverbs, but the\nelement will at the same time also be deleted.\n\nSee L<method C<DELETE-POS>|#method DELETE-POS> and L<method\nC<DELETE-KEY>|#method DELETE-KEY> for the underlying mechanism.\n\nYou can use also these adverbs on associative type objects, but it will\nactually do nothing; it will also return L<C<Nil>|/type/Nil>\n\n=for code\nsay Hash<foo>:delete; # OUTPUT: «Nil␤»\n\nThe adverb can be used on lazy arrays too:\n\n=for code\nmy @lazy-array = lazy 1, 11, 121 ... 10**100;\n@lazy-array[2**24]:delete;\n\nX<|Adverbs,:p (subscript adverb)>\n=head2 C<:p>\n\nReturn both the index/key and the value of the element, in the form of a\nL<C<Pair>|/type/Pair>, and silently skip nonexistent elements:\n\n    my  @tens = 0, 10, 20, 30;\n    say @tens[1]:p;        # OUTPUT: «1 => 10␤»\n    say @tens[0, 4, 2]:p;  # OUTPUT: «(0 => 0 2 => 20)␤»\n\n    my  %month = Jan => 1, Feb => 2, Mar => 3;\n    say %month<Feb>:p;          # OUTPUT: «Feb => 2␤»\n    say %month<Jan Foo Mar>:p;  # OUTPUT: «(Jan => 1 Mar => 3)␤»\n\nIf you I<don't> want to skip nonexistent elements, use the negated form:\n\n    =begin code :preamble<my %month = :1Jan, :2Feb, :3Mar>\n    say %month<Jan Foo Mar>:!p;  # OUTPUT: «(Jan => 1 Foo => (Any) Mar => 3)␤»\n    =end code\n\nIt can be combined with the L<C<:exists>|#:exists> and L<C<:delete>|#:delete> adverbs.\n\nSee also the L<pairs|/routine/pairs> routine.\n\nX<|Adverbs,:kv (subscript adverb)>\n=head2 C<:kv>\n\nReturn both the index/key and the value of the element, in the form of a\nL<C<List>|/type/List>, and silently skip nonexistent elements. When used on a\nL<slice|#Slices>, the return value is a single flat list of interleaved keys\nand values:\n\n    my  @tens = 0, 10, 20, 30;\n    say @tens[1]:kv;        # OUTPUT: «(1 10)␤»\n    say @tens[0, 4, 2]:kv;  # OUTPUT: «(0 0 2 20)␤»\n\n    my  %month = Jan => 1, Feb => 2, Mar => 3;\n    say %month<Feb>:kv;          # OUTPUT: «(Feb 2)␤»\n    say %month<Jan Foo Mar>:kv;  # OUTPUT: «(Jan 1 Mar 3)␤»\n\nIf you I<don't> want to skip nonexistent elements, use the negated form:\n\n    =begin code :preamble<my %month = :1Jan, :2Feb, :3Mar>\n    say %month<Jan Foo Mar>:!kv;  # OUTPUT: «(Jan 1 Foo (Any) Mar 3)␤»\n    =end code\n\nThis adverb is commonly used to iterate over slices:\n\n    =begin code :preamble<my %month>\n    for %month<Feb Mar>:kv -> $month, $i {\n        say \"$month had {Date.new(2015, $i, 1).days-in-month} days in 2015\"\n    }\n    =end code\n\nIt can be combined with the L<C<:exists>|#:exists> and L<C<:delete>|#:delete> adverbs.\n\nSee also the L<kv|/routine/kv> routine.\n\nX<|Adverbs,:k (subscript adverb)>\n=head2 C<:k>\n\nReturn only the index/key of the element, rather than its value, and silently\nskip nonexistent elements:\n\n    my @tens = 0, 10, 20, 30;\n    say @tens[1]:k;        # OUTPUT: «1␤»\n    say @tens[0, 4, 2]:k;  # OUTPUT: «(0 2)␤»\n\n    my %month = Jan => 1, Feb => 2, Mar => 3;\n    say %month<Feb>:k;          # OUTPUT: «Feb␤»\n    say %month<Jan Foo Mar>:k;  # OUTPUT: «(Jan Mar)␤»\n\nIf you I<don't> want to skip nonexistent elements, use the negated form:\n\n    =begin code :preamble<my %month = :1Jan, :2Feb, :3Mar>\n    say %month<Jan Foo Mar>:!k;  # OUTPUT: «(Jan Foo Mar)␤»\n    =end code\n\nSee also the L<keys|/routine/keys> routine.\n\nX<|Adverbs,:v (subscript adverb)>\n=head2 C<:v>\n\nReturn the bare value of the element (rather than potentially returning a\nmutable value container), and silently skip nonexistent elements:\n\n    =begin code\n    my @tens = 0, 10, 20, 30;\n    say @tens[1]:v;        # OUTPUT: «10␤»\n    say @tens[0, 4, 2]:v;  # OUTPUT: «(0, 20)␤»\n    @tens[3] = 31;         # OK\n    @tens[3]:v = 31;       # ERROR, Cannot modify an immutable Int (31)\n\n    my %month = Jan => 1, Feb => 2, Mar => 3;\n    say %month<Feb>:v;          # OUTPUT: «2␤»\n    say %month<Jan Foo Mar>:v;  # OUTPUT: «(1 3)␤»\n    =end code\n\nIf you I<don't> want to skip nonexistent elements, use the negated form:\n\n    =begin code :preamble<my %month = :1Jan, :2Feb, :3Mar>\n    say %month<Jan Foo Mar>:!v;  # OUTPUT: «(1 (Any) 3)␤»\n    =end code\n\nSee also the L<values|/routine/values> routine.\n\n=head1 Custom types\n\nThe subscripting interfaces described on this page are not meant to be\nexclusive to Raku's built-in collection types - you can (and should)\nreuse them for any custom type that wants to provide access to data by\nindex or key.\n\nYou don't have to manually overload the L<C<postcircumfix [ ]>|/language/operators#postcircumfix_[_]>\nand L<C<postcircumfix { }>|/language/operators#postcircumfix_{_}> operators and re-implement all their magic,\nto achieve that - instead, you can rely on the fact that their standard\nimplementation dispatches to a well-defined set of low-level methods behind\nthe scenes. For example:\n\n=table\n    when you write:    this gets called behind the scenes:\n    ===============    ==============================================\n    %foo<aa>           %foo.AT-KEY(\"aa\")\n    %foo<aa>:delete    %foo.DELETE-KEY(\"aa\")\n    @foo[3, 4, 5]      @foo.AT-POS(3), @foo.AT-POS(4), @foo.AT-POS(5)\n    @foo[*-1]          @foo.AT-POS(@foo.elems - 1)\n\nSo in order to make subscripting work, you only have to implement or\ndelegate those low-level methods (L<detailed below|#Methods_to_implement_for_positional_subscripting>) for your custom type.\n\nIf you do, you should also let your type compose the L<C<Positional>|\n/type/Positional> or L<C<Associative>|/type/Associative> role,\nrespectively. This doesn't add any functionality per se, but announces (and\nmay be used to check) that the type implements the corresponding\nsubscripting interface.\n\n=head2 Custom type example\n\nImagine a C<HTTP::Header> type which, despite being a custom class with special\nbehavior, can be indexed like a hash:\n\n    =begin code\n    my $request = HTTP::Request.new(GET => \"raku.org\");\n    say $request.header.^name;  # OUTPUT: «HTTP::Header␤»\n\n    $request.header<Accept> = \"text/plain\";\n    $request.header{'Accept-' X~ <Charset Encoding Language>} = <utf-8 gzip en>;\n    $request.header.push('Accept-Language' => \"fr\");  # like .push on a Hash\n\n    say $request.header<Accept-Language>.raku;  # OUTPUT: «[\"en\", \"fr\"]␤»\n\n    my $rawheader = $request.header.Str;  # stringify according to HTTP spec\n    =end code\n\nA simple way to implement this class would be to give it an attribute of type\nL<C<Hash>|/type/Hash>, and delegate all subscripting and iterating related\nfunctionality to that attribute (using a custom type constraint to make sure\nusers don't insert anything invalid into it):\n\n    =begin code\n    class HTTP::Header does Associative {\n        subset StrOrArrayOfStr where Str | ( Array & {.all ~~ Str} );\n\n        has %!fields of StrOrArrayOfStr\n                     handles <AT-KEY EXISTS-KEY DELETE-KEY push\n                              iterator list kv keys values>;\n\n        method Str { #`[not shown, for brevity] }\n    }\n    =end code\n\nHowever, HTTP header field names are supposed to be case-insensitive (and\npreferred in camel-case). We can accommodate this by taking the C<*-KEY>\nand C<push> methods out of the C<handles> list, and implementing them\nseparately like this:\n\n    =begin code :skip-test<continued example>\n    method AT-KEY     ($key) is rw { %!fields{normalize-key $key}        }\n    method EXISTS-KEY ($key)       { %!fields{normalize-key $key}:exists }\n    method DELETE-KEY ($key)       { %!fields{normalize-key $key}:delete }\n    method push(*@_) { #`[not shown, for brevity] }\n\n    sub normalize-key ($key) { $key.subst(/\\w+/, *.tc, :g) }\n    =end code\n\nNote that subscripting C<%!fields> returns an appropriate rw container, which\nour C<AT-KEY> can simply pass on.\n\nHowever, we may prefer to be less strict about user input and instead take\ncare of sanitizing the field values ourselves. In that case, we can remove\nthe C<StrOrArrayOfStr> type constraint on C<%!fields>, and replace our\nC<AT-KEY> implementation with one that returns a custom L<C<Proxy>|/type/Proxy> container\nwhich takes care of sanitizing values on assignment:\n\n    =begin code :skip-test<continued example>\n    multi method AT-KEY (::?CLASS:D: $key) is rw {\n        my $element := %!fields{normalize-key $key};\n\n        Proxy.new(\n            FETCH => method () { $element },\n\n            STORE => method ($value) {\n                $element = do given $value».split(/',' \\s+/).flat {\n                    when 1  { .[0] }    # a single value is stored as a string\n                    default { .Array }  # multiple values are stored as an array\n                }\n            }\n        );\n    }\n    =end code\n\nNote that declaring the method as C<multi> and restricting it to C<:D> (defined\ninvocants) makes sure that the undefined case is passed through to the default\nimplementation provided by L<C<Any>|/type/Any> (which is involved in auto-vivification).\n\n=head2 Methods to implement for positional subscripting\n\nIn order to make index-based subscripting via L<C<postcircumfix [ ]>|\n/language/operators#postcircumfix_[_]> work for your custom type, you should\nimplement at least C<elems>, C<AT-POS> and C<EXISTS-POS> - and optionally\nothers as detailed below.\n\n=head3 method elems\n\n    multi method elems(::?CLASS:D:)\n\nExpected to return a number indicating how many subscriptable elements\nthere are in the object. May be called by users directly, and is also\ncalled by L<C<postcircumfix [ ]>|/language/operators#postcircumfix_[_]> when\nindexing elements from the end, as in C<@foo[*-1]>.\n\nIf not implemented, your type will inherit the default implementation from\nL<C<Any>|/type/Any> that always returns C<1> for defined invocants - which is most likely not\nwhat you want. So if the number of elements cannot be known for your positional\ntype, add an implementation that L<fail|/routine/fail>s or L<die|/routine/die>s,\nto avoid silently doing the wrong thing.\n\n=head3 method AT-POS\n\n=comment When modifying this section, please also adapt the AT-KEY\n         section accordingly as they are very similar.\n\n    multi method AT-POS (::?CLASS:D: $index)\n\n=comment TODO: Cover the case of multi-dim indices (also for all the other\n               methods below), after jnthn's ongoing refactor is finished.\n\nExpected to return the element at position C<$index>. This is what\nL<C<postcircumfix [ ]>|/language/operators#postcircumfix_[_]> normally calls.\n\nIf you want an element to be mutable (like they are for the built-in\nL<C<Array>|/type/Array> type), you'll have to make sure to return it in the form of\nan item container that evaluates to the element's value when read, and updates\nit when assigned to. Remember to use C<return-rw> or the C<is rw> routine trait\nto make that work; see the L<example|/language/subscripts#Custom_type_example>.\n\n=head3 method EXISTS-POS\n\n=comment When modifying this section, please also adapt the EXISTS-KEY\n         section accordingly as they are very similar.\n\n    multi method EXISTS-POS (::?CLASS:D: $index)\n\nExpected to return a Bool indicating whether or not there is an element at\nposition C<$index>. This is what L<C<postcircumfix [ ]>|\n/language/operators#postcircumfix_[_]> calls when invoked like C<@foo[42]:exists>.\n\nWhat \"existence\" of an element means, is up to your type.\n\nIf you don't implement this, your type will inherit the default implementation\nfrom L<C<Any>|/type/Any>, which returns True for 0 and False for any other index - which is\nprobably not what you want. So if checking for element existence cannot be done\nfor your type, add an implementation that L<fail|/routine/fail>s or\nL<die|/routine/die>s, to avoid silently doing the wrong thing.\n\n=head3 method DELETE-POS\n\n=comment When modifying this section, please also adapt the DELETE-KEY\n         section accordingly as they are very similar.\n\n    multi method DELETE-POS (::?CLASS:D: $index)\n\nExpected to delete the element at position C<$index>, and return the value\nit had. This is what L<C<postcircumfix [ ]>|/language/operators#postcircumfix_[_]>\ncalls when invoked like C<@foo[42]:delete>.\n\nWhat \"deleting\" an element means, is up to your type.\n\nImplementing this method is optional; if you don't, users trying to delete\nelements from an object of this type will get an appropriate error message.\n\n=head3 method ASSIGN-POS\n\n=comment When modifying this section, please also adapt the ASSIGN-KEY\n         section accordingly as they are very similar.\n\n    multi method ASSIGN-POS (::?CLASS:D: $index, $new)\n\nExpected to set the element at position C<$index> to the value C<$new>.\nImplementing this is entirely optional; if you don't, C<self.AT-POS($index)\n= $new> is used instead, and if you do, you should make sure it has the\nsame effect.\n\nThis is meant as an opt-in performance optimization, so that simple\nassignments like C<@numbers[5] = \"five\"> can operate without having to call\nC<AT-POS> (which would have to create and return a potentially expensive\ncontainer object).\n\nNote that implementing C<ASSIGN-POS> does I<not> relieve you from making\nC<AT-POS> a C<rw> method though, because less trivial\nassignments/modifications such as C<@numbers[5]++> will still use\nC<AT-POS>.\n\n=head3 method BIND-POS\n\n=comment When modifying this section, please also adapt the BIND-KEY\n         section accordingly as they are very similar.\n\n    multi method BIND-POS (::?CLASS:D: $index, \\new)\n\nExpected to bind the value or container C<new> to the slot at position\nC<$index>, replacing any container that would be naturally found there.\nThis is what is called when you write:\n\n    =begin code :preamble<my @numbers;>\n    my $x = 10;\n    @numbers[5] := $x;\n    =end code\n\nThe generic L<C<Array>|/type/Array> class supports this in order to allow building\ncomplex linked data structures, but for more domain-specific types it may not\nmake sense, so don't feel compelled to implement it. If you don't, users will\nget an appropriate error message when they try to bind to a positional slot of\nan object of this type.\n\n=head3 method STORE\n\n=comment When modifying this section, please also adapt the STORE\n         section in Associative accordingly as they are very similar.\n\n    method STORE (::?CLASS:D: \\values, :$INITIALIZE)\n\nThis method should only be supplied if you want to support this syntax:\n\n=for code :preamble<role Foo {}>\nmy @a is Foo = 1,2,3;\n\nWhich is used for binding your implementation of the L<C<Positional>|/type/Positional> role.\n\nC<STORE> should accept the values to (re-)initialize the object with.  The\noptional named parameter will contain a C<True> value when the method is called\non the object for the first time. It should return the invocant.\n\n=begin code\nrole Logger { method log( Str $msg) {…}}\n\nclass ConsoLogger does Logger { method log ( Str $msg ) { \"❢ $msg\".say }}\n\nclass DNA {\n    has $.chain;\n    has Logger $!logger;\n\n    submethod BUILD( :$chain, :$logger = ConsoLogger.new() ) {}\n\n    method STORE (Str $chain where {\n            /^^ <[ACGT]>+ $$ / and\n            .chars %% 3\n        },\n        :$INITIALIZE --> DNA) {\n\n        if ($INITIALIZE) {\n            $!logger = ConsoLogger.new();\n            $!logger.log( \"Initialized\" );\n        }\n\n        $!chain  := $chain;\n        $!logger.log(\"Change value to $chain\" );\n        self\n    }\n\n    method Str(::?CLASS:D:) { return $!chain.comb.rotor(3).map( *.join(\"\")).join(\"|\") }\n};\n\nmy @string is DNA = 'GAATCC';    # OUTPUT: «❢ Initialized␤❢ Change value to GAATCC␤»\nsay ~@string;                    # OUTPUT: «GAA|TCC␤»\n@string = 'ACGTCG';              # OUTPUT: «❢ Change value to ACGTCG␤»\nsay  ~@string;                   # OUTPUT: «ACG|TCG␤»\n=end code\n\nThis code takes into account the value of C<$INITIALIZE>, which is set to\nC<True> only if we are assigning a value to a variable declared using the C<is>\nsyntax for the first time; for instance, as in this case, we might need to\ninitialize any injected dependency. The C<STORE> method should set the C<self>\nvariable and return it in all cases, including when the variable has already\nbeen initialized; however, only in the first case we need to initialize the\nlogger we are using in this example.\n\nThe presence of the C<INITIALIZE> flag can be also used to create immutable\ndata structures:\n\n=begin code\nclass A {\n    has @.foo handles <Str gist raku>;\n    multi method STORE(*@!foo, :$INITIALIZE!) { }\n    multi method STORE(|) { die \"Immutable\" }\n}\n\nmy @a is A = 1,2,3,4;\nsay @a;        # OUTPUT: «[1,2,3,4]␤»\n@a = 4,5,6,7;  # dies: Immutable\n=end code\n\n=head2 Methods to implement for associative subscripting\n\nIn order to make key-based subscripting via L<C<postcircumfix { }>|\n/language/operators#postcircumfix_{_}> work for your custom type, you should\nimplement at least C<AT-KEY> and C<EXISTS-KEY> - and optionally\nothers as detailed below.\n\n=head3 method AT-KEY\n\n=comment When modifying this section, please also adapt the AT-POS\n         section accordingly as they are very similar.\n\n    multi method AT-KEY (::?CLASS:D: $key)\n\nExpected to return the element associated with C<$key>. This is what\nL<C<postcircumfix { }>|/language/operators#postcircumfix_{_}> normally calls.\n\nIf you want an element to be mutable (like they are for the built-in\nL<C<Hash>|/type/Hash> type), you'll have to make sure to return it in the form of\nan item container that evaluates to the element's value when read, and updates\nit when assigned to. Remember to use C<return-rw> or the C<is rw> routine trait\nto make that work; see the L<example|/language/subscripts#Custom_type_example>.\n\nOn the other hand if you want your collection to be read-only, feel free\nto return non-container values directly.\n\n=head3 method EXISTS-KEY\n\n=comment When modifying this section, please also adapt the EXISTS-POS\n         section accordingly as they are very similar.\n\n    multi method EXISTS-KEY (::?CLASS:D: $key)\n\nExpected to return a Bool indicating whether or not there is an element\nassociated with C<$key>. This is what L<C<postcircumfix { }>|/language/operators#postcircumfix_{_}>\ncalls when invoked like C<<%foo<aa>:exists>>.\n\nWhat \"existence\" of an element means, is up to your type.\n\nIf you don't implement this, your type will inherit the default implementation\nfrom L<C<Any>|/type/Any>, which always returns False - which is probably not what you want.\nSo if checking for element existence cannot be done for your type, add an\nimplementation that L<fail|/routine/fail>s or L<die|/routine/die>s, to avoid\nsilently doing the wrong thing.\n\n=head3 method DELETE-KEY\n\n=comment When modifying this section, please also adapt the DELETE-POS\n         section accordingly as they are very similar.\n\n    multi method DELETE-KEY (::?CLASS:D: $key)\n\nExpected to delete the element associated with C<$key>, and return the\nvalue it had. This is what L<C<postcircumfix { }>|/language/operators#postcircumfix_{_}> calls when invoked like\nC<<%foo<aa>:delete>>.\n\nWhat \"deleting\" an element means, is up to your type - though it should\nusually cause C<EXISTS-KEY> to become C<False> for that key.\n\nImplementing this method is optional; if you don't, users trying to delete\nelements from an object of this type will get an appropriate error message.\n\n=head3 method ASSIGN-KEY\n\n=comment When modifying this section, please also adapt the ASSIGN-POS\n         section accordingly as they are very similar.\n\n    multi method ASSIGN-KEY (::?CLASS:D: $key, $new)\n\nExpected to set the element associated with C<$key> to the value C<$new>.\nImplementing this is entirely optional; if you don't, C<self.AT-KEY($key) =\n$new> is used instead, and if you do, you should make sure it has the same\neffect.\n\nThis is meant as an opt-in performance optimization, so that simple\nassignments C<<%age<Claire> = 29>> can operate without having to call\nC<AT-KEY> (which would have to create and return a potentially expensive\ncontainer object).\n\nNote that implementing C<ASSIGN-KEY> does I<not> relieve you from making\nC<AT-KEY> a C<rw> method though, because less trivial\nassignments/modifications such as C<<%age<Claire>++>> will still use\nC<AT-KEY>.\n\n=head3 method BIND-KEY\n\n=comment When modifying this section, please also adapt the BIND-POS\n         section accordingly as they are very similar.\n\n    multi method BIND-KEY (::?CLASS:D: $key, \\new)\n\nExpected to bind the value or container C<new> to the slot associated with\nC<$key>, replacing any container that would be naturally found there.\nThis is what is called when you write:\n\n    =begin code :preamble<my %age;>\n    my $x = 10;\n    %age<Claire> := $x;\n    =end code\n\nThe generic L<C<Hash>|/type/Hash> class supports this in order to allow building\ncomplex linked data structures, but for more domain-specific types it may not\nmake sense, so don't feel compelled to implement it. If you don't, users will\nget an appropriate error message when they try to bind to an associative slot of\nan object of this type.\n\n=head3 method STORE\n\n=comment When modifying this section, please also adapt the STORE\n         section in Positional accordingly as they are very similar.\n\n    method STORE (::?CLASS:D: \\values, :$INITIALIZE)\n\nThis method should only be supplied if you want to support the:\n\n=for code :preamble<role Foo {}>\nmy %h is Foo = a => 42, b => 666;\n\nsyntax for binding your implementation of the L<C<Associative>|/type/Associative> role.\n\nShould accept the values to (re-)initialize the object with, which either\ncould consist of L<C<Pair>|/type/Pair>s, or separate key/value pairs.  The optional\nnamed parameter will contain a C<True> value when the method is called on\nthe object for the first time.  Should return the invocant.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/syntax.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Syntax\n\n=SUBTITLE General rules of Raku syntax\n\nRaku borrows many concepts from human language. Which is not\nsurprising, considering it was designed by a linguist.\n\nIt reuses common elements in different contexts; it has the notion of nouns\n(terms) and verbs (operators); it is context-sensitive (in the every day\nsense, not necessarily in the Computer Science interpretation), so a\nsymbol can have a different meaning depending on whether a noun or a\nverb is expected.\n\nIt is also self-clocking, so that the parser can detect most of the\ncommon errors and give good error messages.\n\n=head1 Lexical conventions\n\nRaku code is Unicode text. Current implementations support UTF-8 as\nthe input encoding.\n\nSee also L<Unicode versus ASCII symbols|/language/unicode_ascii>.\n\n=head2 Free form\n\nRaku code is also free-form, in the sense that you are mostly free to\nchose the amount of whitespace you use, though in some cases, the\npresence or absence of whitespace carries meaning.\n\nSo you can write\n\n=begin code\nif True {\n    say \"Hello\";\n}\n=end code\n\nor\n\n=begin code\n    if True {\nsay \"Hello\"; # Bad indentation intended\n        }\n=end code\n\nor\n\n=begin code\nif True { say \"Hello\" }\n=end code\n\nor even\n\n=begin code\nif True {say \"Hello\"}\n=end code\n\nthough you can't leave out any more whitespace in this last example.\n\nX<|Syntax,Unspace>\n=head2 X<Unspace|Syntax,\\>\n\nIn places where the compiler would not allow a space you can use\nany amount of whitespace, as long as it is quoted with a backslash.\nUnspaces in tokens, however, are not supported. Newlines that are unspaced still\ncount when the compiler produces line numbers. Use cases for unspace are\nseparation of postfix operators and routine argument lists.\n\n    sub alignment(+@l) { +@l };\n    sub long-name-alignment(+@l) { +@l };\n    alignment\\         (1,2,3,4).say;\n    long-name-alignment(3,5)\\   .say;\n    say Inf+Inf\\i;\n\nIn this case, our intention was to make the C<.> of both statements, as\nwell as the parentheses, align, so we precede the whitespace used for\npadding with a C<\\>.\n\n=head2 Separating statements with semicolons\n\nA Raku program is a list of statements, separated by semicolons C<;>.\n\n=begin code\nsay \"Hello\";\nsay \"world\";\n=end code\n\nA semicolon after the final statement (or after the final statement\ninside a block) is optional.\n\n=begin code\nsay \"Hello\";\nsay \"world\"\n=end code\n\n=begin code\nif True {\n    say \"Hello\"\n}\nsay \"world\"\n=end code\n\n=head2 Implied separator rule (for statements ending in blocks)\n\nComplete statements ending in bare blocks can omit the trailing\nsemicolon, if no additional statements on the same line follow the\nblock's closing curly brace C<}>. This is called the \"implied separator\nrule.\" For example, you don't need to write a semicolon after an C<if>\nstatement block as seen above, and below.\n\n=begin code\nif True { say \"Hello\" }\nsay \"world\";\n=end code\n\nHowever, semicolons are required to separate a block from trailing\nstatements in the same line.\n\n=begin code\nif True { say \"Hello\" }; say \"world\";\n#                     ^^^ this ; is required\n=end code\n\nThis implied statement separator rule applies in other ways, besides\ncontrol statements, that could end with a bare block. For example, in\ncombination with the colon C<:> syntax for method calls.\n\n=begin code\nmy @names = <Foo Bar Baz>;\nmy @uppercase-names = @names.map: { .uc }    # OUTPUT: [FOO BAR BAZ]\n=end code\n\nFor a series of blocks that are part of the same C<if>/C<elsif>/C<else>\n(or similar) construct, the implied separator rule only applies at the\nend of the last block of that series. These three are equivalent:\n\n=begin code\nif True { say \"Hello\" } else { say \"Goodbye\" }; say \"world\";\n#                                            ^^^ this ; is required\n=end code\n\n=begin code\nif True { say \"Hello\" } else { say \"Goodbye\" } # <- implied statement separator\nsay \"world\";\n=end code\n\n=begin code\nif True { say \"Hello\" }   # still in the middle of an if/else statement\nelse    { say \"Goodbye\" } # <- no semicolon required because it ends in a block\n                          #    without trailing statements in the same line\nsay \"world\";\n=end code\n\n=head2 Comments\n\nComments are parts of the program text which are only intended for human\nreaders; the Raku compilers do not evaluate them as program text. They\nare part of the I<non-ambient> code that includes I<Pod6> text.\n\nComments count as whitespace in places where the absence or presence of\nwhitespace disambiguates possible parses.\n\n=head3 Single-line comments\n\nThe most common form of comments in Raku starts with a single hash character\nC<#> and goes until the end of the line.\n\n=begin code :skip-test<dies deliberately>\nif $age > 250 {     # catch obvious outliers\n    # this is another comment!\n    die \"That doesn't look right\"\n}\n=end code\n\nX<|Syntax,Embedded comments>\n=head3 Multi-line / embedded comments\n\nMulti-line and embedded comments start with a hash character, followed by a\nbacktick, and then a Unicode Open Punctuation character, and end with the matching\nClose Punctuation character. Whitespace is not permitted between the backtick and the\npunctuation character; it will be treated as a single-line comment.\nThe content can not only span multiple lines, but can also be embedded inline.\n\n=begin code\nif #`( why would I ever write an inline comment here? ) True {\n    say \"something stupid\";\n}\n=end code\n\nThese comments can extend multiple lines\n=begin code\n\n#`[\nAnd this is how a multi would work.\nThat says why we do what we do below.\n]\nsay \"No more\";\n=end code\n\nCurly braces inside the comment can be nested, so in C<#`{ a { b } c }>, the\ncomment goes until the very end of the string; this is why if the opening\nbracketing character also occurs in the body of the comment, e.g. C<#`[ This is a\nbox [ of stuff ] ]>, it must have a paired closing character, as shown. You may\nalso use multiple curly braces, such as C<#`{{ double-curly-brace }}>, which\nmight help disambiguate from nested delimiters. You can embed these comments in\nexpressions, as long as you don't insert them in the middle of keywords or\nidentifiers.\n\n=head3 Pod comments\n\nPod syntax can be used for multi-line comments\n\n=begin code\nsay \"this is code\";\n\n=begin comment\n\nHere are several\nlines\nof comment\n\n=end comment\n\nsay 'code again';\n=end code\n\n=head2 X<Identifiers|Language,identifiers>\n\nIdentifiers are grammatical building blocks that may be used to give a name\nto entities/objects such as constants, variables (e.g. L<C<Scalar>|/type/Scalar>s) and routines\n(e.g. L<C<Sub>|/type/Sub>s and Methods). In a L<variable name|/language/variables>, any sigil\n(and twigil) precedes the identifier and does not form a part thereof.\n\n    constant c = 299792458;     # identifier \"c\" names an Int\n    my $a = 123;                # identifier \"a\" in the name \"$a\" of a Scalar\n    sub hello { say \"Hello!\" }; # identifier \"hello\" names a Sub\n\nIdentifiers come in different forms: ordinary, extended, and compound\nidentifiers.\n\n=head3 Ordinary identifiers\n\nAn ordinary identifier is composed of a leading alphabetic character\nwhich may be followed by one or more alphanumeric characters. It may also\ncontain isolated, embedded apostrophes C<'> and/or hyphens C<->, provided\nthat the next character is each time alphabetic.\n\nThe definitions of \"alphabetic\" and \"alphanumeric\" include appropriate Unicode\ncharacters. Which characters are \"appropriate\" depends on the implementation.\nIn the Rakudo/MoarVM Raku implementation alphabetic characters include\ncharacters with the Unicode General Category value I<Letter> (L), and the\nunderscore C<_>. Alphanumeric characters additionally include characters with\nthe Unicode General Category value I<Number, Decimal Digit> (Nd).\n\n=begin code :skip-test<bad identifiers>\n# valid ordinary identifiers:\nx\n_snake_oil\nsomething-longer\nwith-numbers1234\ndon't-do-that\npiece_of_π\n駱駝道              # \"Rakuda-dō\", Japanese for \"Way of the camel\"\n=end code\n\n=begin code :skip-test<bad identifiers>\n# invalid ordinary identifiers:\n42                 # identifier does not start with alphabetic character\nwith-numbers1234-5 # embedded hyphen not followed by alphabetic character\nis-prime?          # question mark is not alphanumeric\nx²                 # superscript 2 is not alphanumeric (explained above)\n=end code\n\n=head3 Extended identifiers\n\nIt is often convenient to have names that contain characters that are not\nallowed in ordinary identifiers. Use cases include situations where a set of\nentities shares a common \"short\" name, but still needs for each of its elements\nto be identifiable individually. For example, you might use a module whose short\nname is C<Dog>, while its long name includes its naming authority and version:\n\n=begin code :skip-test<identifiers only>\nDog:auth<Somebody>:ver<1.0>  # long module names including author and version\nDog:auth<Somebody>:ver<2.0>\n\nuse Dog:auth<Somebody>:ver<2.0>;\n# Selection of second module causes its full name to be aliased to the\n# short name for the rest of # the lexical scope, allowing a declaration\n# like this.\nmy Dog $spot .= new(\"woof\");\n=end code\n\nSimilarly, sets of operators work together in various syntactic categories with\nnames like C<prefix>, C<infix> and C<postfix>. The official names of these\noperators often contain characters that are excluded from ordinary identifiers.\nThe long name is what constitutes the extended identifier, and includes this\nsyntactic category; the short name will be included in quotes in the definition:\n\n=begin code\ninfix:<+>                 # the official name of the operator in $a + $b\ninfix:<*>                 # the official name of the operator in $a * $b\ninfix:«<=»                # the official name of the operator in $a <= $b\n=end code\n\nFor all such uses, you can append one or more colon-separated strings to an\nordinary identifier to create a so-called I<extended identifier>. When appended\nto an identifier (that is, in postfix position), this colon-separated string\ngenerates unique variants of that identifier.\n\nThese strings have the form C<:key<value>>, wherein C<key> I<or> C<value> are\noptional; that is, after the colon that separates it from a regular identifier,\nthere will be a C<key> and/or a quoting bracketing construct such as C«< >», C<«\n»> or C<[' ']> which quotes one or more arbitrary characters C<value>.N<Starting\nwith Raku language version 6.d, colon pairs with C<sym> as the C<key> (e.g.\nC«:sym<foo>») are reserved for possible future use.>\n\n=begin code :skip-test<partly bad identifiers>\n# exemplary valid extended identifiers:\npostfix:<²>               # the official long name of the operator in $x²\nWOW:That'sAwesome\nWOW:That's<<🆒>>\nparty:sweet<16>\n\n# exemplary invalid extended identifiers:\nparty:16<sweet>           # 16 is not an ordinary identifier\nparty:16sweet\nparty:!a                  # ...and neither is !a\nparty:$a                  # ...nor $a\n=end code\n\nIn an extended identifier, the postfix string is considered an integral part of\nthe name, so C<infix:<+>> and C<infix:<->> are two different operators. The\nbracketing characters used, however, do not count as part of it; only the quoted\ndata matters. So these are all the same name:\n\n=begin code :skip-test<identifiers only>\ninfix:<+>\ninfix:<<+>>\ninfix:«+»\ninfix:['+']\ninfix:('+')\n=end code\n\nSimilarly, all of this works:\n\n=begin code\nmy $foo:bar<baz> = 'quux';\nsay $foo:bar«baz»;                               # OUTPUT: «quux␤»\nmy $take-me:<home> = 'Where the glory has no end';\nsay $take-me:['home'];                           # OUTPUT: «Where [...]␤»\nmy $foo:bar<2> = 5;\nsay $foo:bar(1+1);                               # OUTPUT: «5␤»\n=end code\n\nWhere an extended identifier comprises two or more colon pairs, their order\nis generally significant:\n\n=begin code\nmy $a:b<c>:d<e> = 100;\nmy $a:d<e>:b<c> = 200;\nsay $a:b<c>:d<e>;               # OUTPUT: «100␤», NOT: «200␤»\n=end code\n\nAn exception to this rule is I<module versioning>; so these identifiers\neffectively name the same module:\n\n=begin code :skip-test<needs dummy module>\nuse ThatModule:auth<Somebody>:ver<2.7.18.28.18>\nuse ThatModule:ver<2.7.18.28.18>:auth<Somebody>\n=end code\n\nFurthermore, extended identifiers support compile-time interpolation; this\nrequires the use of L<constants|/language/terms#Constants> for the interpolation\nvalues:\n\n=begin code\nconstant $c = 42;  # Constant binds to Int; $-sigil enables interpolation\nmy $a:foo<42> = \"answer\";\nsay $a:foo«$c»;    # OUTPUT: «answer␤»\n=end code\n\nAlthough quoting bracketing constructs are generally interchangeable in the\ncontext of identifiers, they are not identical. In particular, angle brackets\nC«< >» (which mimic single quote interpolation characteristics) cannot be used\nfor the interpolation of constant names.\n\n=begin code :skip-test<illustrates error>\nconstant $what = 'are';\nmy @we:<are>= <the champions>;\nsay @we:«$what»;     # OUTPUT: «[the champions]␤»\nsay @we:<$what>;\n# Compilation error: Variable '@we:<$what>' is not declared\n=end code\n\n=head3 Compound identifiers\n\nA compound identifier is an identifier that is composed of two or more\nordinary and/or extended identifiers that are separated from one another by a\ndouble colon C<::>.\n\nThe double colon C<::> is known as the I<namespace separator> or the\nI<package delimiter>, which clarifies its semantic function in a name: to force\nthe preceding portion of the name to be considered a\nL<package|/language/packages>/namespace through which the subsequent portion of\nthe name is to be located:\n\n    module MyModule {               # declare a module package\n        our $var = \"Hello\";         # declare package-scoped variable\n    }\n    say $MyModule::var              # OUTPUT: «Hello␤»\n\nIn the example above, C<MyModule::var> is a compound identifier, composed\nof the package name identifier C<MyModule> and the identifier part of the\nvariable name C<var>. Altogether C<$MyModule::var> is often referred\nto as a L<package-qualified name|/language/packages#Package-qualified_names>.\n\nSeparating identifiers with double colons causes the rightmost name to be\ninserted into existing (see above example) I<or automatically created>\npackages:\n\n=begin code\nmy $foo::bar = 1;\nsay OUR::.keys;           # OUTPUT: «(foo)␤»\nsay OUR::foo.HOW          # OUTPUT: «Perl6::Metamodel::PackageHOW.new␤»\n=end code\n\nThe last lines shows how the C<foo> package was created automatically, as a\ndeposit for variables in that namespace.\n\nThe double colon syntax enables runtime\nL<interpolation|/language/packages#Interpolating_into_names> of a string into a\npackage or variable name using C<::($expr)> where you'd ordinarily put a package\nor variable name:\n\n    my $buz = \"quux\";\n    my $bur::quux = 7;\n    say $bur::($buz);               # OUTPUT: «7␤»\n\n=head2 term C«term:<>»\n\nYou can use C«term:<>» to introduce new terms, which is handy for introducing\nconstants that defy the rules of normal identifiers:\n\n    use Test; plan 1; constant &term:<👍> = &ok.assuming(True);\n    👍\n    # OUTPUT: «1..1␤ok 1 - ␤»\n\nBut terms don't have to be constant: you can also use them for functions\nthat don't take any arguments, and force the parser to expect an\noperator after them. For instance:\n\n    sub term:<dice> { (1..6).pick };\n    say dice + dice;\n\ncan print any number between 2 and 12.\n\nIf instead we had declared C<dice> as a regular\n\n    sub dice() {(1...6).pick }\n\n, the expression C<dice + dice> would be parsed as\nC<dice(+(dice()))>, resulting in an error since C<sub dice> expects zero\narguments.\n\n=head1 Statements and expressions\n\nRaku programs are made of lists of statements. A special case of a statement\nis an I<expression>, which returns a value. For example C<if True { say 42 }>\nis syntactically a statement, but not an expression, whereas C<1 + 2> is an\nexpression (and thus also a statement).\n\nThe C<do> prefix turns statements into expressions. So while\n\n=begin code :skip-test<illustrates error>\nmy $x = if True { 42 };     # Syntax error!\n=end code\n\nis an error,\n\n   my $x = do if True { 42 };\n\nassigns the return value of the if statement (here C<42>) to the variable\nC<$x>.\n\n\n=head1 Terms\n\nTerms are the basic nouns that, optionally together with operators, can\nform expressions. Examples for terms are variables (C<$x>), barewords\nsuch as type names (L<C<Int>|/type/Int>), literals (C<42>), declarations (C<sub f() { }>)\nand calls (C<f()>).\n\nFor example, in the expression C<2 * $salary>, C<2> and C<$salary> are two\nterms (an L<C<Int>|/type/Int> literal and a L<variable|/language/variables>).\n\n=head2 Variables\n\nVariables typically start with a special character called the I<sigil>, and\nare followed by an identifier. Variables must be declared before you can use\nthem.\n\n    # declaration:\n    my $number = 21;\n    # usage:\n    say $number * 2;\n\nSee the L<documentation on variables|/language/variables> for more details.\n\n\n=head2 Barewords (constants, type names)\n\nPre-declared identifiers can be terms on their own. Those are typically type\nnames or constants, but also the term C<self> which refers to an object that\na method was called on (see L<objects|/language/objects>), and sigilless\nvariables:\n\n    say Int;                # OUTPUT: «(Int)␤»\n    #   ^^^ type name (built in)\n\n    constant answer = 42;\n    say answer;\n    #   ^^^^^^ constant\n\n    class Foo {\n        method type-name {\n            self.^name;\n          # ^^^^ built-in term 'self'\n        }\n    }\n    say Foo.type-name;     # OUTPUT: «Foo␤»\n    #   ^^^ type name\n\n\n=head2 Packages and qualified names\n\nNamed entities, such as variables, constants, classes, modules or subs, are part\nof a namespace. Nested parts of a name use C<::> to separate the hierarchy. Some\nexamples:\n\n=begin code :skip-test<identifiers only>\n$foo                # simple identifiers\n$Foo::Bar::baz      # compound identifiers separated by ::\n$Foo::($bar)::baz   # compound identifiers that perform interpolations\nFoo::Bar::bob(23)   # function invocation given qualified name\n=end code\n\nSee the L<documentation on packages|/language/packages> for more\ndetails.\n\n\n=head2 Literals\n\nA L<literal|https://en.wikipedia.org/wiki/Literal_%28computer_programming%29>\nis a representation of a constant value in source code. Raku has literals\nfor several built-in types, like L<C<Str>|/type/Str>, several numeric types,\nL<C<Pair>|/type/Pair>s and more.\n\nX<|Syntax,String (literals)>\n=head3 String literals\n\nString literals are surrounded by quotes:\n\n    say 'a string literal';\n    say \"a string literal\\nthat interprets escape sequences\";\n\nSee L<quoting|/language/quoting> for many more options, including\nL<interpolation quoting C<qq>|/language/quoting#Interpolation:_qq>. Raku uses\nthe standard escape characters in literals: C<\\0 \\a \\b \\t \\n \\f \\r \\e>,\nwith the same meaning as the ASCII escape codes, specified in\nL<the design document|https://github.com/Raku/old-design-docs/blob/master/S02-bits.pod#Backslash_sequences>.\n\n    say \"🔔\\a\";  # OUTPUT: «🔔␇␤»\n\nX<|Syntax,0b (radix form)>\nX<|Syntax,0d (radix form)>\nX<|Syntax,0o (radix form)>\nX<|Syntax,0x (radix form)>\nX<|Syntax,Number (literals)>\n=head3 X<Number literals|Syntax,Number literals>\n\nNumber literals are generally specified in base ten (which can be specified\nliterally, if needed, via the prefix C<0d>), unless a prefix like C<0x>\n(heB<x>adecimal, base 16), C<0o> (B<o>ctal, base 8) or C<0b> (B<b>inary, base 2)\nor an explicit base in adverbial notation like C«:16<A0>» specifies it\notherwise. Unlike other programming languages, leading zeros do I<not> indicate\nbase 8; instead a compile-time warning is issued.\n\nIn all literal formats, you can use underscores to group digits, although they\ndon't carry any semantic information; the following literals all evaluate to the\nsame number:\n\n=begin code :skip-test<literals only>\n1000000\n1_000_000\n10_00000\n100_00_00\n=end code\n\n=head4 L<C<Int>|/type/Int> literals\n\nIntegers default to signed base-10, but you can use other bases. For details,\nsee L<C<Int>|/type/Int>.\n\n=begin code :skip-test<literals only>\n# not a single literal, but unary - operator applied to numeric literal 2\n-2\n12345\n0xBEEF      # base 16\n0o755       # base 8\n:3<1201>    # arbitrary base, here base 3\n=end code\n\n=head4 L<C<Rat>|/type/Rat> literals\n\nL<C<Rat>|/type/Rat> literals (rationals) are very common, and take the\nplace of decimals or floats in many other languages. Integer division\nalso results in a L<C<Rat>|/type/Rat>.\n\n    =begin code :skip-test<literals only>\n    1.          # Error: A number must have at least one digit after the radix point\n    1.0\n    3.14159\n    -2.5        # Not actually a literal, but still a Rat\n    :3<21.0012> # Base 3 rational\n    ⅔\n    2/3         # Not actually a literal, but still a Rat\n    =end code\n\n=head4 L<C<Num>|/type/Num> literals\n\nScientific notation with an integer exponent to base ten after an C<e> produces\na L<C<Num>|/type/Num> (a floating point value):\n\n    =begin code :skip-test<literals only>\n    1.e0        # error: A number must have at least one digit after the radix point\n    1e0\n    6.022e23\n    1e-9\n    -2e48\n    2e2.5       # error\n    =end code\n\n=head4 L<C<Complex>|/type/Complex> literals\n\nL<C<Complex>|/type/Complex> numbers are written either as an imaginary number\n(which is just a rational number with postfix C<i> appended), or as a sum of\na real and an imaginary number:\n\n    =begin code :skip-test<literals only>\n    1.+2i       # error: A number must have at least one digit after the radix point\n    1+2.i       # error: A number must have at least one digit after the radix point\n    1+2i\n    6.123e5i    # note that this is 6.123e5 * i, not 6.123 * 10 ** (5i)\n    =end code\n\nX<|Syntax,Pairs (literals)>\n=head3 X<Pair literals|Syntax,Pair literals>\n\nL<C<Pair>|/type/Pair>s are made of a key and a value, and there are two\nbasic forms for constructing them: C«key => 'value'» and\nC<:key('value')>.\n\n=head4 Arrow pairs\n\nArrow pairs can have an expression, a string literal or a \"bare\nidentifier\", which is a string with ordinary-identifier syntax that does\nnot need quotes on the left-hand side:\n\n=begin code :skip-test<literals only>\nlike-an-identifier-ain't-it => 42\n\"key\" => 42\n('a' ~ 'b') => 1\n=end code\n\n=head4 Adverbial pairs (colon pairs)\n\nShort forms without explicit values:\n\n=begin code\nmy $thing = 42;\n:$thing                 # same as  thing => $thing\n:thing                  # same as  thing => True\n:!thing                 # same as  thing => False\n=end code\n\nThe variable form also works with other sigils, like C<:&callback> or\nC<:@elements>. If the value is a number literal, it can also be\nexpressed in this short form:\n\n    :42thing            # same as  thing => 42\n    :٤٢thing            # same as  thing => 42\n\nThis order is inverted if you use another alphabet\n\n     :٤٢ث              # same as   ث => ٤٢\n\nthe I<thaa> letter precedes the number.\n\nLong forms with explicit values:\n\n=begin code :skip-test<literals only>\n:thing($value)              # same as  thing => $value\n:thing<quoted list>         # same as  thing => <quoted list>\n:thing['some', 'values']    # same as  thing => ['some', 'values']\n:thing{a => 'b'}            # same as  thing => { a => 'b' }\n=end code\n\nX<|Syntax,Boolean (literals)>\n=head3 Boolean literals\n\nC<True> and C<False> are Boolean literals; they will always have initial capital\nletter.\n\n=head3 Array literals\n\nA pair of square brackets can surround an expression to form an itemized\nL<C<Array>|/type/Array> literal; typically there is a comma-delimited list\ninside:\n\n    say ['a', 'b', 42].join(' ');   # OUTPUT: «a b 42␤»\n    #   ^^^^^^^^^^^^^^ Array constructor\n\nIf the constructor is given a single L<C<Iterable>|/type/Iterable>, it'll\nclone and flatten it. If you want an L<C<Array>|/type/Array> with just 1 element that\nis an L<C<Iterable>|/type/Iterable>, ensure to use a comma after it:\n\n    my @a = 1, 2;\n    say [@a].raku;  # OUTPUT: «[1, 2]␤»\n    say [@a,].raku; # OUTPUT: «[[1, 2],]␤»\n\nThe L<C<Array>|/type/Array> constructor does not flatten other types of contents. Use\nthe L<C<Slip>|/type/Slip> prefix operator (C<|>) to flatten the needed\nitems:\n\n    my @a = 1, 2;\n    say [@a, 3, 4].raku;  # OUTPUT: «[[1, 2], 3, 4]␤»\n    say [|@a, 3, 4].raku; # OUTPUT: «[1, 2, 3, 4]␤»\n\nL<C<List>|/type/List> type can be explicitly created from an array\nliteral declaration without a coercion from Array, using B<is>\nL<trait|/language/traits> on declaration.\n\n    my @a is List = 1, 2; # a List, not an Array\n    # wrong: creates an Array of Lists\n    my List @a;\n\n=head3 Hash literals\n\nA leading associative sigil and pair of parenthesis C<%( )> can surround\na L<C<List>|/type/List> of L<C<Pair>|/type/Pair>s to form a L<C<Hash>|/type/Hash> literal; typically\nthere is a comma-delimited L<C<List>|/type/List> of L<C<Pair>|/type/Pair>s inside. If a non-pair is\nused, it is assumed to be a key and the next element is the value. Most\noften this is used with simple arrow pairs.\n\n    say %( a => 3, b => 23, :foo, :dog<cat>, \"french\", \"fries\" );\n    # OUTPUT: «a => 3, b => 23, dog => cat, foo => True, french => fries␤»\n\n    say %(a => 73, foo => \"fish\").keys.join(\" \");   # OUTPUT: «a foo␤»\n    #   ^^^^^^^^^^^^^^^^^^^^^^^^^ Hash constructor\n\nWhen assigning to a C<%>-sigiled variable on the left-hand side, the\nsigil and parenthesis surrounding the right-hand side L<C<Pair>|/type/Pair> are\noptional.\n\n    my %ages = fred => 23, jean => 87, ann => 4;\n\nBy default, keys in C<%( )> are forced to strings. To compose a hash with\nnon-string keys, use curly brace delimiters with a colon prefix C<:{ }> :\n\n    my $when = :{ (now) => \"Instant\", (DateTime.now) => \"DateTime\" };\n\nNote that with objects as keys, you cannot access non-string keys as strings:\n\n    say :{ -1 => 41, 0 => 42, 1 => 43 }<0>;  # OUTPUT: «(Any)␤»\n    say :{ -1 => 41, 0 => 42, 1 => 43 }{0};  # OUTPUT: «42␤»\n\nParticular types that implement L<C<Associative>|/type/Associative> role,\nL<C<Map>|/type/Map> (including L<C<Hash>|/type/Hash> and\nL<C<Stash>|/type/Stash> subclasses) and L<C<QuantHash>|/type/QuantHash> (and\nits subclasses), can be explicitly created from a hash literal without\na coercion, using B<is> L<trait|/language/traits> on declaration:\n\n    my %hash;                    # Hash\n    my %hash is Hash;            # explicit Hash\n    my %map is Map;              # Map\n    my %stash is Stash;          # Stash\n\n    my %quant-hash is QuantHash; # QuantHash\n\n    my %setty is Setty;          # Setty\n    my %set is Set;              # Set\n    my %set-hash is SetHash;     # SetHash\n\n    my %baggy is Baggy;          # Baggy\n    my %bag is Bag;              # Bag\n    my %bag-hash is BagHash;     # BagHash\n\n    my %mixy is Mixy;            # Mixy\n    my %mix is Mix;              # Mix\n    my %mix-hash is MixHash;     # MixHash\n\nNote that using a usual type declaration with a hash sigil creates a\ntyped Hash, not a particular type:\n\n    # This is wrong: creates a Hash of Mixes, not Mix:\n    my Mix %mix;\n    # Works with $ sigil:\n    my Mix $mix;\n    # Can be typed:\n    my Mix[Int] $mix-of-ints;\n\n=head3 Regex literals\n\nA L<C<Regex>|/type/Regex> is declared with slashes like C</foo/>. Note that\nthis C<//> syntax is shorthand for the full C<rx//> syntax.\n\n    =begin code :skip-test<literals only>\n    /foo/          # Short version\n    rx/foo/        # Longer version\n    Q :regex /foo/ # Even longer version\n\n    my $r = /foo/; # Regexes can be assigned to variables\n    =end code\n\n=head3 Signature literals\n\nSignatures can be used standalone for pattern matching, in addition to\nthe typical usage in sub and block declarations. A standalone signature\nis declared starting with a colon:\n\n    say \"match!\" if 5, \"fish\" ~~ :(Int, Str); # OUTPUT: «match!␤»\n\n    my $sig = :(Int $a, Str);\n    say \"match!\" if (5, \"fish\") ~~ $sig; # OUTPUT: «match!␤»\n\n    given \"foo\", 42 {\n      when :(Str, Str) { \"This won't match\" }\n      when :(Str, Int $n where $n > 20) { \"This will!\" }\n    }\n\nSee the L<signatures|/language/signatures> documentation for more information.\n\n=head2 Declarations\n\n=head3 Variable declaration\n\n    my $x;                          # simple lexical variable\n    my $x = 7;                      # initialize the variable\n    my Int $x = 7;                  # declare the type\n    my Int:D $x = 7;                # specify that the value must be defined (not undef)\n    my Int $x where { $_ > 3 } = 7; # constrain the value based on a function\n    my Int $x where * > 3 = 7;      # same constraint, but using Whatever shorthand\n\nSee L<Variable Declarators and\nScope|/language/variables#Variable_declarators_and_scope>\nfor more details on other scopes (C<our>, C<has>).\n\n=head3 Callable declarations\n\nRaku provides syntax for multiple L<C<Callable>|/type/Callable> code objects\n(that is, code objects that can be invoked, such as subroutines). Specifically,\nRaku provides syntax for subroutines (both single- and multiple-dispatch), code\nblocks, and methods (again, both single- and multiple-dispatch).\n\n=head4 Subroutine declaration\n\nSubroutines are created with the keyword C<sub> followed by an optional\nname, an optional signature and a code block. Subroutines are lexically\nscoped, so if a name is specified at the declaration time, the same name\ncan be used in the lexical scope to invoke the subroutine. A subroutine\nis an instance of type L<C<Sub>|/type/Sub> and can be assigned to any\ncontainer.\n\n    sub {}\n    # The minimal legal subroutine declaration\n\n    sub say-hello1 { say \"Hello!\" }\n    # A subroutine with a name\n\n    sub say-hello2(Str $to-whom) { say \"Hello $to-whom!\" }\n    # A subroutine with a name and a signature\n\nYou can assign subroutines to variables.\n\n    my &greet0 = sub { say \"Hello!\" }            # Unnamed sub assigned to &greet0\n    my &greet1 = sub say-hello1 { say \"Hello!\" } # Named sub assigned to &greet1\n\n\n=head4 Multiple-dispatch subroutine declaration\n\nSubroutines can be declared as a C<multi> – that is, as a subroutine that with\nmultiple candidates, each with a different signature.  A multiple dispatch\nsubroutine is created almost exactly like a single-dispatch subroutine: with the\nkeyword C<multi>, optionally followed by the keyword C<sub>, followed by an\noptional name, an optional signature, and a code block. See\nL<Multi-dispatch|/language/functions#Multi-dispatch> for details.\n\nThe two single-dispatch subroutines C<greet0> and C<greet1> (defined above)\ncould be combined into a single C<greet> multi as follows:\n\n    multi greet { say \"Hello!\" }\n    #     ^^^ optional\n    multi greet($name) { say \"Hello $name!\" }\n\nYou may optionally precede C<multi> declarations with a\nL<C<proto>|/language/functions#proto> declarations; C<proto>s declare a signature\nthat any call must conform to before being dispatched to candidates.  For\nexample, this C<proto> requires that all candidates take at least one positional\nparameter:\n\n    proto at-least1($, |) {*}\n    multi at-least1($first)          { note $first }\n    multi at-least1($first, $second) { note \"got two\" }\n    multi at-least1($first, :$named) { note \"got named\" }\n\n    # The following is legal to *declare* but can never be called\n    multi at-least1 { note \"Got none\"}\n\n\n=head4 Block declaration\n\nL<C<Block>|/type/Block>s are invocable code objects similar to subroutines but\nintended for small-scale code reuse.  Blocks are created by a code block inside\nof C<{ }> curly braces, optionally preceded by C«->» followed by a signature (or\nC«<->» followed by a signature for L<rw (aka,\nread-write)|/type/Routine#trait_is_rw> blocks).  If no signature is provided,\nBlocks can accept parameters implicitly by using placeholder variables with the\nL<C<^> twigil|/language/variables#The_^_twigil> and the L<C<:> twigil|/language/variables#The_:_twigil>.\nBlocks with neither an explicit nor implicit signature have a default signature of C<$_>.\n\n\n    my &greet0 = { say \"Hello!\" }     # Block stored in &greet0\n    my &greet1 = { say \"Hello $_!\" }  # Block with default signature\n    my &greet2 = -> $to-whom { say \"Hello $to-whom!\" }  # Block with explicit signature\n    my &greet3 = { say \"Hello $^to-whom!\" }             # Block with implicit positional\n    my &greet4 = { say \"Hello $:to-whom!\" }             # Block with implicit named\n\n    my &add1-in-place = <-> $a { ++$a }                 # Block with rw signature\n\n\nAlthough doing so is less idiomatic, Blocks may also be stored in scalar variables\n\n    my $greet = { say \"Hello!\" }\n\n=head4 Method declaration\n\nL<C<Method>|/type/Method>s are a callable code object invoked against a specific\nobject (called the method's \"invocant\").  Outside of a class declaration,\nmethods are declared by the C<method> keyword, followed by a signature, followed\nby a code block.  Within the method signature, the method's invocant is followed\nby a C<:> instead of the C<,> that normally separates arguments.  Methods\ndeclared outside of a class must be stored in a variable to be used.\n\n    my &m = method ($invocant: $arg1, $arg2) { note }\n\nThis syntax is unusual – typically, methods are declared inside a class.  In\nthis context, method declaration more closely resembles subroutine declaration:\nmethods are declared by the keyword C<method> followed by a name, followed by an\noptional signature, followed by a code block.  Methods defined inside a class,\nhave that class as their default invocant but can override that default (for\nexample, to L<constrain the invocant's\ndefiniteness|/language/signatures#Constraining_argument_definiteness>).\n\n    class Greeter {\n       method greet($to-whom)           { say \"Hello $to-whom!\" }\n       method defined-greet(Greeter:D:) { say \"Hello!\" }\n    }\n\nFor more details on methods, see L<Methods|/language/classtut#Methods>.\n\n=head4 Multiple-dispatch method declaration\n\nInside of a class, you can declare multiple-dispatch methods with syntax that's\nvery similar to the syntax for multiple-dispatch subroutines.  As with C<multi>\nsubroutines, you can also declare a C<proto> for multiple-dispatch methods.\n\n\n    class Greeter {\n          multi method greet           { say \"Hello!\" }\n          multi method greet($to-whom) { say \"Hello $to-whom!\" }\n\n          proto method at-least1($, |)   {*}\n          multi method at-least1($first) { note $first }\n          # The following is legal to *declare* but can never be called\n          multi method at-least1         { note \"Got none\"}\n    }\n\n=head3 X<C<package>, C<module>, C<class>, C<role>, and C<grammar> declaration|Syntax,unit>\n\nX<|Syntax,module>\nX<|Syntax,package>\nThere are several types of package, each declared with a keyword, a\nname, some optional traits, and a body of subroutines, methods, or\nrules.\n\n    package P { }\n\n    module M { }\n\n    class C { }\n\n    role R { }\n\n    grammar G { }\n\nSeveral packages may be declared in a single file. However, you can declare\na C<unit> package at the start of the file, and the rest of the file will be\ntaken as being the body of the package. In this case, the curly braces are not\nrequired.\n\n=begin code :solo\nunit module M;\n# ... stuff goes here instead of in {}'s\n=end code\n\n\n=head1 Invoking code objects\n\nRaku provides standard syntax for invoking subroutines/blocks and for invoking\nmethods.  Additionally, Raku provides alternate syntax to invoke subroutines\nwith method-like syntax and to invoke methods with subroutine-like syntax\n\n=head2 Invoking subroutines or blocks\n\nLexically declared subroutines and subroutine/blocks assigned to C<&>-sigiled\nvariables can be invoked by their name followed by their arguments (optionally\nenclosed in C<(…)>).  Alternatively, their name may be preceded by the C<&>\nsigil but, in that case, the C<(…)> surrounding the function's arguments is\nmandatory but may be preceded by an optional C<.>. (An C<&>-sigiled variable\nwithout C<(…)> refers to the function as an object – that is, without invoking\nit). Thus, all of the following call the function C<foo> with no arguments:\n\n\n    =begin code :preamble<sub foo {};>\n    foo;\n    foo();\n    &foo();\n    &foo.();\n    =end code\n\nIf a subroutine or block is assigned to a C<$>-sigiled variable, then it can\nB<only> be invoked using parentheses:\n\n    my $foo = sub { note }\n    $foo();\n    $foo.();\n\nFor more information on invoking subroutines/blocks, see L<functions|/language/functions>.\n\n=head2 Invoking methods\n\nA method defined in a class is invoked on an instance of that class by\nreferring to the class followed by a C<.> followed by the method name.  Invoking\nthe method without arguments doesn't require parentheses.  To supply arguments,\nyou must either surround them in C<(…)> or follow the method name with a C<:>.\nThe following code shows the syntax described above:\n\n=begin code\nclass Person {\n    has $.age = 0;\n    has Str $.name = \"Anon\";\n\n    multi method greet        { say \"Hello, $.name()!\" }\n    multi method greet($name) { say \"Hello, $name!\" }\n};\nmy $person = Person.new(:name<Jane>, :age(98));\n\n$person.greet;   # Calls greet method with 0 args\n$person.greet(); # Calls greet method with 0 args\n$person.greet('Nushi'); # Calls greet method with 1 arg\n$person.greet: 'Nushi'; # Calls greet method with 1 arg\n=end code\n\n=head3 Invoking methods with : (precedence drop)\n\nNote that the syntax in the final line results in the method treating the\nremainder of the statement as its argument list.  (Or, said differently, it\ndrops the precedence of the method call; for that reason, the C<:> used here is\nsometimes called the \"precedence drop\").  The following code illustrates the\nconsequences of that change:\n\n\n=begin code\nmy $band = 'Foo Fighters';\nsay $band.substr( 0, 3 ).uc; # OUTPUT: «FOO␤»\nsay $band.substr: 0, 3  .uc; # OUTPUT: «Foo␤»\n\n=end code\n\nThe final line isn't equivalent to the one above it; instead, it's the same as\nC<$band.substr(0, 3.uc)> – likely not what was intended here.  That's because in\nthe second method call the C<uc> method is called on \"3\" and not to the result\nof the leftmost C<substr>; in other words, the C<substr> method yields\nprecedence to the C<uc> method.\n\n=head3 Invoking methods on the topic\n\nIf a method is called without an invocant (that is, with nothing to the left of\nthe C<.>), then it will use the current L<topic\nvariable|/language/variables#The_$__variable> as its invocant.  For example:\n\n    given 'Foo Fighters' {\n       say .substr: 0, 3;  # OUTPUT: «Foo␤»\n    }\n\n\n=head2 Method-like function calls & function-like method calls\n\nSubroutines can be invoked with method-like syntax – that is, you can call a\nfunction on an object followed by a dot in much the same way that you can call a\nmethod (including by optionally using a C<:>).  The only limitation is that you\nI<must> precede the function name with an C<&>.  For example:\n\n    sub greet($name, :$excited = True) {\n        say \"Hello $name\" ~ ($excited ?? '!' !! '.')\n    }\n    greet \"Maria\";    # OUTPUT: «Hello Maria!␤»\n    \"Maria\".&greet;   # OUTPUT: «Hello Maria!␤»\n    \"Maria\".&greet(); # OUTPUT: «Hello Maria!␤»\n    given \"Maria\" { .&greet } # OUTPUT: «Hello Maria!␤»\n\n    \"Maria\".&greet(:!excited); # OUTPUT: «Hello Maria.␤»\n    \"Maria\".&greet: :!excited; # OUTPUT: «Hello Maria.␤»\n\nSimilarly, methods may be invoked with function-like syntax – that is, you can\ncall a method by providing the method name first followed by the method's\narguments (including its invocant).  To do so, simply supply the invocant as the\nfirst argument followed by a C<:>.\n\n    class Person {\n        has Str $.name;\n\n        multi method greet        { say \"Hello, $.name()!\" }\n        multi method greet($name) { say \"Hello, $name!\" }\n    };\n    my $person = Person.new(:name<Ruòxī>, :age(11));\n\n    greet $person:;         # same as $person.greet;\n    greet Person: 'Yasmin'; # same as Person.greet('Yasmin');\n\nDue to the presence of method-like function syntax and function-like method\nsyntax, it is especially important to be clear on whether a given syntactic form\ncalls a method or a subroutine.  This detail can be easy to neglect, especially\nbecause in many cases Raku provides a method and a subroutine of the same name.\n\nFor instance, the following simple example produces the same output for both\nfunction and method calls.\n\n    say 42;  # Subroutine call\n    42.&say; # Still a subroutine call\n    42.say;  # Method call\n    say 42:; # Also a method call\n\nHowever, even when both a subroutine and a method exist, calling the correct one\ncan make a large difference.  To see this in action, consider C<map>, which\nexists as both a subroutine and a method but where the method expects its\narguments in a different order:\n\n    my @list = 1..9;\n    sub add1($a) { $a + 1 }\n\n    map &add1, @list; # Sub call; expects list last\n    map @list: &add1; # Method call; expects function last\n\n    @list.map(&add1);  # Method call; expects function last\n    &add1.&map(@list); # Sub call; expects list last\n\n\n\n=head1 Operators\n\nSee L<Operators|/language/operators> for lots of details.\n\nOperators are functions with a more symbol heavy and composable syntax.\nLike other functions, operators can be multi-dispatch to allow for\ncontext-specific usage.\n\nThere are five types (arrangements) for operators, each taking either\none or two arguments.\n\n    =begin code :skip-test<showcasing syntaxes>\n    ++$x           # prefix, operator comes before single input\n    5 + 3          # infix, operator is between two inputs\n    $x++           # postfix, operator is after single input\n    <the blue sky> # circumfix, operator surrounds single input\n    %foo<bar>      # postcircumfix, operator comes after first input and surrounds second\n    =end code\n\n=head2 Metaoperators\n\nOperators can be composed. A common example of this is combining an\ninfix (binary) operator with assignment. You can combine assignment with\nany binary operator.\n\n=begin code :skip-test<showcasing syntaxes>\n$x += 5     # Adds 5 to $x, same as $x = $x + 5\n$x min= 3   # Sets $x to the smaller of $x and 3, same as $x = $x min 3\n$x .= child # Equivalent to $x = $x.child\n=end code\n\nWrap an infix operator in C<[ ]> to create a new reduction operator that works\non a single list of inputs, resulting in a single value.\n\n    say [+] <1 2 3 4 5>;    # OUTPUT: «15␤»\n    (((1 + 2) + 3) + 4) + 5 # equivalent expanded version\n\nWrap an infix operator in C<« »> (or the ASCII equivalent C«<< >>») to\ncreate a new hyper operator that works pairwise on two lists.\n\n    say <1 2 3> «+» <4 5 6> # OUTPUT: «(5 7 9)␤»\n\nThe direction of the arrows indicates what to do when the lists are not the same\nsize.\n\n=begin code :skip-test<showcasing syntaxes>\n@a «+« @b # Result is the size of @b, elements from @a will be re-used\n@a »+» @b # Result is the size of @a, elements from @b will be re-used\n@a «+» @b # Result is the size of the biggest input, the smaller one is re-used\n@a »+« @b # Exception if @a and @b are different sizes\n=end code\n\nYou can also wrap a unary operator with a hyper operator.\n\n    say -« <1 2 3> # OUTPUT: «(-1 -2 -3)␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Language/system.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE System interaction\n\n=SUBTITLE Working with the underlying operating system and running applications\n\n=head1 Getting arguments through the command line\n\nThe simplest way is to use the\nL<C<@*ARGS>|/language/variables#%40%2AARGS> variable to obtain\narguments from the command line; this array will contain the strings that follow\nthe program name. L<C<%*ENV>|/language/variables#Runtime_environment> will\ncontain the environment variables, so that if you use:\n\n=begin code :lang<shell>\nexport API_KEY=1967196417966160761fabc1511067\n./consume_api.raku\n=end code\n\nYou can use them from your program this way:\n\n    my $api-key = %*ENV<API_KEY> // die \"Need the API key\";\n\nThis will fail if the environment variable C<API_KEY> has not been defined\npreviously.\n\nRaku has a better way to deal with command line arguments if they represent\nfile names: the L<C<$*ARGFILES>|/language/variables#%24%2AARGFILES>\ndynamic variable.\n\n=begin code\nfor $*ARGFILES.lines -> $l {\n    say \"Long lines in {$*ARGFILES.path}\"\n        if $l.chars > 72 ;\n}\n=end code\n\nYou can run this program this way C<argfiles.raku *.raku>, for instance, and it will\nprint a file name every time it finds a line longer than 72 characters.\nC<$*ARGFILES> contains filehandles of all files described in the command lines-\nC<.lines> will read in turn one line from every one of them, changing the value\nof C<$*ARGFILES.path> every time a new handle is being processed. In general, it\nprovides a very convenient API for scripts that deal with sets of files.\n\n=head1 Getting arguments interactively\n\nUse C<prompt> to have a running program query the user for data:\n\n=begin code\nmy UInt $num-iters = prompt \"How many iterations to run: \";\n=end code\n\n=head1 Running programs synchronously and asynchronously\n\nThere are two routines to run external programs: L<C<run>|/routine/run> and\nL<C<shell>|/routine/shell>. Both exist in the L<C<IO>|/type/IO> role and are\nthus included in all classes that mix that role in, like L<C<IO::Path>|/type/IO::Path>. Both\nreturn a L<C<Proc>|/type/Proc> object, but the main difference is that C<run> will\ntry to avoid the system shell, if possible, while C<shell> will run the command\nthrough the default system shell.\n\nThe key class for running all external programs is L<C<Proc::Async>|/type/Proc::Async>, which runs\nprocesses asynchronously and allows\nL<concurrent|/language/concurrency#Proc::Async> interaction with the\nrunning processes. In general, it is a good practice to interact with the system\nthrough these high-level, abstract interfaces. However, Raku provides with\nother ways of interacting with the system through a low-level interface.\n\n=head1 Making operating system calls through the native API\n\nThe L<C<NativeCall>|/language/nativecall> API can be used to interact with\nsystem libraries, as well as any other accessible library. This\nL<short tutorial|/language/nativecall#Short_tutorial_on_calling_a_C_function>\nexplains, for instance, how to call system functions such as C<getaddrinfo>\nusing that interface; some other functions like C<kill> can also be L<accessed\nthat way, via declaration using the NativeCall\ninterface|/language/perl-func#kill>.\n\nFortunately, you do not have to do that for all native functions. As part of her\nButterfly project porting Perl functions to Raku as part of the ecosystem,\nL<Elizabeth Mattijsen|https://github.com/lizmat> is porting many system\nfunctions that were part of that language to modules such as\nL<C<P5getprotobyname>|https://github.com/lizmat/P5getprotobyname>, which\nincludes functions such as C<endprotoent>, C<getprotoent>, C<getprotobyname>,\nC<getprotobynumber> and C<setprotoent>.\nL<Search and install C<P5> modules|https://raku.land/zef:lizmat/P5built-ins>\nif you want to use those functions already in Raku.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/tables.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"reference\")\n\n=TITLE Pod6 tables\n\n=SUBTITLE Valid, invalid, and unexpected tables\n\nThe official specification for Pod6 tables is located in the\nDocumentation specification here:\nL<Tables|https://raw.githubusercontent.com/perl6/specs/master/S26-documentation.pod>.\nAlthough Pod6 specifications are not completely and properly handled yet,\nseveral projects are ongoing to correct the situation; one such\nproject is ensuring the proper handling of Pod6 tables.\n\nAs part of that effort, this document explains the current state of\nPod6 tables by example: valid tables, invalid tables, and unexpected tables\n(i.e., valid tables that, because of sloppy construction, may result\nin something different than the user expects).\n\n=head1 Restrictions\n\n1. The only valid column separators are either visible (V<' | '> or V<' + '>)\n(note at least one space is required before and after the visible column\nseparators) or invisible [two or more contiguous whitespace (WS)\ncharacters (e.g., V<'  '>)]. Column separators are not normally recognized\nas such at the left or right side of a table, but one on the right side may\nresult in one or more empty cells depending upon the number of the cells in\nother rows. (Note that a pipe or plus character meant as part of cell\ndata will result in an unintended extra column unless the character is escaped\nwith a backslash, e.g., '\\|' or '\\+'.)\n\n2. Mixing visible and invisible column separators in the same table is\nillegal.\n\n3. The only valid row separator characters are V<'_'>, V<'-'>, V<'+'>, V<' '>,\nV<'|'>, and V<'='>.\n\n4. Consecutive interior row-separator lines are illegal.\n\n5. Leading and trailing row-separator lines generate a warning.\n\n6. Formatting blocks in table cells are currently ignored and treated as\nplain text.\n\nHINT: During development, use of the environment variable C<RAKUDO_POD6_TABLE_DEBUG>\nwill show you how Rakudo interprets your Pod tables before they are passed\nto renderers such as C<Pod::To::HTML>, C<Pod::To::Text>, and\nC<Pod::To::Markdown>.\n\n=head1 Best practices\n\nHINT: Not adhering to the following best practices may require more table\nprocessing due to additional looping over table rows.\n\n1. Use of WS for column separators is fragile, and they should only be\nused for simple tables. The C<Ugly Tables> section below illustrates\nthe problem.\n\n2. Align table columns and rows carefully. See the examples in later\nbest practices.\n\n3. Don't use visual borders on the table.\n\n4. For tables with a heading and single- or multi-line content, use\none or more contiguous equal signs (V<'='>) as the row separator after\nthe heading, and use one or more contiguous hyphens (V<'-'>) as the row\nseparator in the content portion of the table.  For example,\n\n=item Heading and single- or multi-line content\n\n=begin code\n=begin table\n hdr col 0 | hdr col 1\n ======================\n row 0     | row 0\n col 0     | col 1\n ----------------------\n row 1     | row 1\n col 0     | col 1\n ----------------------\n=end table\n=end code\n\n=item Heading and single-line content\n\n=begin code\n=begin table\n hdr col 0   | hdr col 1\n ======================\n row 0 col 0 | row 0 col 1\n row 1 col 0 | row 1 col 1\n=end table\n=end code\n\n5. For tables with no header and multi-line content, use one or more\ncontiguous hyphens (V<'-'>) as the row separator in the content portion\nof the table.  For example,\n\n=begin code\n=begin table\n row 0       | row 0\n col 0       | col 1\n ----------------------\n row 1 col 0 | row 1 col 1\n=end table\n=end code\n\n6. For tables with many rows and no multi-line content, using no row\nseparators is fine. However, with one or more rows with multi-line\ncontent, it is easier to ensure proper results by using a row\nseparator line (visible or invisible) between every content row.\n\n7. Ensure intentionally empty cells have column separators, otherwise\nexpect a warning about short rows being filled with empty cells.\n(Tables rows will always have the same number of cells as the\nrow with the most cells. Short rows are padded on the right with\nempty cells and generate a warning.)\n\n8. Adding a caption to a table is possible using the C<=begin table>\nline as in this example:\n\n=begin code\n=begin table :caption<My Tasks>\nmow lawn\ntake out trash\n=end table\n=end code\n\nAlthough not a good practice, currently there is in use an alternate\nmethod of defining a caption as shown in this example:\n\n=begin code\n=begin table :config{caption => \"My Tasks\"}\nmow lawn\ntake out trash\n=end table\n=end code\n\nNote the alternative method of putting the caption in the C<config> hash\nwas necessary before the C<:caption> method was implemented, but that\nmethod is now considered to be deprecated. The practice will generate a\nwarning in the upcoming version C<6.d>, and it will raise an exception in\nversion C<6.e>.\n\n=head1 Valid tables\n\nFollowing are examples of valid tables (taken from the current\nL<Specification Tests|https://github.com/Raku/roast>).\n\n=begin code\n=begin table\n        The Shoveller   Eddie Stevens     King Arthur's singing shovel\n        Blue Raja       Geoffrey Smith    Master of cutlery\n        Mr Furious      Roy Orson         Ticking time bomb of fury\n        The Bowler      Carol Pinnsler    Haunted bowling ball\n=end table\n=end code\n\n=begin code\n=table\n    Constants           1\n    Variables           10\n    Subroutines         33\n    Everything else     57\n=end code\n\n=begin code\n=for table\n    mouse    | mice\n    horse    | horses\n    elephant | elephants\n=end code\n\n=begin code\n=table\n    Animal | Legs |    Eats\n    =======================\n    Zebra  +   4  + Cookies\n    Human  +   2  +   Pizza\n    Shark  +   0  +    Fish\n=end code\n\n=begin code\n=table\n        Superhero     | Secret          |\n                      | Identity        | Superpower\n        ==============|=================|================================\n        The Shoveller | Eddie Stevens   | King Arthur's singing shovel\n=end code\n\n=begin code\n=begin table\n\n                        Secret\n        Superhero       Identity          Superpower\n        =============   ===============   ===================\n        The Shoveller   Eddie Stevens     King Arthur's\n                                          singing shovel\n\n        Blue Raja       Geoffrey Smith    Master of cutlery\n\n        Mr Furious      Roy Orson         Ticking time bomb\n                                          of fury\n\n        The Bowler      Carol Pinnsler    Haunted bowling ball\n=end table\n=end code\n\n=begin code\n=table\n    X | O |\n   ---+---+---\n      | X | O\n   ---+---+---\n      |   | X\n=end code\n\n=begin code\n=table\n    X   O\n   ===========\n        X   O\n   ===========\n            X\n=end code\n\n=begin code\n=begin table\n\nfoo\nbar\n\n=end table\n=end code\n\n=head1 Invalid tables\n\nFollowing are examples of invalid tables, and they should\ntrigger an unhandled exception during parsing.\n\n=item Mixed column separator types in the same row are not allowed:\n\n=begin code\n=begin table\nr0c0 +  r0c1 | r0c3\n=end table\n=end code\n\n=item  Mixed visual and whitespace column separator types in the same table\nare not allowed:\n\n=begin code :skip-test<pod error>\n=begin table\nr0c0 +  r0c1 | r0c3\nr1c0    r0c1   r0c3\n=end table\n=end code\n\n=item Two consecutive interior row separators are not allowed:\n\n=begin code :skip-test<pod error>\n=begin table\nr0c0 |  r0c1\n============\n============\nr1c0 |  r1c1\n=end table\n=end code\n\n=head1 Unexpected tables\n\nFollowing are examples of valid tables that are probably intended to\nbe two columns, but the columns are not aligned well so each\nwill parse as a single-column table.\n\n=item  Unaligned columns with WS column separators:\n\nNotice the second row has the two words separated by only B<one> WS\ncharacter, while it takes at least B<two> adjacent WS characters to define\na column separation. B<This is a valid table but will be parsed as a\nsingle-column table>.\n\n=begin code\n=begin table\nr0c0    r0c1\n r1c0 r0c1\n=end table\n=end code\n\n=item  Unaligned columns with visual column separators:\n\nNotice the second row has the two words separated by a visible\ncharacter (V<'|'>) but the character is not recognized as a column\nseparator because it doesn't have an adjacent WS character on both\nsides of it.  Although this is a legal table, the result will not\nbe what the user intended because the first row has two\ncolumns while the second row has only one column, and it will thus have\nan empty second column.\n\n=begin code\n=begin table\nr0c0  |  r0c1\n r1c0 |r0c1\n=end table\n=end code\n\n=end pod\n"
  },
  {
    "path": "doc/Language/temporal.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Date and time functions\n\n=SUBTITLE Processing date and time in Raku\n\nRaku includes several classes that deal with temporal information: L<C<Date>|/type/Date>, L<C<DateTime>|/type/DateTime>, L<C<Instant>|/type/Instant> and L<C<Duration>|/type/Duration>. The first two are I<dateish>, so they mix in the L<C<Dateish>|/type/Dateish> role, which defines all methods and properties that classes that deal with date should assume. It also includes a class hierarchy of exceptions rooted in L<C<X::Temporal>|/type/X::Temporal>.\n\nWe will try to illustrate these classes in the next (somewhat extended) example, which can be used to process all files in a directory (by default C<.>) with a particular extension (by default C<.raku>) in a directory, sort them according to their age, and compute how many files have been created per month and how many were modified in certain periods expressed in ranges of months:\n\n=begin code\nsub MAIN( $path = \".\", $extension = \"raku\" ) {\n    my DateTime $right = DateTime.now;\n    my %metadata;\n    my %files-month;\n    my %files-period;\n    for dir($path).grep( / \\.$extension $/ ) -> $file {\n        CATCH {\n            when X::Temporal { say \"Date-related problem\", .payload }\n            when X::IO { say \"File-related problem\", .payload }\n            default { .payload.say }\n        }\n        my Instant $modified = $file.modified;\n        my Instant $accessed = $file.accessed;\n        my Duration $duration = $accessed - $modified;\n        my $age = $right - DateTime($accessed);\n        my $time-of-day = $file.changed.DateTime.hh-mm-ss but Dateish;\n        my $file-changed-date =  $file.changed.Date;\n        %metadata{$file} = %( modified => $modified,\n                              accessed => $accessed,\n                              age => $age,\n                              difference => $duration,\n                              changed-tod => $time-of-day,\n                              changed-date => $file-changed-date);\n        %files-month{$file-changed-date.month}++;\n        given $file-changed-date {\n            when Date.new(\"2018-01-01\")..^Date.new(\"2018-04-01\") { %files-period<pre-grant>++}\n            when Date.new(\"2018-04-01\")..Date.new(\"2018-05-31\") { %files-period<grant>++}\n            default { %files-period<post-grant>++};\n        }\n    }\n\n    %metadata.sort( { $^a.value<age> <=> $^b.value<age> } ).map: {\n        say $^x.key, \", \",\n        $^x.value<accessed modified age difference changed-tod changed-date>.join(\", \");\n    };\n    %files-month.keys.sort.map: {\n        say \"Month $^x → %files-month{$^x}\"\n    };\n\n    %files-period.keys.map: {\n        say \"Period $^x → %files-period{$^x}\"\n    };\n}\n=end code\n\nL<C<DateTime>|/type/DateTime> is used in line 2 to contain the current date and time returned by L<C<now>|/routine/now>.\n\nA CATCH phaser is declared in lines 7 to 11. Its main mission is to distinguish between L<C<DateTime>|/type/DateTime>-related exceptions and other types. These kinds of exception can arise from L<invalid formats|/type/X::Temporal::InvalidFormat> or L<timezone clashes|/type/X::DateTime::TimezoneClash>. Barring some corruption of the file attributes, both are impossible, but in any case they should be caught and separated from other types of exceptions.\n\nWe use L<C<Instant>|/type/Instant>s in lines 12-13 to represent the moment in which the files where accessed and modified. An Instant is measured in atomic seconds and is a very low-level description of a time event; however, the L<C<Duration>|/type/Duration> declared in line 14 represents the time transcurred among two different L<C<Instant>|/type/Instant>s and we will be using it to represent the age.\n\nFor some variables, we might be interested in dealing with them with some I<dateish> traits. C<$time-of-day> contains the time of the day the file was changed; C<changed> will return an Instant, but it is converted into a Date (which is L<C<Dateish>|/type/Dateish> while L<C<Instant>|/type/Instant> is not) and then the time of day is extracted from that. C<$time-of-day> will have C<«Str+{Dateish}␤»> type.\n\nX<|Language,Date ranges>\nWe will use the date in this variable to find out the period when the files were changed.\n\n    Date.new(\"2018-01-01\")..^Date.new(\"2018-04-01\")\n\ncreates a date L<C<Range>|/type/Range> and C<$file-changed-date> is smartmatched against it. Dates can be used this way; in this case it creates a L<C<Range>|/type/Range> that excludes its last element.\n\nThis very variable is also used to compute the month of the year when the file was modified. L<C<Date>|/type/Date> is obviously L<C<Dateish>|/type/Dateish> and then has the C<month> method to extract that property from it.\n\nL<C<Duration>|/type/Duration> objects can be compared. This is used in\n\n=for code :preamble<my %metadata>\n%metadata.sort({\n    $^a.value<age> <=> $^b.value<age>\n});\n\nto sort the files by age.\n\n\n=end pod\n"
  },
  {
    "path": "doc/Language/terms.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"reference\")\n\n=TITLE Terms\n\n=SUBTITLE Raku terms\n\nMost syntactic constructs in Raku can be categorized in I<terms> and\nL<operators|/language/operators>.\n\nHere you can find an overview of different kinds of terms.\n\n=head1 Literals\n\n=head2 Int\n\n=begin code :skip-test<literals only>\n42\n12_300_00\n:16<DEAD_BEEF>\n=end code\n\nL<C<Int>|/type/Int> literals consist of digits and can contain underscores\nbetween any two digits.\n\nTo specify a base other than ten, use the colonpair form C«:radix<number>».\n\n=head2 Rat\n\n    =begin code :skip-test<literals only>\n    12.34\n    1_200.345_678\n    =end code\n\nL<C<Rat>|/type/Rat> literals (rational numbers) contain two integer parts joined by\na dot.\n\nNote that trailing dots are not allowed, so you have to write C<1.0> instead\nof C<1.> (this rule is important because there are infix operators starting\nwith a dot, for example the C<..> L<C<Range>|/type/Range> operator).\n\n=head2 Num\n\n=begin code :skip-test<literals only>\n12.3e-32\n3e8\n=end code\n\nL<C<Num>|/type/Num> literals (floating point numbers) consist of L<C<Rat>|/type/Rat>\nor L<C<Int>|/type/Int> literals followed by an C<e> and a (possibly negative)\nexponent. C<3e8> constructs a L<C<Num>|/type/Num> with value C<3 * 10**8>.\n\n=head2 Str\n\n=begin code :skip-test<literals only>\n'a string'\n'I\\'m escaped!'\n\"I don't need to be\"\n\"\\\"But I still can be,\\\" he said.\"\nq|Other delimiters can be used too!|\n=end code\n\nString literals are most often created with C<'> or C<\">, however strings are\nactually a powerful sub-language of Raku. See\nL<Quoting Constructs|/language/quoting>.\n\n=head2 Regex\n\n=begin code :skip-test<literals only>\n/ match some text /\nrx/slurp \\s rest (.*) $/\n=end code\n\nThese forms produce regex literals. See L<quoting constructs|/language/quoting>.\n\n=head2 Pair\n\n    =begin code :skip-test<literals only>\n    a => 1\n    'a' => 'b'\n    :identifier\n    :!identifier\n    :identifier<value>\n    :identifier<value1 value2>\n    :identifier($value)\n    :identifier['val1', 'val2']\n    :identifier{key1 => 'val1', key2 => 'value2'}\n    :valueidentifier\n    :$item\n    :@array\n    :%hash\n    :&callable\n    =end code\n\nL<C<Pair>|/type/Pair> objects can be created either with the\nL«C<<=>>> infix operator|/language/operators#infix_=>» (which\nauto-quotes the left-hand side if it is an identifier), or with the various\ncolon-pair forms. Those almost always start with a colon and then are followed\neither by an identifier or the name of an already existing variable (whose\nname without the sigil is used as the key and value of the variable is used\nas the value of the pair). There is a special form where an integer value\nis immediately after the colon and the key is immediately after the value.\n\nIn the identifier form of a colon-pair, the optional value can be any\ncircumfix.  If it is left blank, the value is C<Bool::True>. The value of\nthe C<:!identifier> form is C<Bool::False>.\n\nIf used in an argument list, all of these forms count as named arguments,\nwith the exception of C«'quoted string' => $value».\n\n=head2 List\n\n    =begin code :skip-test<literals only>\n    ()\n    1, 2, 3\n    <a b c>\n    «a b c»\n    qw/a b c/\n    =end code\n\nL<C<List>|/type/List> literals are: the empty pair of parentheses C<()>, a\ncomma-separated list, or several quoting constructs.\n\n=head2 C<*>\n\nThe C<*> literal creates an object of type L<C<Whatever>|/type/Whatever>. See\nL<C<Whatever>|/type/Whatever> documentation for more details; when used as a\nterm, the expression it's included will become a\nL<C<WhateverCode>|/type/WhateverCode>\n\n=for code\nsay .^name with *;    # OUTPUT: «Whatever␤»\nsay .^name with *+3;  # OUTPUT: «WhateverCode␤»\n\n=head1 Identifier terms\n\nThere are built-in identifier terms in Raku, which are listed below.  In\naddition one can add new identifier terms with the syntax:\n\n    sub term:<forty-two> { 42 };\n    say forty-two\n\nor as constants:\n\n    constant forty-two = 42;\n    say forty-two;\n\n=head2 term self\n\nInside a method, C<self> refers to the invocant (i.e. the object the method\nwas called on). If used in a context where it doesn't make sense, a\ncompile-time exception of type L<C<X::Syntax::NoSelf>|/type/X::Syntax::NoSelf> is thrown.\n\n=head2 term now\n\nReturns an L<C<Instant>|/type/Instant> object representing the current time. It\nincludes L<leap seconds|https://en.wikipedia.org/wiki/Leap_second> and as such is a\nfew dozen seconds larger than L<time|/language/terms#term_time>:\n\n    say (now - time).Int; # OUTPUT: «37␤»\n\n=head2 term time\n\nReturns the current POSIX time in B<seconds> as an L<C<Int>|/type/Int>; see\nL<nano|/language/terms#term_nano> for more precision. See\nL<now|/language/terms#term_now> for high-resolution timestamp that includes\nL<leap seconds|https://en.wikipedia.org/wiki/Leap_second>.\n\n=head2 term nano\n\nReturns the current POSIX time in B<nano seconds> as an L<C<Int>|/type/Int>.\nSee L<now|/language/terms#term_now> for high-resolution timestamp that\nincludes L<leap seconds|https://en.wikipedia.org/wiki/Leap_second>.\n\nAvailable as of 6.e language version (early implementation exists in Rakudo\ncompiler 2022.12+).  For Rakudo releases from 2021.04, the\nL<nano|https://raku.land/zef:lizmat/nano> module can be used to obtain the\nsame functionality.\n\n=head2 term rand\n\nReturns a pseudo-random L<C<Num>|/type/Num> in the range C<0..^1>.\n\n=head2 term π\n\nReturns the number C<π> at codepoint U+03C0 (GREEK SMALL LETTER PI), i.e.\nthe ratio between circumference and diameter of a circle. The ASCII equivalent\nof C<π> is C<pi>.\n\n=head2 term pi\n\nReturns the number C<π>, i.e., the ratio between circumference and diameter\nof a circle. C<pi> is the ASCII equivalent of C<π>.\n\n=head2 term τ\n\nReturns the number C<τ> at codepoint U+03C4 (GREEK SMALL LETTER TAU), i.e.\nthe ratio between circumference and radius of a circle. The ASCII equivalent\nof C<τ> is C<tau>.\n\n=head2 term tau\n\nReturns the number C<τ>, i.e.  the ratio between circumference and radius of\na circle. C<tau> is the ASCII equivalent of C<τ>.\n\n=head2 term 𝑒\n\nReturns Euler's number at codepoint U+1D452 (MATHEMATICAL ITALIC SMALL E).\nThe ASCII equivalent of C<𝑒> is C<e>.\n\n=head2 term e\n\nReturns Euler's number.  C<e> is the ASCII equivalent of C<𝑒>.\n\n=head2 term i\n\nReturns the imaginary unit (for L<C<Complex>|/type/Complex> numbers).\n\n=head2 term ∅\n\nX<|Terms,∅>\n\nReturns C<set()>, aka the X<empty set|Terms,empty set>, at codepoint U+2205 (EMPTY SET).\n\n=head1 Variables\n\nVariables are discussed in the L<variable language docs|/language/variables>.\n\nX<|Syntax,constant (Terms)>\n=head1 Constants\n\nConstants are similar to L<variables|/language/variables> without a\nL<container|/language/containers>, and thus cannot be rebound. However,\ntheir initializers are evaluated at L<BEGIN|/syntax/BEGIN> time:\n\n    constant speed-of-light = 299792458; # m/s\n    constant @foo  = 1, 2, 3;\n    constant &talk = &say;\n    talk speed-of-light²; # OUTPUT: «89875517873681764␤»\n    talk @foo;            # OUTPUT: «(1 2 3)␤»\n\nCompile-time evaluation means\nL<you should be careful|/language/traps#Constants_are_computed_at_compile_time>\nwith using constants\ninside modules, which get automatically precompiled, and so the value\nof the constant would not change even between multiple executions of the\nprogram:\n\n=begin code :solo\n# Foo.rakumod\nunit module Foo;\nconstant comp-time = DateTime.now;\n=end code\n\n=begin code :lang<shell>\n# The value of the constant remains the same even though our script\n# is executed multiple times:\n$ raku -I. -MFoo -e 'say Foo::comp-time'\n2018-06-17T18:18:50.021484-04:00\n$ raku -I. -MFoo -e 'say Foo::comp-time'\n2018-06-17T18:18:50.021484-04:00\n=end code\n\nConstants are declared with keyword C<constant> followed by\nan L<identifier|/language/syntax#Identifiers> with an I<optional> sigil.\nConstants are L«C<our> scoped|/language/variables#The_our_declarator»\nby default.\n\n=begin code\n    constant foo  = 42;\nmy  constant $baz = rand;\nour constant @foo = 1, 2, 3;\n    constant %bar = %(:42foo, :100bar);\n=end code\n\nI<NOTE: if you're using the Rakudo compiler, you need release 2018.08 or\nnewer for type constraints and auto-coercion on constants to be\navailable. Auto-coercion on %-sigiled constants requires 6.d>.\n\nAn optional type constraint can be used, in which case the use of scope\ndeclarator is required:\n\n=begin code :skip-test<illustrates error>\n# !!WRONG!! missing scope declarator before type:\nInt constant bar = 42;\n\n# RIGHT:\nour Int constant bar = 42;\n=end code\n\nUnlike L<variables|/language/variables>, you cannot parameterize C<@>-,\nC<%>-, and C<&>-sigiled constants by specifying the parameterization\ntype in the declarator itself:\n\n=begin code :skip-test<illustrates error>\n# !!WRONG!! cannot parameterize @-sigiled constant with Int\n# This will throw X::ParametricConstant\nour Int constant @foo = 42;\n\n# OK: parameterized types as values are fine\nconstant @foo = Array[Int].new: 42;\n=end code\n\nThe reason for the restriction is that constants with C<@> and C<%>\nsigils default to L<C<List>|/type/List> and L<C<Map>|/type/Map> types, which cannot be\nparameterized. To keep things simple and consistent, parameterization\nwas simply disallowed in these constructs.\n\nThe C<@>-, C<%>-, and C<&>-sigiled constants specify implied typecheck of the\ngiven value for L<C<Positional>|/type/Positional>,\nL<C<Associative>|/type/Associative>, and L<C<Callable>|/type/Callable> roles\nrespectively. The C<@>-sigiled constants—and as of C<6.d> language version, the\nC<%>-sigiled constants as well—perform auto-coercion of the value if it does not\npass the implied typecheck. The C<@>-sigiled constants will coerce using method\nL<cache|/routine/cache> and C<%>-sigiled constants coerce using method\nL<C<Map>|/type/Map>.\n\n=begin code\nconstant @foo = 42;\n@foo.raku.say; # OUTPUT: «(42,)␤»\n\nconstant @bar = [<a b c>];\n@bar.raku.say; # OUTPUT: «[\"a\", \"b\", \"c\"]␤»\n\nconstant %foo = <foo bar>;\n%foo.raku.say; # OUTPUT: «Map.new((:foo(\"bar\")))␤»\n\nconstant %bar = {:10foo, :72bar};\n%bar.raku.say; # OUTPUT: «{:bar(72), :foo(10)}␤»\n\n# Pair is already Associative, so it remains a Pair\nconstant %baz = :72baz;\n%baz.raku.say; # OUTPUT: «:baz(72)␤»\n=end code\n\nFor convenience and consistency reasons, you can use the\nL«binding operator (C<:=>)|/routine/:=» instead of the assignment operator,\nuse backslash before sigilless name of the constant variable (same as with\nL<sigilless variables|/language/variables#Sigilless_variables>), and even\nomit the name of the constant entirely to have an anonymous constant. Since\nyou can't refer to anonymous entities, you may be better off using\na L«C<BEGIN> phaser|/language/phasers#BEGIN» instead, for clarity.\n\n    constant %foo := :{:42foo};\n    constant \\foo = 42;\n    constant = 'anon';\n\n=end pod\n"
  },
  {
    "path": "doc/Language/testing.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"reference\")\n\n=TITLE Testing\n\n=SUBTITLE Writing and running tests in Raku\n\n\nTesting code is an integral part of software development. Tests provide\nautomated, repeatable verifications of code behavior, and ensures your\ncode works as expected.\n\nIn Raku, the L<C<Test>|/type/Test> module provides a testing framework, used also\nby Raku's official spectest suite.\n\nThe testing functions emit output conforming to the\nL<Test Anything Protocol|https://testanything.org>. In general, they are used\nin sink context:\n\n=for code :preamble<use Test; my ($meta,$relaxed-name); sub check-name($meta,:$relaxed-name){}>\nok check-name($meta, :$relaxed-name), \"name has a hyphen rather than '::'\"\n\nbut all functions also return as a Boolean if the test has been successful or\nnot, which can be used to print a message if the test fails:\n\n=begin code :preamble<use Test; my ($meta,$relaxed-name); sub check-name($meta,:$relaxed-name){}>\nok check-name($meta, :$relaxed-name), \"name has a hyphen rather than '::'\" \\\n  or diag \"\\nTo use hyphen in name, pass :relaxed-name to check-name\\n\";\n=end code\n\n=head1 Writing tests\n\nAlthough it is possible to organize your tests differently, the typical\nRaku convention is for tests to live under the C<t> directory in the\nproject's base directory.\n\nA typical test file looks something like this:\n\n=begin code :solo :preamble<my $num-tests = 0>\nuse Test;      # a Standard module included with Rakudo\nuse lib 'lib';\n\nplan $num-tests;\n\n# .... tests\n\ndone-testing;  # optional with 'plan'\n=end code\n\nWe load the builtin L<C<Test>|/type/Test> module and specify where our other libraries are.\nWe then specify how\nmany tests we I<plan> to run (such that the testing framework can tell us if\nmore or fewer tests were run than we expected) and when finished with the\ntests, we use I<done-testing> to tell the framework we are done.\n\n=head2 Thread safety\n\nNote that routines in L<C<Test>|/type/Test> module are I<not> thread-safe. This means you\nshould not attempt to use the testing routines in multiple threads\nsimultaneously, as the L<TAP|https://testanything.org/> output might come out of\norder and confuse the program interpreting it.\n\nThere are no current plans to make it thread safe. If threaded-testing is\ncrucial to you, you may find some suitable\nL<ecosystem modules|https://raku.land/?q=Test> to use\ninstead of L<C<Test>|/type/Test> for your testing needs.\n\n=head1 Running tests\n\nTests can be run individually by specifying the test filename on the\ncommand line:\n\n=for code :lang<shell>\n$ raku t/test-filename.rakutest\n\nTo run all tests in the directory recursively,\nL<prove6|https://raku.land/zef:leont/App::Prove6> can be used.\n\nYou have to install it before using with zef:\n\n=for code :lang<shell>\n$ zef install App::Prove6\n\nYou can run C<prove6> in a distribution directory this way:\n\n=for code :lang<shell>\n$ prove6 --lib t/\n\nThe C<t/> argument specified directory that contains tests and the\nC<--lib> option is passed to include C<lib> directory into Raku\ndistribution path, it is an equivalent of C<-Ilib> argument of\nC<raku> command.\n\nFor more documentation regarding C<prove6> usage refer to\nL<its page|https://raku.land/zef:leont/App::Prove6>.\n\nTo abort the test suite upon first failure, set the\nC<RAKU_TEST_DIE_ON_FAIL> environment variable:\n\n=for code :lang<shell>\n$ RAKU_TEST_DIE_ON_FAIL=1 raku t/test-filename.rakutest\n\nThe same variable can be used within the test file. Set it before loading\nthe L<C<Test>|/type/Test> module:\n\n    BEGIN %*ENV<RAKU_TEST_DIE_ON_FAIL> = 1;\n    use Test;\n    ...\n\nB<Note:> Before Rakudo release 2020.05 the environment variable\nC<PERL6_TEST_DIE_ON_FAIL> was used to enable this feature, it is still\nsupported but deprecated.\n\nTest timing in microseconds can be emitted by setting the\nC<RAKU_TEST_TIMES> environment variable:\n\n=for code :lang<shell>\n$ env RAKU_TEST_TIMES=1 raku -e 'use Test; plan 1; pass sleep(1);'\n1..1\n# between two timestamps 0 microseconds\nok 1 -\n# t=1000721\n\nThe same variable can be used within the test file. Set it before loading\nthe L<C<Test>|/type/Test> module:\n\n=for code\nBEGIN %*ENV<RAKU_TEST_TIMES> = 1;\nuse Test;\n...\n\nB<Note:> Before Rakudo release 2020.05 the environment variable\nC<PERL6_TEST_TIMES> was used to enable this feature, it is still\nsupported but deprecated.\n\n=head1 Test plans\n\nTests plans use L<C<plan>|/type/Test#sub_plan> for declaring how many plans are\ngoing to be done or, as might be the case, skipped. If no plan is declared,\nL<C<done-testing>|/type/Test#sub_done-testing> is used to declare the end of the\ntests.\n\n=head1 Testing return values\n\nThe L<C<Test>|/type/Test> module exports various functions that check the return value of a\ngiven expression and produce standardized test output.\n\nIn practice, the expression will often be a call to a function or method that\nyou want to unit-test. L<C<ok>|/type/Test#sub_ok> and L<C<nok>|/type/Test#sub_nok> will\nmatch C<True> and C<False>. However, where possible it's better to use one of\nthe specialized comparison test functions below, because they can print more\nhelpful diagnostics output in case the comparison fails.\n\n=head2 By string comparison\n\nL<C<is>|/type/Test#sub_is> and L<C<isnt>|/type/Test#sub_isnt> test for equality using the\nproper operator, depending on the object (or class) it's handled.\n\n=head2 By approximate numeric comparison\n\nL<C<is-approx>|/type/Test#sub_is-approx> compares numbers with a certain precision,\nwhich can be absolute or relative. It can be useful for numeric values whose\nprecision will depend on the internal representation.\n\n=head2 By structural comparison\n\nStructures can be also compared using L<C<is-deeply>|/type/Test#sub_is-deeply>,\nwhich will check that internal structures of the objects compared is the same.\n\n=head2 By arbitrary comparison\n\nYou can use any kind of comparison with L<C<cmp-ok>|/type/Test#sub_cmp-ok>, which\ntakes as an argument the function or operator that you want to be used for\ncomparing.\n\n=head2 By object type\n\nL<C<isa-ok>|/type/Test#sub_isa-ok> tests whether an object is of a certain type.\n\n\n=head2 By method name\n\nL<C<can-ok>|/type/Test#sub_can-ok> is used on objects to check whether they have\nthat particular method.\n\n=head2 By role\n\nX<|Subroutines,does-ok>\nL<C<does-ok>|/type/Test#sub_does-ok> checks whether the given variable can do a\ncertain L<Role|/language/objects#Roles>.\n\n=head2 By regex\n\nL<C<like>|/type/Test#sub_like> and L<C<unlike>|/type/Test#sub_unlike> check using\nregular expressions; in the first case passes if a match exists, in the second\ncase when it does not.\n\n=head1 Testing modules\n\nModules are tentatively loaded with L<C<use-ok>|/type/Test#sub_use-ok>, which fails\nif they fail to load.\n\n=head1 Testing exceptions\n\nL<C<dies-ok>|/type/Test#sub_dies-ok> and L<C<lives-ok>|/type/Test#sub_lives-ok> are\nopposites ways of testing code; the first checks that it throws an exception,\nthe second that it does not; L<C<throws-like>|/type/Test#sub_throws-like> checks\nthat the code throws the specific exception it gets handed as an argument;\nL<C<fails-like>|/type/Test#sub_fails-like>, similarly, checks if the code returns a\nspecific type of L<C<Failure>|/type/Failure>. L<C<eval-dies-ok>|/type/Test#sub_eval-dies-ok> and\nL<C<eval-lives-ok>|/type/Test#sub_eval-lives-ok> work similarly on strings that are\nevaluated prior to testing.\n\n=head1 Testing intentional exits\n\nFor developers of Raku packages, it is sometimes useful to provide an intentional\nexit of the code path for a specific condition which can be indicated by a\nunique, numerical exit code in the POSIX range of 1-127. Such is provided by\ntest L<C<exits-ok>|/type/Test#sub_exits-ok>.\n\nNote it will be effective with the release of Rakudo 2026.01.\n\nIts use is demonstrated in the following subroutine:\n\n    sub apply-factor-to(Numeric $num --> Numeric) {\n        unless $num > 1 {\n            say \"FATAL: sub 'apply-factor-to' input is $num, it must be > 1\";\n            exit(3);\n        }\n        $num * 2.0;\n    }\n\nThat can be tested like this:\n\n=begin code :preamble<sub apply-factor-to {}>\nuse Test;\n\nexits-ok {\n    my $x = apply-factor-to -2;\n}, 3, \"got the expected signal 3 for invalid input\";\n=end code\n\n=head1 Grouping tests\n\nThe result of a group of subtests is only C<ok> if all subtests are C<ok>; they\nare grouped using L<C<subtest>|/type/Test#sub_subtest>.\n\n\n=head1 Skipping tests\n\nSometimes tests just aren't ready to be run, for instance a feature might not\nyet be implemented, in which case tests can be marked as\nL<C<todo>|/type/Test#sub_todo>. Or it could be the case that a given feature only\nworks on a particular platform - in which case one would\nL<C<skip>|/type/Test#sub_skip> the test on other platforms;\nL<C<skip-rest>|/type/Test#sub_skip-rest> will skip the remaining tests instead of a\nparticular number given as argument; L<C<bail-out>|/type/Test#sub_bail-out> will\nsimply exit the tests with a message.\n\n=head1 Manual control\n\nIf the convenience functionality documented above does not suit your needs, you\ncan use the following functions to manually direct the test harness output;\nL<C<pass>|/type/Test#sub_pass> will say a test has passed, and\nL<C<diag>|/type/Test#sub_diag> will print a (possibly) informative message.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/traits.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Traits\n\n=SUBTITLE Compile-time specification of behavior made easy\n\nIn Raku,  I<traits> are compiler hooks attached to objects and classes that\nmodify their default behavior, functionality or representation. As such compiler\nhooks, they are defined in compile time, although they can be used in runtime.\n\nSeveral traits are already defined as part of the language or the Rakudo\ncompiler by using the C<trait_mod> keyword. They are listed, and explained,\nnext.\n\n=head1 The X<C<is> trait|Traits,is (trait)>\n\n    proto trait_mod:<is>(Mu $, |) {*}\n\nC<is> applies to any kind of scalar object, and can take any number of named or\npositional arguments. It is the most commonly used trait, and takes the\nfollowing forms, depending on the type of the first argument.\n\n=head2 C<is> applied to classes.\n\nThe most common form, involving two classes, one that is being defined and the\nother existing, L<defines parenthood|/routine/is>. C<A is B>, if both are\nclasses, defines A as a subclass of B.\n\nL<C<is DEPRECATED>|/type/Attribute#trait_is_DEPRECATED> can be applied to\nclasses, Attributes or Routines, marks them as deprecated and issues a message,\nif provided.\n\nSeveral instances of C<is> are translated directly into attributes for the class\nthey refer to: C<rw>, C<nativesize>, C<ctype>, C<unsigned>, C<hidden>,\nC<array_type>.\n\nThe X<Uninstantiable representation trait|Traits,Uninstantiable representation trait> is not so much related to the\nrepresentation as related to what can be done with a specific class; it\neffectively prevents the creation of instances of the class in any\npossible way.\n\n=begin code\nconstant @IMM = <Innie Minnie Moe>;\n\nclass don't-instantiate is repr('Uninstantiable') {\n    my $.counter;\n\n    method imm () {\n        return @IMM[ $.counter++ mod @IMM.elems ];\n    }\n}\nsay don't-instantiate.imm for ^10;\n=end code\n\nUninstantiable classes can still be used via their class variables and\nmethods, as above. However, trying to instantiate them this way: C<my\n$do-instantiate = don't-instantiate.new;> will yield the error C<You\ncannot create an instance of this type (don't-instantiate)>.\n\n=head2 C<is repr> and native representations.\n\nSince the C<is> trait refers, in general, to the nature of the class or object\nthey are applied to, they are used extensively in\nL<native calls|/language/nativecall> to\nL<specify the representation|/language/nativecall#Specifying_the_native_representation>\nof the data structures that are going to be handled by the native functions via\nthe C<is repr> suffix; at the same time, C<is native> is used for the routines\nthat are actually implemented via native functions. These are the\nrepresentations that can be used:\n\n=item X<CStruct|Reference,CStruct> corresponds to a C<struct> in the C language. It is a\ncomposite data structure which includes different and heterogeneous\nlower-level data structures; see L<this|/language/nativecall#Structs>\nfor examples and further explanations.\n\n=item X<CPPStruct|Reference,CPPStruct>, similarly, correspond to a C<struct> in C++.\nHowever, this is Rakudo specific for the time being.\n\n=item X<CPointer|Reference,CPointer> is a pointer in any of these languages. It is a\ndynamic data structure that must be instantiated before being used, can\nbe L<used|/language/nativecall#Basic_use_of_pointers> for classes whose\nmethods are also native.\n\n=item X<CUnion|Reference,CUnion> is going to use the same representation as an C<union>\nin C; see L<this|/language/nativecall#CUnions> for an example.\n\nOn the other hand, X<P6opaque|Reference,P6opaque> is the default representation used for\nall objects in Raku.\n\n    class Thar {};\n    say Thar.REPR;    # OUTPUT: «P6opaque␤»\n\nThe L<metaobject protocol|/language/mop> uses it by default for every object\nand class unless specified otherwise; for that reason, it is in general not\nnecessary unless you are effectively working with that interface.\n\n\n=head2 C<is> on routines\n\nThe C<is> trait can be used on the definition of methods and routines to\nestablish L<precedence|/language/functions#Precedence> and\nL<associativity|/language/functions#Associativity>. They act as a L<sub defined\nusing C<trait_mod>|/type/Sub#Traits> which take as argument the types and names\nof the traits that are going to be added. In the case of subroutines, traits\nwould be a way of adding functionality which cuts across class and role\nhierarchies, or can even be used to add behaviors to independently defined\nroutines.\n\n=head2 X<C<is implementation-detail>|Traits,is implementation-detail> trait\n\nAvailable as of the 2020.05 release of the Rakudo compiler.\n\nThis trait is used by Raku language implementations and module authors\nto mark particular routines (including methods) as not meant to be a\npart of public API. While such routines can be found when looked up\ndirectly, they will not appear in results of introspection:\n\n    my &do-not-use-routine = CORE::<&DYNAMIC>;\n    say CORE::.keys.grep(* eq '&DYNAMIC'); # OUTPUT: «()␤»\n\nSuch routines are not meant for use by users and their behavior and availability can be changed\nanytime.\n\nAs of the 2021.02 release of the Rakudo compiler, it is also possible to\napply the C<is implementation-detail> method on classes and roles.\n\n=head3 method is-implementation-detail\n\n    method is-implementation-detail(--> True)\n\nApplying this trait makes the C<is-implementation-detail> method called on\nL<C<Code>|/type/Code> to return C<True>, thus giving a hint to the user not to use it\nif they are not willing to maintain this code in case of changes for years to come:\n\n    my &fail-routine = &fail;\n    unless &fail-routine.is-implementation-detail {\n        say \"&fail is not an implementation detail, can expect backward compatibility\";\n    }\n\n    sub PRIVATE-CALCULATION is implementation-detail { #`(Not safe to rely on this) }\n    if &PRIVATE-CALCULATION.is-implementation-detail {\n        say \"You better not to rely on &PRIVATE-CALCULATION unless you really know what you are doing\";\n    }\n\n=end pod\n"
  },
  {
    "path": "doc/Language/traps.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"reference\")\n\n=TITLE Traps to avoid\n\n=SUBTITLE Traps to avoid when getting started with Raku\n\nWhen learning a programming language, possibly with the background of\nbeing familiar with another programming language, there are always some\nthings that can surprise you and might cost valuable time in debugging\nand discovery.\n\nThis document aims to show common misconceptions in order to avoid them.\n\nDuring the making of Raku great pains were taken to get rid of warts\nin the syntax.  When you whack one wart, though, sometimes another pops\nup.  So a lot of time was spent finding the minimum number of warts or\ntrying to put them where they would rarely be seen.  Because of this,\nRaku's warts are in different places than you may expect them to be\nwhen coming from another language.\n\n=head1 Variables and constants\n\n=head2 Constants are computed at compile time\n\nConstants are computed at compile time, so if you use them in modules\nkeep in mind that their values will be frozen due to precompilation of\nthe module itself:\n\n=for code :skip-test\n# WRONG (most likely):\nunit module Something::Or::Other;\nconstant $config-file = \"config.txt\".IO.slurp;\n\nThe C<$config-file> will be slurped during precompilation and changes\nto C<config.txt> file won't be re-loaded when you start the script\nagain; only when the module is re-compiled.\n\nAvoid L<using a container|/language/containers> and prefer\nL<binding a value|/language/containers#Binding>\nto a variable that offers a\nbehavior similar to a constant, but allowing the value to get updated:\n\n=for code :solo\n# Good; file gets updated from 'config.txt' file on each script run:\nunit module Something::Or::Other;\nmy $config-file := \"config.txt\".IO.slurp;\n\n=head2 Assignment of L<C<Nil>|/type/Nil> can produce a different value, usually L<C<Any>|/type/Any>\n\nActually, assignment of L<C<Nil>|/type/Nil> to a variable\nL<reverts the variable to its default value|/type/Nil>. For example,\n\n=begin code\nmy @a = 4, 8, 15, 16;\n@a[2] = Nil;\nsay @a; # OUTPUT: «[4 8 (Any) 16]␤»\n=end code\n\nIn this case, L<C<Any>|/type/Any> is the default value of an L<C<Array>|/type/Array> element.\n\nYou can purposefully assign L<C<Nil>|/type/Nil> as a default value:\n\n=begin code\nmy %h is default(Nil) = a => Nil;\nsay %h; # OUTPUT: «Hash %h = {:a(Nil)}␤»\n=end code\n\nOr bind a value to L<C<Nil>|/type/Nil> if that is the result you want:\n\n=begin code :preamble<my @a = 1,2,3,4;>\n@a[3] := Nil;\nsay @a; # OUTPUT: «[4 8 (Any) Nil]␤»\n=end code\n\nThis trap might be hidden in the result of functions, such as matches:\n\n=begin code\nmy $result2 = 'abcdef' ~~ / dex /;\nsay \"Result2 is { $result2.^name }\"; # OUTPUT: «Result2 is Any␤»\n=end code\n\nA L<C<Match> will be C<Nil>|/language/regexes#Match_syntax>\nif it finds nothing; however assigning L<C<Nil>|/type/Nil> to C<$result2> above\nwill result in its default value, which is L<C<Any>|/type/Any> as shown.\n\n=head2 Using a block to interpolate anon state vars\n\nThe programmer intended for the code to count the number of times the\nroutine is called, but the counter is not increasing:\n\n    =begin code\n    sub count-it { say \"Count is {$++}\" }\n    count-it;\n    count-it;\n\n    # OUTPUT:\n    # Count is 0\n    # Count is 0\n    =end code\n\nWhen it comes to state variables, the block in which the vars are\ndeclared gets cloned —and vars get initialized anew— whenever that\nblock's block is re-entered. This lets constructs like the one below\nbehave appropriately; the state variable inside the loop gets\ninitialized anew each time the sub is called:\n\n    =begin code\n    sub count-it {\n        for ^3 {\n            state $count = 0;\n            say \"Count is $count\";\n            $count++;\n        }\n    }\n\n    count-it;\n    say \"…and again…\";\n    count-it;\n\n\n    # OUTPUT:\n    # Count is 0\n    # Count is 1\n    # Count is 2\n    # …and again…\n    # Count is 0\n    # Count is 1\n    # Count is 2\n    =end code\n\nThe same layout exists in our buggy program. The C<{ }> inside a\ndouble-quoted string isn't merely an interpolation to execute a piece of\ncode. It's actually its own block, which is just as in the example above\ngets cloned each time the sub is entered, re-initializing our state\nvariable. To get the right count, we need to get rid of that inner\nblock, using a scalar contextualizer to interpolate our piece of code\ninstead:\n\n    =begin code\n    sub count-it { say \"Count is $($++)\" }\n    count-it;\n    count-it;\n\n    # OUTPUT:\n    # Count is 0\n    # Count is 1\n    =end code\n\nAlternatively, you can also use the L<concatenation operator|/routine/~>\ninstead:\n\n    =begin code\n    sub count-it { say \"Count is \" ~ $++ }\n    =end code\n\n=head2 Using set subroutines on L<C<Associative>|/type/Associative> when the value is falsy\n\nUsing L<(cont)|/routine/(cont), infix ∋>, L<∋|/routine/(cont), infix ∋>, L<∌|/routine/∌>,\nL<(elem)|/routine/(elem), infix ∈>, L<∈|/routine/(elem), infix ∈>, or L<∉|/routine/∉> on classes\nimplementing L<C<Associative>|/type/Associative> will return C<False> if the value\nof the key is falsy:\n\n=begin code\nenum Foo «a b»;\nsay Foo.enums ∋ 'a';\n\n# OUTPUT:\n# False\n=end code\n\nInstead, use C<:exists>:\n\n=begin code\nenum Foo «a b»;\nsay Foo.enums<a>:exists;\n\n# OUTPUT:\n# True\n=end code\n\n=head1 Blocks\n\n=head2 Beware of empty \"blocks\"\n\nCurly braces are used to declare blocks. However, empty curly braces\nwill declare a hash.\n\n=begin code\n$ = {say 42;} # Block\n$ = {;}       # Block\n$ = {…}       # Block\n$ = { }       # Hash\n=end code\n\nYou can use the second form if you effectively want to declare an empty\nblock:\n\n    my &does-nothing = {;};\n    say does-nothing(33); # OUTPUT: «Nil␤»\n\n\n=head1 Objects\n\n=head2 Assigning to attributes\n\nNewcomers often think that, because attributes with accessors are\ndeclared as C<has $.x>, they can assign to C<$.x> inside the class.\nThat's not the case.\n\nFor example\n\n=begin code\nclass Point {\n    has $.x;\n    has $.y;\n    method double {\n        $.x *= 2;   # WRONG\n        $.y *= 2;   # WRONG\n        self;\n    }\n}\n\nsay Point.new(x => 1, y => -2).double.x\n# OUTPUT: «Cannot assign to an immutable value␤»\n=end code\n\nthe first line inside the method C<double> is marked with C<# WRONG> because\nC<$.x>, short for C<$( self.x )>, is a call to a read-only accessor.\n\nThe syntax C<has $.x> is short for something like C<has $!x; method x() {\n$!x }>, so the actual attribute is called C<$!x>, and a read-only accessor\nmethod is automatically generated.\n\nThus the correct way to write the method C<double> is\n\n=for code :preamble<has ($.x, $.y)>\nmethod double {\n    $!x *= 2;\n    $!y *= 2;\n    self;\n}\n\nwhich operates on the attributes directly.\n\n=head2 C<BUILD> prevents automatic attribute initialization from constructor\narguments\n\nWhen you define your own C<BUILD> submethod, you must take care of\ninitializing all attributes by yourself. For example\n\n=begin code\nclass A {\n    has $.x;\n    has $.y;\n    submethod BUILD {\n        $!y = 18;\n    }\n}\n\nsay A.new(x => 42).x;       # OUTPUT: «Any␤»\n=end code\n\nleaves C<$!x> uninitialized, because the custom C<BUILD> doesn't\ninitialize it.\n\nB<Note:> Consider using L<TWEAK|/language/objects#index-entry-TWEAK>\ninstead. L<Rakudo|/language/glossary#Rakudo> supports\nL<TWEAK|/language/objects#index-entry-TWEAK> method since release\n2016.11.\n\nOne possible remedy is to explicitly initialize the attribute in\nC<BUILD>:\n\n=for code :preamble<has ($.x, $.y)>\nsubmethod BUILD(:$x) {\n    $!y = 18;\n    $!x := $x;\n}\n\nwhich can be shortened to:\n\n=for code :preamble<has ($.x, $.y)>\nsubmethod BUILD(:$!x) {\n    $!y = 18;\n}\n\n=head1 Whitespace\n\n=head2 Whitespace in regexes does not match literally\n\n=for code\nsay 'a b' ~~ /a b/; # OUTPUT: «False␤»\n\nWhitespace in regexes is, by default, considered an optional filler without\nsemantics, just like in the rest of the Raku language.\n\nWays to match whitespace:\n\n=item C<\\s> to match any one whitespace, C<\\s+> to match at least one\n=item C<' '> (a blank in quotes) to match a single blank\n=item C<\\t>, C<\\n> for specific whitespace (tab, newline)\n=item C<\\h>, C<\\v> for horizontal, vertical whitespace\n=item C<<.ws>>, a built-in rule for whitespace that oftentimes does what\n      you actually want it to do\n=item with C<m:s/a b/> or C<m:sigspace/a b/>, the blank in the regexes\n      matches arbitrary whitespace\n\n=head2 Ambiguities in parsing\n\nWhile some languages will let you get away with removing as much whitespace\nbetween tokens as possible, Raku is less forgiving. The overarching\nmantra is we discourage code golf, so don't scrimp on whitespace (the\nmore serious underlying reason behind these restrictions is\nsingle-pass parsing and ability to parse Raku programs with virtually\nno L<backtracking|https://en.wikipedia.org/wiki/Backtracking>).\n\nThe common areas you should watch out for are:\n\n=head3 Block vs. Hash slice ambiguity\n\n=for code :skip-test<illustrates error>\n# WRONG; trying to hash-slice a Bool:\nwhile ($++ > 5){ .say }\n\n=begin code\n# RIGHT:\nwhile ($++ > 5) { .say }\n\n# EVEN BETTER; Raku does not require parentheses there:\nwhile $++ > 5 { .say }\n=end code\n\n=head3 Reduction vs. Array constructor ambiguity\n\n=for code :skip-test<illustrates error>\n# WRONG; ambiguity with `[<]` metaop:\nmy @a = [[<foo>],];\n\n=begin code\n# RIGHT; reductions cannot have spaces in them, so put one in:\nmy @a = [[ <foo>],];\n\n# No ambiguity here, natural spaces between items suffice to resolve it:\nmy @a = [[<foo bar ber>],];\n=end code\n\n=head3 Less than vs. Word quoting/Associative indexing\n=for code :skip-test<illustrates error>\n# WRONG; trying to index 3 associatively:\nsay 3<5>4\n\n=begin code\n# RIGHT; prefer some extra whitespace around infix operators:\nsay 3 < 5 > 4\n=end code\n\n=head3 Exclusive sequences vs. sequences with Ranges\n\nSee the section on L<operator traps|#Exclusive_sequence_operator> for\nmore information about how the C<...^> operator can be mistaken for\nthe C<...> operator with a C<^> operator immediately following it. You\nmust use whitespace correctly to indicate which interpretation will be\nfollowed.\n\n=head1 Captures\n\n=head2 Containers versus values in a capture\n\nBeginners might expect a variable in a L<C<Capture>|/type/Capture> to supply its current\nvalue when that L<C<Capture>|/type/Capture> is later used.  For example:\n\n=for code\nmy $a = 2; say join \",\", ($a, ++$a);  # OUTPUT: «3,3␤»\n\nHere the L<C<Capture>|/type/Capture> contained the B<container> pointed to by C<$a> and the\nB<value> of the result of the expression C<++$a>.  Since the L<C<Capture>|/type/Capture> must be\nreified before C<&say> can use it, the C<++$a> may happen before C<&say> looks\ninside the container in C<$a> (and before the L<C<List>|/type/List> is created with the two\nterms) and so it may already be incremented.\n\nInstead, use an expression that produces a value when you want a value.\n\n=for code\nmy $a = 2; say join \",\", (+$a, ++$a); # OUTPUT: «2,3␤»\n\nOr even simpler\n=for code\nmy $a = 2; say  \"$a, {++$a}\"; # OUTPUT: «2, 3␤»\n\nThe same happens in this case:\n=begin code\nmy @arr;\nmy ($a, $b) = (1,1);\nfor ^5 {\n    ($a,$b) = ($b, $a+$b);\n    @arr.push: ($a, $b);\n    say @arr\n};\n=end code\n\nOutputs C<«[(1 2)]␤[(2 3) (2 3)]␤[(3 5) (3 5) (3 5)]␤...>. C<$a> and C<$b> are\nnot reified until C<say> is called, the value that they have in that precise\nmoment is the one printed. To avoid that, decontainerize values or take them out\nof the variable in some way before using them.\n\n=begin code\nmy @arr;\nmy ($a, $b) = (1,1);\nfor ^5 {\n    ($a,$b) = ($b, $a+$b);\n    @arr.push: ($a.item, $b.item);\n    say @arr\n};\n=end code\n\nWith L<item|/routine/item>, the container will be evaluated in item context, its\nvalue extracted, and the desired outcome achieved.\n\n=head1 L<C<Cool>|/type/Cool> tricks\n\nRaku includes a L<C<Cool>|/type/Cool> class, which provides some of the DWIM\nbehaviors we got used to by coercing arguments when necessary. However, DWIM is\nnever perfect. Especially with L<C<List>|/type/List>s, which are L<C<Cool>|/type/Cool>, there are\nmany methods that will not do what you probably think they do, including\nC<contains>, C<starts-with> or C<index>. Please see some examples in the section\nbelow.\n\n=head2 Strings are not L<C<List>|/type/List>s, so beware indexing\n\nIn Raku, strings (L<C<Str>|/type/Str>s) are not lists of characters. One\nL<cannot iterate|#Strings_are_not_iterable> over them or index into them as you\ncan with L<C<List>|/type/List>s, despite the name of the L<.index method|/type/Str#method_index>.\n\n=head2 L<C<List>|/type/List>s become strings, so beware C<.index()>ing\n\nL<C<List>|/type/List> inherits from L<C<Cool>|/type/Cool>, which provides access to\nL<.index|/type/Str#method_index>. Because of the way C<.index>\nL<coerces|/type/List#method_Str> a L<C<List>|/type/List> into a L<C<Str>|/type/Str>, this can\nsometimes appear to be returning the index of an element in the list, but\nthat is not how the behavior is defined.\n\n=for code\nmy @a = <a b c d>;\nsay @a.index(‘a’);    # OUTPUT: «0␤»\nsay @a.index('c');    # OUTPUT: «4␤» -- not 2!\nsay @a.index('b c');  # OUTPUT: «2␤» -- not undefined!\nsay @a.index(<a b>);  # OUTPUT: «0␤» -- not undefined!\n\nThese same caveats apply to L<.rindex|/type/Str#routine_rindex>.\n\n=head2 L<C<List>|/type/List>s become strings, so beware C<.contains()>\n\nSimilarly, L<.contains|/type/Cool#method_contains> does not look for\nelements in the list.\n\n=for code\nmy @menu = <hamburger fries milkshake>;\nsay @menu.contains('hamburger');            # OUTPUT: «True␤»\nsay @menu.contains('hot dog');              # OUTPUT: «False␤»\nsay @menu.contains('milk');                 # OUTPUT: «True␤»!\nsay @menu.contains('er fr');                # OUTPUT: «True␤»!\nsay @menu.contains(<es mi>);                # OUTPUT: «True␤»!\n\nIf you actually want to check for the presence of an element, use the\nL<(cont)|/routine/(cont), infix ∋> operator for single elements, and the\nL<<superset|/language/operators#infix_(>=),_infix_⊇>> and L<<strict superset|/language/operators#infix_(>),_infix_⊃>>\noperators for multiple elements.\n\n=for code\nmy @menu = <hamburger fries milkshake>;\nsay @menu (cont) 'fries';                   # OUTPUT: «True␤»\nsay @menu (cont) 'milk';                    # OUTPUT: «False␤»\nsay @menu (>) <hamburger fries>;            # OUTPUT: «True␤»\nsay @menu (>) <milkshake fries>;            # OUTPUT: «True␤» (! NB: order doesn't matter)\n\nIf you are doing a lot of element testing, you may be better off using\na L<C<Set>|/type/Set>.\n\n=head2 L<C<Numeric>|/type/Numeric> literals are parsed before coercion\n\nExperienced programmers will probably not be surprised by this, but\nNumeric literals will be parsed into their numeric value before being\ncoerced into a string, which may create nonintuitive results.\n\n=for code\nsay 0xff.contains(55);      # OUTPUT: «True␤»\nsay 0xff.contains(0xf);     # OUTPUT: «False␤»\nsay 12_345.contains(\"23\");  # OUTPUT: «True␤»\nsay 12_345.contains(\"2_\");  # OUTPUT: «False␤»\n\n=head2 Getting a random item from a L<C<List>|/type/List>\n\nA common task is to retrieve one or more random elements from a collection,\nbut C<List.rand> isn't the way to do that. L<C<Cool>|/type/Cool> provides\nL<rand|/type/Cool#method_rand>, but that first coerces the L<C<List>|/type/List> into\nthe number of items in the list, and returns a random real number\nbetween 0 and that value. To get random elements, see L<pick|/routine/pick>\nand L<roll|/routine/roll>.\n\n=for code\nmy @colors = <red orange yellow green blue indigo violet>;\nsay @colors.rand;       # OUTPUT: «2.21921955680514␤»\nsay @colors.pick;       # OUTPUT: «orange␤»\nsay @colors.roll;       # OUTPUT: «blue␤»\nsay @colors.pick(2);    # OUTPUT: «(yellow violet)␤»  (cannot repeat)\nsay @colors.roll(3);    # OUTPUT: «(red green red)␤»  (can repeat)\n\n=head2 L<C<List>|/type/List>s numify to their number of elements in numeric context\n\nYou want to check whether a number is divisible by any of a set of numbers:\n\n    say 42 %% <11 33 88 55 111 20325>; # OUTPUT: «True␤»\n\nWhat? There's no single number 42 should be divisible by. However, that list has\n6 elements, and 42 is divisible by 6. That's why the output is true. In this\ncase, you should turn the L<C<List>|/type/List> into a L<C<Junction>|/type/Junction>:\n\n=for code\nsay 42 %% <11 33 88 55 111 20325>.any;\n# OUTPUT: «any(False, False, False, False, False, False)␤»\n\nwhich will clearly reveal the falsehood of the divisiveness of all the numbers\nin the list, which will be numified separately.\n\n=head1 Arrays\n\n=head2 Referencing the last element of an array\n\nIn some languages one could reference the last element of an array by\nasking for the \"-1th\" element of the array, e.g.:\n\n=for code :lang<perl>\nmy @array = qw{victor alice bob charlie eve};\nsay @array[-1];    # OUTPUT: «eve␤»\n\nIn Raku it is not possible to use negative subscripts, however the same is\nachieved by actually using a function, namely C<*-1>.  Thus, accessing the\nlast element of an array becomes:\n\n=for code\nmy @array = qw{victor alice bob charlie eve};\nsay @array[*-1];   # OUTPUT: «eve␤»\n\nYet another way is to utilize the array's tail method:\n\n=for code\nmy @array = qw{victor alice bob charlie eve};\nsay @array.tail;      # OUTPUT: «eve␤»\nsay @array.tail(2);   # OUTPUT: «(charlie eve)␤»\n\n=head2 Typed array parameters\n\nQuite often new users will happen to write something like:\n\n=for code\nsub foo(Array @a) { ... }\n\n...before they have gotten far enough in the documentation to realize that\nthis is asking for an Array of Arrays.  To say that C<@a> should only accept\nArrays, use instead:\n\n=for code\nsub foo(@a where Array) { ... }\n\nIt is also common to expect this to work, when it does not:\n\n=for code\nsub bar(Int @a) { 42.say };\nbar([1, 2, 3]);             # expected Positional[Int] but got Array\n\nThe problem here is that [1, 2, 3] is not an C<Array[Int]>, it is a plain\nold Array that just happens to have Ints in it.  To get it to work,\nthe argument must also be an C<Array[Int]>.\n\n=for code :preamble<sub bar (Int @a) { 42.say }>\nmy Int @b = 1, 2, 3;\nbar(@b);                    # OUTPUT: «42␤»\nbar(Array[Int].new(1, 2, 3));\n\nThis may seem inconvenient, but on the upside it moves the type-check\non what is assigned to C<@b> to where the assignment happens, rather\nthan requiring every element to be checked on every call.\n\n\n=head2 Using C<«»> quoting when you don't need it\n\nThis trap can be seen in different varieties. Here are some of them:\n\n=begin code\nmy $x = ‘hello’;\nmy $y = ‘foo bar’;\n\nmy %h = $x => 42, $y => 99;\nsay %h«$x»;   # ← WRONG; assumption that $x has no whitespace\nsay %h«$y»;   # ← WRONG; splits ‘foo bar’ by whitespace\nsay %h«\"$y\"»; # ← KINDA OK; it works but there is no good reason to do that\nsay %h{$y};   # ← RIGHT; this is what should be used\n\nrun «touch $x»;        # ← WRONG; assumption that only one file will be created\nrun «touch $y»;        # ← WRONG; will touch file ‘foo’ and ‘bar’\nrun «touch \"$y\"»;      # ← WRONG; better, but has a different issue if $y starts with -\nrun «touch -- \"$y\"»;   # ← KINDA OK; it works but there is no good enough reason to do that\nrun ‘touch’, ‘--’, $y; # ← RIGHT; explicit and *always* correct\nrun <touch -->, $y;    # ← RIGHT; < > are OK, this is short and correct\n=end code\n\nBasically, C<«»> quoting is only safe to use if you remember to\nI<always> quote your variables. The problem is that it inverts the\ndefault behavior to unsafe variant, so just by forgetting some quotes\nyou are risking to introduce either a bug or maybe even a security\nhole. To stay on the safe side, refrain from using C<«»>.\n\n=head1 Strings\n\nSome problems that might arise when dealing with L<C<Str>|/type/Str>s.\n\n=head2 Quotes and interpolation\n\nInterpolation in string literals can be too clever for your own good.\n\n=for code :preamble<my $foo>\n# \"HTML tags\" interpreted as associative indexing:\n\"$foo<html></html>\" eq\n\"$foo{'html'}{'/html'}\"\n\n=for code :preamble<my $foo = { $^x }>\n# Parentheses interpreted as call with argument:\n\"$foo(\" ~ @args ~ \")\" eq\n\"$foo(' ~ @args ~ ')\"\n\nYou can avoid those problems using non-interpolating single quotes and switching\nto more liberal interpolation with C<\\qq[]> escape sequence:\n\n=for code\nmy $a = 1;\nsay '\\qq[$a]()$b()';\n# OUTPUT: «1()$b()␤»\n\nAnother alternative is to use C<Q:c> quoter, and use code blocks C<{}> for\nall interpolation:\n\n=for code\nmy $a = 1;\nsay Q:c«{$a}()$b()»;\n# OUTPUT: «1()$b()␤»\n\n=head2 Beware of variables used within C<qqx>\n\nVariables within C<qqx[]> can introduce a security hole; the variable content can be set to well-crafted string and execute arbitrary code:\n\n=for code\nmy $world = \"there\\\";rm -rf /path/to/dir\\\"\";\nsay qqx{echo \"hello $world\"};\n# OUTPUT: «hello there␤»\n\nThe above code will also delete I</path/to/dir>, you can avoid this problem by making sure the variable content does not have shell special characters, or use L<run|/routine/run> and L<C<Proc::Async>|/type/Proc::Async> for better ways to execute external commands.\n\n=head2 Strings are not iterable\n\nThere are methods that L<C<Str>|/type/Str> inherits from L<C<Any>|/type/Any> that work\non iterables like lists. Iterators on strings contain one element that is the\nwhole string. To use list-based methods like C<sort>, C<reverse>, you need to\nconvert the string into a list first.\n\n=for code\nsay \"cba\".sort;              # OUTPUT: «(cba)␤»\nsay \"cba\".comb.sort.join;    # OUTPUT: «abc␤»\n\n=head2 C<.chars> gets the number of graphemes, not Codepoints\n\nIn Raku, L«C<.chars>|/routine/chars» returns the number of graphemes, or user visible\ncharacters. These graphemes could be made up of a letter plus an accent for\nexample. If you need the number of codepoints, you should use\nL«C<.codes>|/routine/codes». If you need the number of bytes when encoded as UTF8, you\nshould use C<.encode.bytes> to encode the string as UTF8 and then get the number\nof bytes.\n\n    say \"\\c[LATIN SMALL LETTER J WITH CARON, COMBINING DOT BELOW]\"; # OUTPUT: «ǰ̣␤»\n    say 'ǰ̣'.codes;        # OUTPUT: «2␤»\n    say 'ǰ̣'.chars;        # OUTPUT: «1␤»\n    say 'ǰ̣'.encode.bytes; # OUTPUT: «4␤»\n\nFor more information on how strings work in Raku, see the L<Unicode page|/language/unicode>.\n\n=head2 All text is normalized by default\n\nRaku normalizes all text into Unicode NFC form (Normalization Form Canonical).\nFilenames are the only text not normalized by default. If you are expecting\nyour strings to maintain a byte for byte representation as the original,\nyou need to use L«C<UTF8-C8>|/language/unicode#UTF8-C8» when reading or writing\nto any filehandles.\n\n=head2 Allomorphs generally follow numeric semantics\n\nL<C<Str>|/type/Str> C<\"0\"> is C<True>, while L<C<Numeric>|/type/Numeric> is C<False>. So what's the L<C<Bool>|/type/Bool> value of\nL<allomorph|/language/glossary#Allomorph> C«<0>»?\n\nIn general, allomorphs follow L<C<Numeric>|/type/Numeric> semantics, so the ones that I<numerically> evaluate\nto zero are C<False>:\n\n    say so   <0>; # OUTPUT: «False␤»\n    say so <0e0>; # OUTPUT: «False␤»\n    say so <0.0>; # OUTPUT: «False␤»\n\nTo force comparison being done for the L<C<Stringy>|/type/Stringy> part of the allomorph, use\nL«prefix C<~> operator|/routine/~» or the L<C<Str>|/type/Str> method to coerce the allomorph\nto L<C<Str>|/type/Str>, or use the L<chars|/routine/chars> routine to test whether the allomorph has any length:\n\n    say so      ~<0>;     # OUTPUT: «True␤»\n    say so       <0>.Str; # OUTPUT: «True␤»\n    say so chars <0>;     # OUTPUT: «True␤»\n\n=head2 Case-insensitive comparison of strings\n\nIn order to do case-insensitive comparison, you can use C<.fc>\n(fold-case). The problem is that people tend to use C<.lc> or C<.uc>,\nand it does seem to work within the ASCII range, but fails on other\ncharacters. This is not just a Raku trap, the same applies to other\nlanguages.\n\n=begin code\nsay ‘groß’.lc eq ‘GROSS’.lc; # ← WRONG; False\nsay ‘groß’.uc eq ‘GROSS’.uc; # ← WRONG; True, but that's just luck\nsay ‘groß’.fc eq ‘GROSS’.fc; # ← RIGHT; True\n=end code\n\nIf you are working with regexes, then there is no need to use C<.fc>\nand you can use C<:i> (C<:ignorecase>) adverb instead.\n\n\n=head1 Pairs\n\n=head2 Constants on the left-hand side of pair notation\n\nConsider this code:\n\n=begin code\nenum Animals <Dog Cat>;\nmy %h := :{ Dog => 42 };\nsay %h{Dog}; # OUTPUT: «(Any)␤»\n=end code\n\nThe C<:{ … }> syntax is used to create\nL<object hashes|/language/hashmap#Non-string_keys_(object_hash)>. The\nintentions of someone who wrote that code were to create a hash with\nEnum objects as keys (and C<say %h{Dog}> attempts to get a value using\nthe Enum object to perform the lookup). However, that's not how pair\nnotation works.\n\nFor example, in C«Dog => 42» the key will be a L<C<Str>|/type/Str>. That is, it\ndoesn't matter if there is a constant, or an enumeration with the\nsame name. The pair notation will always use the left-hand side as a\nstring literal, as long as it looks like an identifier.\n\nTo avoid this, use C«(Dog) => 42» or C«::Dog => 42».\n\n\n=head2 Scalar values within L<C<Pair>|/type/Pair>\n\nWhen dealing with L<C<Scalar>|/type/Scalar> values, the L<C<Pair>|/type/Pair> holds\nthe container to the value. This means that\nit is possible to reflect changes to the L<C<Scalar>|/type/Scalar> value\nfrom outside the L<C<Pair>|/type/Pair>:\n\n=begin code\nmy $v = 'value A';\nmy $pair = Pair.new( 'a', $v );\n$pair.say;  # OUTPUT: a => value A\n\n$v = 'value B';\n$pair.say; # OUTPUT: a => value B\n=end code\n\nUse the method L<freeze|/type/Pair#method_freeze> to force the removal of the\nL<C<Scalar>|/type/Scalar> container from the L<C<Pair>|/type/Pair>. For more details see the documentation\nabout L<C<Pair>|/type/Pair>.\n\n=head1 Sets, bags and mixes\n\n=head2 Sets, bags and mixes do not have a fixed order\n\nWhen iterating over this kind of objects, an order is not defined.\n\n=begin code\nmy $set = <a b c>.Set;\n.say for $set.list; # OUTPUT: «a => True␤c => True␤b => True␤»\n# OUTPUT: «a => True␤c => True␤b => True␤»\n# OUTPUT: «c => True␤b => True␤a => True␤»\n=end code\n\nEvery iteration might (and will) yield a different order, so you cannot trust\na particular sequence of the elements of a set. If order does not matter, just\nuse them that way. If it does, use C<sort>\n\n    my $set = <a b c>.Set;\n    .say for $set.list.sort;  # OUTPUT: «a => True␤b => True␤c => True␤»\n\nIn general, sets, bags and mixes are unordered, so you should not depend on them\nhaving a particular order.\n\n=head1 Operators\n\nSome operators commonly shared among other languages were repurposed in Raku\nfor other, more common, things:\n\n=head2 Junctions\n\nThe C<^>, C<|>, and C<&> are I<not> bitwise operators, they create\nL<Junctions|/type/Junction>. The corresponding bitwise operators in Raku are:\nC<+^>, C<+|>, C<+&> for integers and C<?^>, C<?|>, C<?&> for\nL<Bools|/type/Bool>.\n\n=head2 Exclusive sequence operator\n\nLavish use of whitespace helps readability, but keep in mind infix operators\ncannot have any whitespace in them. One such operator is the sequence operator\nthat excludes right point: C<...^> (or its L<Unicode\nequivalent|/language/unicode_ascii> C<…^>).\n\n    say 1... ^5; # OUTPUT: «(1 0 1 2 3 4)␤»\n    say 1...^5;  # OUTPUT: «(1 2 3 4)␤»\n\nIf you place whitespace between the ellipsis (C<…>) and the caret (C<^>),\nit's no longer a single infix operator, but an infix inclusive sequence operator\n(C<…>) and a prefix L<C<Range>|/type/Range> operator (C<^>). L«Iterables|/type/Iterable»\nare valid endpoints for the sequence operator, so the result you'll get might\nnot be what you expected.\n\n=head2 String ranges/Sequences\n\nIn some languages, using strings as range end points, considers the entire\nstring when figuring out what the next string should be; loosely treating the\nstrings as numbers in a large base. Here's the Perl version:\n\n=for code\nsay join \", \", \"az\"..\"bc\";\n# OUTPUT: «az, ba, bb, bc␤»\n\nSuch a range in Raku will produce a different result, where I<each letter>\nwill be ranged to a corresponding letter in the end point, producing more\ncomplex sequences:\n\n=for code\nsay join \", \", \"az\"..\"bc\";\n#`{ OUTPUT: «\n    az, ay, ax, aw, av, au, at, as, ar, aq, ap, ao, an, am, al, ak, aj, ai, ah,\n    ag, af, ae, ad, ac, bz, by, bx, bw, bv, bu, bt, bs, br, bq, bp, bo, bn, bm,\n    bl, bk, bj, bi, bh, bg, bf, be, bd, bc\n␤»}\n\n=for code\nsay join \", \", \"r2\"..\"t3\";\n# OUTPUT: «r2, r3, s2, s3, t2, t3␤»\n\nTo achieve simpler behavior, similar to the Perl example above, use a\nsequence operator that calls C<.succ> method on the starting string:\n\n=for code\nsay join \", \", (\"az\", *.succ ... \"bc\");\n# OUTPUT: «az, ba, bb, bc␤»\n\n=head2 Topicalizing operators\n\nThe smartmatch operator C<~~> and C<andthen> set the topic C<$_> to\ntheir left-hand-side. In conjunction with implicit method calls on the\ntopic this can lead to surprising results.\n\n=for code\nmy &method = { note $_; $_ };\n$_ = 'object';\nsay .&method;\n# OUTPUT: «object␤object␤»\nsay 'topic' ~~ .&method;\n# OUTPUT: «topic␤True␤»\n\nIn many cases flipping the method call to the LHS will work.\n\n=for code\nmy &method = { note $_; $_ };\n$_ = 'object';\nsay .&method;\n# OUTPUT: «object␤object␤»\nsay .&method ~~ 'topic';\n# OUTPUT: «object␤False␤»\n\n=head2 Fat arrow and constants\n\nThe fat arrow operator C«=>» will turn words on its left-hand side to\nL<C<Str>|/type/Str> without checking the scope for constants or C<\\>-sigiled\nvariables. Use explicit scoping to get what you mean.\n\n=for code\nconstant V = 'x';\nmy %h = V => 'oi‽', ::V => 42;\nsay %h.raku\n# OUTPUT: «{:V(\"oi‽\"), :x(42)}␤»\n\n=head2 Infix operator assignment\n\nInfix operators, both built in and user defined, can be combined with the\nassignment operator as this addition example demonstrates:\n\n    my $x = 10;\n    $x += 20;\n    say $x;     # OUTPUT: «30␤»\n\nFor any given infix operator C<op>, C<L op= R> is equivalent to C<L = L op R>\n(where C<L> and C<R> are the left and right arguments, respectively).\nThis means that the following code may not behave as expected:\n\n    my @a = 1, 2, 3;\n    @a += 10;\n    say @a;  # OUTPUT: «[13]␤»\n\nComing from a language like C++, this might seem odd. It is important to bear\nin mind that C<+=> isn't defined as method on the left-hand argument\n(here the C<@a> array) but is simply shorthand for:\n\n    my @a = 1, 2, 3;\n    @a = @a + 10;\n    say @a;  # OUTPUT: «[13]␤»\n\nHere C<@a> is assigned the result of adding C<@a> (which has three elements)\nand C<10>; C<13> is therefore placed in C<@a>.\n\nUse the L<hyper form|/language/operators#Hyper_operators>\nof the assignment operators instead:\n\n    my @a = 1, 2, 3;\n    @a »+=» 10;\n    say @a;  # OUTPUT: «[11 12 13]␤»\n\n=head3 Method calls do not chain\n\nAn exception to the clarification C<L = L op R> above occurs when infix operator\nassignment is used in conjunction with the method call operator a la C<L .= R>.\nIn this case, only the first method in any chain is applied in the assignment.\n\n    my $s = \"abcd\";\n    say $s .= uc.lc; # OUTPUT: abcd\n    say $s;          # OUTPUT: ABCD\n\nBy separating the chain into individual infix operator assignments, you can achieve\nthe desired affect:\n\n    my $s = \"abcd\";\n    say $s .= uc .= lc; # OUTPUT: abcd\n    say $s;             # OUTPUT: abcd\n\n=head1 Regexes\n\n=head2 C«$x» vs C«<$x>», and C«$(code)» vs C«<{code}>»\n\nRaku offers several constructs to generate regexes at runtime through\ninterpolation (see their detailed description\nL<here|/language/regexes#Regex_interpolation>). When a regex generated this way\ncontains only literals, the above constructs behave (pairwise) identically, as\nif they are equivalent alternatives. As soon as the generated regex contains\nmetacharacters, however, they behave differently, which may come as a confusing\nsurprise.\n\nThe first two constructs that may easily be confused with each other are\nC«$variable» and C«<$variable>»:\n\n    my $variable = 'camelia';\n    say ‘I ♥ camelia’ ~~ /  $variable  /;   # OUTPUT: ｢camelia｣\n    say ‘I ♥ camelia’ ~~ / <$variable> /;   # OUTPUT: ｢camelia｣\n\nHere they act the same because the value of C<$variable> consists of literals.\nBut when the variable is changed to comprise regex metacharacters the outputs\nbecome different:\n\n    my $variable = '#camelia';\n    say ‘I ♥ #camelia’ ~~ /  $variable  /;   # OUTPUT: «｢#camelia｣␤»\n    say ‘I ♥ #camelia’ ~~ / <$variable> /;   # !! Error: malformed regex\n\nWhat happens here is that the string C<#camelia> contains the metacharacter\nC<#>. In the context of a regex, this character should be quoted to match\nliterally; without quoting, the C<#> is parsed as the start of a comment that\nruns until the end of the line, which in turn causes the regex not to be\nterminated, and thus to be malformed.\n\nTwo other constructs that must similarly be distinguished from one another are\nC«$(code)» and C«<{code}>». Like before, as long as the (stringified) return\nvalue of C<code> comprises only literals, there is no distinction between the\ntwo:\n\n    my $variable = 'ailemac';\n    say ‘I ♥ camelia’ ~~ / $($variable.flip)   /;   # OUTPUT: «｢camelia｣␤»\n    say ‘I ♥ camelia’ ~~ / <{$variable.flip}>  /;   # OUTPUT: «｢camelia｣␤»\n\nBut when the return value is changed to comprise regex metacharacters, the\noutputs diverge:\n\n    my $variable = 'ailema.';\n    say ‘I ♥ camelia’ ~~ / $($variable.flip)   /;   # OUTPUT: Nil\n    say ‘I ♥ camelia’ ~~ / <{$variable.flip}>  /;   # OUTPUT: «｢camelia｣␤»\n\nIn this case the return value of the code is the string C<.amelia>, which\ncontains the metacharacter C<.>. The above attempt by C«$(code)» to match the\ndot literally fails; the attempt by C«<{code}>» to match the dot as a regex\nwildcard succeeds. Hence the different outputs.\n\n=head2 C<|> vs C<||>: which branch will win\n\nTo match one of several possible alternatives, C<||> or C<|> will be used. But\nthey are so different.\n\nWhen there are multiple matching alternations, for those separated by\nC<||>, the first matching alternation wins; for those separated by C<|>,\nwhich to win is decided by LTM strategy. See also:\nL<documentation on C<||>|/language/regexes#Alternation:_||> and\nL<documentation on C<|>|/language/regexes#Longest_alternation:_|>.\n\nFor simple regexes just using C<||> instead of C<|>\nwill get you familiar semantics, but if writing grammars then it's useful to\nlearn about LTM and declarative prefixes and prefer C<|>. And keep yourself\naway from using them in one regex. When you have to do that, add parentheses\nand ensure that you know how LTM strategy works to make the code\ndo what you want.\n\nThe trap typically arises when you try to mix both C<|> and C<||> in\nthe same regex:\n\n=for code\nsay 42 ~~ / [  0 || 42 ] | 4/; # OUTPUT: «｢4｣␤»\nsay 42 ~~ / [ 42 ||  0 ] | 4/; # OUTPUT: «｢42｣␤»\n\nThe code above may seem like it is producing a wrong result, but the\nimplementation is actually right.\n\n=head2 C<$/> changes each time a regular expression is matched\n\nEach time a regular expression is matched against something, the special\nvariable C<$/> holding the result L<Match object|/type/Match>\nis changed accordingly to the result of the match (that could also be L<C<Nil>|/type/Nil>).\n\nThe C<$/> is changed without any regard to the scope the regular expression is matched within.\n\nFor further information and examples please see the L<related section in the Regular Expressions documentation|/language/regexes#$/_changes_each_time_a_regular_expression_is_matched>.\n\n=head2 C«<foo>» vs. C«< foo>»: named rules vs. quoted lists\n\nRegexes can contain quoted lists; longest token matching is performed on the\nlist's elements as if a C<|> alternation had been specified (see\nL<here|/language/regexes#Quoted_lists_are_LTM_matches> for further information).\n\nWithin a regex, the following are lists with a single item, C<'foo'>:\n\n    say 'foo' ~~ /< foo >/;  # OUTPUT: «｢foo｣␤»\n    say 'foo' ~~ /< foo>/;   # OUTPUT: «｢foo｣␤»\n\nbut this is a call to the named rule C<foo>:\n\n=begin code\nsay 'foo' ~~ /<foo>/;\n# OUTPUT: «No such method 'foo' for invocant of type 'Match'␤ in block <unit> at <unknown file> line 1␤»\n=end code\n\nBe wary of the difference; if you intend to use a quoted list, ensure that\nwhitespace follows the initial C«<».\n\n=head2 Non-capturing, non-global matching in list context\n\nUnlike Perl, non-capturing and non-global matching in list context doesn't produce any values:\n\n    if  'x' ~~ /./ { say 'yes' }  # OUTPUT: «yes␤»\n    for 'x' ~~ /./ { say 'yes' }  # NO OUTPUT\n\nThis is because its 'list' slot (inherited from Capture class) doesn't get populated with the original Match object:\n\n    say ('x' ~~ /./).list  # OUTPUT: «()␤»\n\nTo achieve the desired result, use global matching, capturing parentheses or a list with a trailing comma:\n\n    for 'x' ~~ m:g/./ { say 'yes' }  # OUTPUT: «yes␤»\n    for 'x' ~~ /(.)/  { say 'yes' }  # OUTPUT: «yes␤»\n    for ('x' ~~ /./,) { say 'yes' }  # OUTPUT: «yes␤»\n\n=head1 Common precedence mistakes\n\n=head2 Adverbs and precedence\n\nAdverbs do have a precedence that may not follow the order of operators that is displayed on your screen. If two operators of equal precedence are followed by an adverb it will pick the first operator it finds in the abstract syntax tree. Use parentheses to help Raku understand what you mean or use operators with looser precedence.\n\n=for code\nmy %x = a => 42;\nsay !%x<b>:exists;            # dies with X::AdHoc\nsay %x<b>:!exists;            # this works\nsay !(%x<b>:exists);          # works too\nsay not %x<b>:exists;         # works as well\nsay True unless %x<b>:exists; # avoid negation altogether\n\n=head2 Ranges and precedence\n\nThe loose precedence of C<..> can lead to some errors.  It is usually best to parenthesize ranges when you want to operate on the entire range.\n\n=for code\n1..3.say;    # OUTPUT: «3␤» (and warns about useless use of \"..\")\n(1..3).say;  # OUTPUT: «1..3␤»\n\n=head2 Loose Boolean operators\n\nThe precedence of C<and>, C<or>, etc. is looser than routine calls. This can\nhave surprising results for calls to routines that would be operators or\nstatements in other languages like C<return>, C<last> and many others.\n\n=for code\nsub f {\n    return True and False;\n    # this is actually\n    # (return True) and False;\n}\nsay f; # OUTPUT: «True␤»\n\n=head2 Exponentiation operator and prefix minus\n\n=for code\nsay -1²;   # OUTPUT: «-1␤»\nsay -1**2; # OUTPUT: «-1␤»\n\nWhen performing a\nL<regular mathematical calculation|https://www.wolframalpha.com/input/?i=-1%C2%B2>,\nthe power takes precedence over the minus; so C<-1²> can be written as C<-(1²)>.\nRaku matches these rules of mathematics and the precedence of C<**> operator is\ntighter than that of the prefix C<->. If you wish to raise a negative number\nto a power, use parentheses:\n\n=for code\nsay (-1)²;   # OUTPUT: «1␤»\nsay (-1)**2; # OUTPUT: «1␤»\n\n=head2 Method operator calls and prefix minus\n\nPrefix minus binds looser than dotty method op calls. The prefix minus will be\napplied to the return value from the method. To ensure the minus gets\npassed as part of the argument, enclose in parenthesis.\n\n=for code\nsay  -1.abs;  # OUTPUT: «-1␤»\nsay (-1).abs; # OUTPUT: «1␤»\n\n=head1 Subroutine and method calls\n\nSubroutine and method calls can be made using one of two forms:\n\n=for code :skip-test<illustrates pattern>\nfoo(...); # function call form, where ... represent the required arguments\nfoo ...;  # list op form, where ... represent the required arguments\n\nThe function call form can cause problems for the unwary when\nwhitespace is added after the function or method name and before the\nopening parenthesis.\n\nFirst we consider functions with zero or one parameter:\n\n=for code\nsub foo() { say 'no arg' }\nsub bar($a) { say \"one arg: $a\" }\n\nThen execute each with and without a space after the name:\n\n=for code :skip-test<illustrates error>\nfoo();    # okay: no arg\nfoo ();   # FAIL: Too many positionals passed; expected 0 arguments but got 1\nbar($a);  # okay: one arg: 1\nbar ($a); # okay: one arg: 1\n\nNow declare a function of two parameters:\n\n=for code\nsub foo($a, $b) { say \"two args: $a, $b\" }\n\nExecute it with and without the space after the name:\n\n=for code :skip-test<illustrates error>\nfoo($a, $b);  # okay: two args: 1, 2\nfoo ($a, $b); # FAIL: Too few positionals passed; expected 2 arguments but got 1\n\nThe lesson is: \"be careful with spaces following sub and method names\nwhen using the function call format.\"  As a general rule, good\npractice might be to avoid the space after a function name when using\nthe function call format.\n\nNote that there are clever ways to eliminate the error with the\nfunction call format and the space, but that is bordering on hackery\nand will not be mentioned here.  For more information, consult\nL<Functions|/language/functions#Functions>.\n\nFinally, note that, currently, when declaring the functions whitespace\nmay be used between a function or method name and the parentheses\nsurrounding the parameter list without problems.\n\n=head2 Named parameters\n\nMany built-in subroutines and method calls accept named parameters and your own\ncode may accept them as well, but be sure the arguments you pass when calling\nyour routines are actually named parameters:\n\n=for code\nsub foo($a, :$b) { ... }\nfoo(1, 'b' => 2); # FAIL: Too many positionals passed; expected 1 argument but got 2\n\nWhat happened? That second argument is not a named parameter argument, but a\nL<C<Pair>|/type/Pair> passed as a positional argument. If you want a named\nparameter it has to look like a name to Perl:\n\n=begin code :preamble<sub foo ($a, *%arg) {}>\nfoo(1, b => 2); # okay\nfoo(1, :b(2));  # okay\nfoo(1, :b<it>); # okay\n\nmy $b = 2;\nfoo(1, :b($b)); # okay, but redundant\nfoo(1, :$b);    # okay\n\n# Or even...\nmy %arg = 'b' => 2;\nfoo(1, |%arg);  # okay too\n=end code\n\nThat last one may be confusing, but since it uses the C<|> prefix on a\nL<C<Hash>|/type/Hash>, which is a special compiler construct indicating you\nwant to use I<the contents> of the variable as arguments, which for hashes\nmeans to treat them as named arguments.\n\nIf you really do want to pass them as pairs you should use a L<C<List>|/type/List>\nor L<C<Capture>|/type/Capture> instead:\n\n=for code :skip-test<illustrates error>\nmy $list = ('b' => 2),; # this is a List containing a single Pair\nfoo(|$list, :$b);       # okay: we passed the pair 'b' => 2 to the first argument\nfoo(1, |$list);         # FAIL: Too many positionals passed; expected 1 argument but got 2\nfoo(1, |$list.Capture); # OK: .Capture call converts all Pair objects to named args in a Capture\n\n=for code :skip-test<illustrates error>\nmy $cap = \\('b' => 2); # a Capture with a single positional value\nfoo(|$cap, :$b); # okay: we passed the pair 'b' => 2 to the first argument\nfoo(1, |$cap);   # FAIL: Too many positionals passed; expected 1 argument but got 2\n\nA Capture is usually the best option for this as it works exactly like the usual\ncapturing of routine arguments during a regular call.\n\nThe nice thing about the distinction here is that it gives the developer the\noption of passing pairs as either named or positional arguments, which can be\nhandy in various instances.\n\n=head2 Argument count limit\n\nWhile it is typically unnoticeable, there is a backend-dependent\nargument count limit. Any code that does flattening of arbitrarily\nsized arrays into arguments won't work if there are too many elements.\n\n=for code\nmy @a = 1 xx 9999;\nmy @b;\n@b.push: |@a;\nsay @b.elems # OUTPUT: «9999␤»\n\n=for code\nmy @a = 1 xx 999999;\nmy @b;\n@b.push: |@a; # OUTPUT: «Too many arguments in flattening array.␤  in block <unit> at <tmp> line 1␤␤»\n\nAvoid this trap by rewriting the code so that there is no\nflattening. In the example above, you can replace C<push> with\nC<append>. This way, no flattening is required because the array can\nbe passed as is.\n\n=for code\nmy @a = 1 xx 999999;\nmy @b;\n@b.append: @a;\nsay @b.elems # OUTPUT: «999999␤»\n\n=head2 Phasers and implicit return\n\n=begin code\nsub returns-ret () {\n    CATCH {\n        default {}\n    }\n    \"ret\";\n}\n\nsub doesn't-return-ret () {\n    \"ret\";\n    CATCH {\n        default {}\n    }\n}\n\nsay returns-ret;        # OUTPUT: «ret␤»\nsay doesn't-return-ret;\n# BAD: outputs «Nil» and a warning «Useless use of constant string \"ret\" in sink context (line 13)»\n=end code\n\nCode for C<returns-ret> and C<doesn't-return-ret> might look exactly the same, since in principle it does not matter where the L<C<CATCH>|/language/phasers#CATCH> block goes. However, a block is an object and the last object in a C<sub> will be returned, so the C<doesn't-return-ret> will return L<C<Nil>|/type/Nil>, and, besides, since \"ret\" will be now in sink context, it will issue a warning. In case you want to place phasers last for conventional reasons, use the explicit form of C<return>.\n\n=begin code\nsub explicitly-return-ret () {\n    return \"ret\";\n    CATCH {\n        default {}\n    }\n}\n=end code\n\n=head2 C<LEAVE> needs explicit return from a sub to run\n\nAs the documentation for the\nL<C<LEAVE> phaser indicates|/language/phasers#LEAVE>\nC<LEAVE> runs when a block is exited, \"... except when the program exits\nabruptly\". That is, unlike C<END>, it's going to be invoked only if the block\nactually returns in an orderly way. This is why:\n\n=for code\nsub a() { LEAVE say \"left\"; exit 1 }; # No output, it will simply exit\n\nwill not run the C<LEAVE> code, since technically it's not returning. On the\nother hand, L<C<END>|/language/phasers#END> is a program execution phaser and\nwill run no matter what\n\n=for code\nsub a() {\n    END say \"Begone\"; exit 1\n}; a; # OUTPUT: «Begone␤»\n\n=head1 Input and output\n\n=head2 Closing open filehandles and pipes\n\nUnlike some other languages, Raku does not use reference counting,\nand so B<the filehandles are NOT closed when they go out of scope>. You\nhave to explicitly close them either by using L<close|/routine/close> routine or using the\nC<:close> argument several of L<C<IO::Handle's>|/type/IO::Handle> methods accept.\nSee L«C<IO::Handle.close>|/type/IO::Handle#routine_close» for details.\n\nThe same rules apply to L<C<IO::Handle's>|/type/IO::Handle> subclass\nL<C<IO::Pipe>|/type/IO::Pipe>, which is what you operate on when reading from a L<C<Proc>|/type/Proc> you get\nwith routines L<run|/routine/run> and L<shell|/routine/shell>.\n\nThe caveat applies to L<C<IO::CatHandle>|/type/IO::CatHandle> type as well, though not as severely.\nSee L«C<IO::CatHandle.close>|/type/IO::CatHandle#method_close» for details.\n\n=head2 IO::Path stringification\n\nPartly for historical reasons and partly by design, an L<C<IO::Path>|/type/IO::Path> object\nL<stringifies|/type/IO::Path#method_Str> without considering its\nL«C<CWD> attribute|/type/IO::Path#attribute_CWD», which means if you L<chdir|/routine/chdir>\nand then stringify an L<C<IO::Path>|/type/IO::Path>, or stringify an L<C<IO::Path>|/type/IO::Path> with custom\nC<$!CWD> attribute, the resultant string won't reference the original\nfilesystem object:\n\n=begin code\nwith 'foo'.IO {\n    .Str.say;       # OUTPUT: «foo␤»\n    .relative.say;  # OUTPUT: «foo␤»\n\n    chdir \"/tmp\";\n    .Str.say;       # OUTPUT: «foo␤»\n    .relative.say   # OUTPUT: «../home/camelia/foo␤»\n}\n\n# Deletes ./foo, not /bar/foo\nunlink IO::Path.new(\"foo\", :CWD</bar>).Str\n=end code\n\nThe easy way to avoid this issue is to not stringify an L<C<IO::Path>|/type/IO::Path> object at all.\nCore routines that work with paths can take an L<C<IO::Path>|/type/IO::Path> object, so you don't\nneed to stringify the paths.\n\nIf you do have a case where you need a stringified version of an L<C<IO::Path>|/type/IO::Path>, use\nL<absolute|/routine/absolute> or L<relative|/routine/relative> methods to stringify it into an absolute or relative\npath, respectively.\n\nIf you are facing this issue because you use L<chdir|/routine/chdir> in your code,\nconsider rewriting it in a way that does not involve changing the\ncurrent directory. For example, you can pass C<cwd> named argument to\nL<run|/routine/run> without having to use C<chdir> around it.\n\n=head2 Splitting the input data into lines\n\nThere is a difference between using C<.lines> on\nL«C<IO::Handle>|/type/IO::Handle#routine_lines» and on a\nL«C<Str>|/type/Str#routine_lines». The trap arises if you start\nassuming that both split data the same way.\n\n=begin code\nsay $_.raku for $*IN.lines # .lines called on IO::Handle\n# OUTPUT:\n# \"foox\"\n# \"fooy\\rbar\"\n# \"fooz\"\n=end code\n\nAs you can see in the example above, there was a line which contained\nC<\\r> (“carriage return” control character). However, the input is\nsplit strictly by C<\\n>, so C<\\r> was kept as part of the string.\n\nOn the other hand, L«C<Str.lines>|/type/Str#routine_lines» attempts to\nbe “smart” about processing data from different operating\nsystems. Therefore, it will split by all possible variations of a\nnewline.\n\n=begin code\nsay $_.raku for $*IN.slurp(:bin).decode.lines # .lines called on a Str\n# OUTPUT:\n# \"foox\"\n# \"fooy\"\n# \"bar\"\n# \"fooz\"\n=end code\n\nThe rule is quite simple: use\nL«C<IO::Handle.lines>|/type/IO::Handle#routine_lines» when working with\nprogrammatically generated output, and\nL«C<Str.lines>|/type/Str#routine_lines» when working with user-written\ntexts.\n\nUse C<$data.split(“\\n”)> in cases where you need the behavior of\nL«C<IO::Handle.lines>|/type/IO::Handle#routine_lines» but the original\nL<C<IO::Handle>|/type/IO::Handle> is not available.\n\n=comment RT#132154\n\nNote that if you really want to slurp the data first, then you will\nhave to use C<.IO.slurp(:bin).decode.split(“\\n”)>. Notice how we use\nC<:bin> to prevent it from doing the decoding, only to call C<.decode>\nlater anyway. All that is needed because C<.slurp> is assuming that\nyou are working with text and therefore it attempts to be smart about\nnewlines.\n\n=comment RT#131923\n\nIf you are using L<C<Proc::Async>|/type/Proc::Async>, then there is currently no easy way\nto make it split data the right way. You can try reading the whole\noutput and then using L«C<Str.split>|/type/Str#routine_split» (not viable\nif you are dealing with large data) or writing your own logic to split\nthe incoming data the way you need. Same applies if your data\nis null-separated.\n\n\n=head2 L<C<Proc::Async>|/type/Proc::Async> and C<print>\n\nWhen using Proc::Async you should not assume that C<.print> (or any\nother similar method) is synchronous. The biggest issue of this trap\nis that you will likely not notice the problem by running the code\nonce, so it may cause a hard-to-detect intermittent fail.\n\nHere is an example that demonstrates the issue:\n\n=begin code\nloop {\n    my $proc = Proc::Async.new: :w, ‘head’, ‘-n’, ‘1’;\n    my $got-something;\n    react {\n        whenever $proc.stdout.lines { $got-something = True }\n        whenever $proc.start        { die ‘FAIL!’ unless $got-something }\n\n        $proc.print: “one\\ntwo\\nthree\\nfour”;\n        $proc.close-stdin;\n    }\n    say $++;\n}\n=end code\n\nAnd the output it may produce:\n\n=begin code :lang<text>\n0\n1\n2\n3\nAn operation first awaited:\n  in block <unit> at print.raku line 4\n\nDied with the exception:\n    FAIL!\n      in block  at print.raku line 6\n=end code\n\nResolving this is easy because C<.print> returns a promise that you\ncan await on. The solution is even more beautiful if you are\nworking in a L<react|/language/concurrency#react> block:\n\n=begin code :skip-test<$proc needs a complex initialization>\nwhenever $proc.print: “one\\ntwo\\nthree\\nfour” {\n    $proc.close-stdin;\n}\n=end code\n\n=head2 Using C<.stdout> without C<.lines>\n\nMethod C<.stdout> of L<C<Proc::Async>|/type/Proc::Async> returns a supply that emits\nI<chunks> of data, not lines. The trap is that sometimes people assume\nit to give lines right away.\n\n=begin code\nmy $proc = Proc::Async.new(‘cat’, ‘/usr/share/dict/words’);\nreact {\n    whenever $proc.stdout.head(1) { .say } # ← WRONG (most likely)\n    whenever $proc.start { }\n}\n=end code\n\nThe output is clearly not just 1 line:\n\n=begin code :lang<text>\nA\nA's\nAMD\nAMD's\nAOL\nAOL's\nAachen\nAachen's\nAaliyah\nAaliyah's\nAaron\nAaron's\nAbbas\nAbbas's\nAbbasid\nAbbasid's\nAbbott\nAbbott's\nAbby\n=end code\n\nIf you want to work with lines, then use C<$proc.stdout.lines>. If\nyou're after the whole output, then something like this should do the\ntrick: C<whenever $proc.stdout { $out ~= $_ }>.\n\n=head1 Exception handling\n\n=head2 Sunk L<C<Proc>|/type/Proc>\n\nSome methods return a L<C<Proc>|/type/Proc> object. If it represents a failed process, L<C<Proc>|/type/Proc> itself\nwon't be exception-like, but B<sinking it> will cause an L<C<X::Proc::Unsuccessful>|/type/X::Proc::Unsuccessful>\nexception to be thrown. That means this construct will throw, despite the C<try> in place:\n\n=for code\ntry run(\"raku\", \"-e\", \"exit 42\");\nsay \"still alive\";\n# OUTPUT: «The spawned process exited unsuccessfully (exit code: 42)␤»\n\nThis is because C<try> receives a L<C<Proc>|/type/Proc> and returns it, at which point it sinks and\nthrows. Explicitly sinking it inside the C<try> avoids the issue\nand ensures the exception is thrown inside the C<try>:\n\n=for code\ntry sink run(\"raku\", \"-e\", \"exit 42\");\nsay \"still alive\";\n# OUTPUT: «still alive␤»\n\nIf you're not interested in catching any exceptions, then use an anonymous\nvariable to keep the returned L<C<Proc>|/type/Proc> in; this way it'll never sink:\n\n=for code\n$ = run(\"raku\", \"-e\", \"exit 42\");\nsay \"still alive\";\n# OUTPUT: «still alive␤»\n\n\n=head1 Using shortcuts\n\n=head2 The ^ twigil\n\nUsing the C<^> twigil can save a fair amount of time and space when writing out small blocks of code. As an example:\n\n=for code\nfor 1..8 -> $a, $b { say $a + $b; }\n\ncan be shortened to just\n\n=for code\nfor 1..8 { say $^a + $^b; }\n\nThe trouble arises when a person wants to use more complex names for the\nvariables, instead of just one letter. The C<^> twigil is able to have\nthe positional variables be out of order and named whatever you want,\nbut assigns values based on the variable's Unicode ordering. In the\nabove example, we can have C<$^a> and C<$^b> switch places, and those\nvariables will keep their positional values. This is because the Unicode\ncharacter 'a' comes before the character 'b'. For example:\n\n=for code\n# In order\nsub f1 { say \"$^first $^second\"; }\nf1 \"Hello\", \"there\";    # OUTPUT: «Hello there␤»\n\n=for code\n# Out of order\nsub f2 { say \"$^second $^first\"; }\nf2 \"Hello\", \"there\";    # OUTPUT: «there Hello␤»\n\nDue to the variables allowed to be called anything, this can cause some problems if you are not accustomed to how Raku handles these variables.\n\n=begin code\n# BAD NAMING: alphabetically `four` comes first and gets value `1` in it:\nfor 1..4 { say \"$^one $^two $^three $^four\"; }    # OUTPUT: «2 4 3 1␤»\n\n# GOOD NAMING: variables' naming makes it clear how they sort alphabetically:\nfor 1..4 { say \"$^a $^b $^c $^d\"; }               # OUTPUT: «1 2 3 4␤»\n=end code\n\n\n=head2 Using C<»> and C<map> interchangeably\n\nWhile L<<C<»>|/language/operators#methodop_%C2%BB._/_methodop_%3E%3E.>>\nmay look like a shorter way to write C<map>, they differ in some key aspects.\n\nFirst, the C<»> includes a I<hint> to the compiler that it may\nautothread the execution, thus if you're using it to call a routine\nthat produces side effects, those side effects may be produced out of order\n(the result of the operator I<is> kept in order, however).\nAlso if the routine being invoked accesses a resource, there's the\npossibility of a race condition, as multiple invocations may happen\nsimultaneously, from different threads.\n\n=comment This is an actual output from Rakudo 2015.09\n=begin code\n<a b c d>».say # OUTPUT: «d␤b␤c␤a␤»\n=end code\n\nSecond, C<»> checks the L<nodality|/routine/is%20nodal> of the routine being\ninvoked and based on that will use either L<deepmap|/routine/deepmap> or L<nodemap|/routine/nodemap> to map over\nthe list, which can be different from how a L<map|/routine/map> call would map over it:\n=begin code\nsay ((1, 2, 3), [^4], '5')».Numeric;       # OUTPUT: «((1 2 3) [0 1 2 3] 5)␤»\nsay ((1, 2, 3), [^4], '5').map: *.Numeric; # OUTPUT: «(3 4 5)␤»\n=end code\n\nThe bottom line is that C<map> and C<»> are not interchangeable, but\nusing one instead of the other is OK as long as you understand the\ndifferences.\n\n=head2 Word splitting in C<« »>\n\nKeep in mind that C<« »> performs word splitting similarly to how\nshells do it, so\nL<many shell pitfalls|https://mywiki.wooledge.org/BashPitfalls> apply\nhere as well (especially when using in combination with C<run>):\n\n    my $file = ‘--my arbitrary filename’;\n    run ‘touch’, ‘--’, $file;  # RIGHT\n    run <touch -->, $file;     # RIGHT\n\n    run «touch -- \"$file\"»;    # RIGHT but WRONG if you forget quotes\n    run «touch -- $file»;      # WRONG; touches ‘--my’, ‘arbitrary’ and ‘filename’\n    run ‘touch’, $file;        # WRONG; error from `touch`\n    run «touch \"$file\"»;       # WRONG; error from `touch`\n\nNote that C<--> is required for many programs to disambiguate between\ncommand-line arguments and\nL<filenames that begin with hyphens|https://mywiki.wooledge.org/BashPitfalls#Filenames_with_leading_dashes>.\n\n=head1 Scope\n\n=head2 Using a C<once> block\n\nThe C<once> block is a block of code that will only run once when its parent block is run. As an example:\n\n=for code\nmy $var = 0;\nfor 1..10 {\n    once { $var++; }\n}\nsay \"Variable = $var\";    # OUTPUT: «Variable = 1␤»\n\nThis functionality also applies to other code blocks like C<sub> and C<while>, not just C<for> loops. Problems arise though, when trying to nest C<once> blocks inside of other code blocks:\n\n=for code\nmy $var = 0;\nfor 1..10 {\n    do { once { $var++; } }\n}\nsay \"Variable = $var\";    # OUTPUT: «Variable = 10␤»\n\nIn the above example, the C<once> block was nested inside of a code block which was inside of a C<for> loop code block. This causes the C<once> block to run multiple times, because the C<once> block uses state variables to determine whether it has run previously. This means that if the parent code block goes out of scope, then the state variable the C<once> block uses to keep track of if it has run previously, goes out of scope as well. This is why C<once> blocks and C<state> variables can cause some unwanted behavior when buried within more than one code block.\n\nIf you want to have something that will emulate the functionality of a once block, but still work when buried a few code blocks deep, we can manually build the functionality of a C<once> block. Using the above example, we can change it so that it will only run once, even when inside the C<do> block by changing the scope of the C<state> variable.\n\n=for code\nmy $var = 0;\nfor 1..10 {\n    state $run-code = True;\n    do { if ($run-code) { $run-code = False; $var++; } }\n}\nsay \"Variable = $var\";    # OUTPUT: «Variable = 1␤»\n\nIn this example, we essentially manually build a C<once> block by making a C<state> variable called C<$run-code> at the highest level that will be run more than once, then checking to see if C<$run-code> is C<True> using a regular C<if>. If the variable C<$run-code> is C<True>, then make the variable C<False> and continue with the code that should only be completed once.\n\nThe main difference between using a C<state> variable like the above example and using a regular C<once> block is what scope the C<state> variable is in. The scope for the C<state> variable created by the C<once> block, is the same as where you put the block (imagine that the word 'C<once>' is replaced with a state variable and an C<if> to look at the variable). The example above using C<state> variables works because the variable is at the highest scope that will be repeated; whereas the example that has a C<once> block inside of a C<do>, made the variable within the C<do> block which is not the highest scope that is repeated.\n\nUsing a C<once> block inside a class method will cause the once state to carry across all instances of that class.\nFor example:\n\n=for code\nclass A {\n    method sayit() { once say 'hi' }\n}\nmy $a = A.new;\n$a.sayit;      # OUTPUT: «hi␤»\nmy $b = A.new;\n$b.sayit;      # nothing\n\n\n=head2 C<LEAVE> phaser and C<exit>\n\nUsing L«C<LEAVE>|/language/phasers#LEAVE» phaser to perform graceful resource\ntermination is a common pattern, but it does not cover the case when\nthe program is stopped with L«C<exit>|/routine/exit».\n\nThe following nondeterministic example should demonstrate the\ncomplications of this trap:\n=begin code\nmy $x = say ‘Opened some resource’;\nLEAVE say ‘Closing the resource gracefully’ with $x;\n\nexit 42 if rand < ⅓; # ① ｢exit｣ is bad\ndie ‘Dying because of unhandled exception’ if rand < ½; # ② ｢die｣ is ok\n# fallthru ③\n=end code\n\nThere are three possible results:\n=begin code :lang<text>\n①\nOpened some resource\n\n②\nOpened some resource\nClosing the resource gracefully\nDying because of unhandled exception\n  in block <unit> at print.raku line 5\n\n③\nOpened some resource\nClosing the resource gracefully\n=end code\n\nA call to C<exit> is part of normal operation for many programs, so\nbeware unintentional combination of C<LEAVE> phasers and C<exit> calls.\n\n=head2 C<LEAVE> phaser may run sooner than you think\n\nParameter binding is executed when we're \"inside\" the routine's block,\nwhich means C<LEAVE> phaser would run when we leave that block if parameter\nbinding fails when wrong arguments are given:\n\n=begin code\nsub foo(Int) {\n    my $x = 42;\n    LEAVE say $x.Int; # ← WRONG; assumes that $x is set\n}\nsay foo rand; # OUTPUT: «No such method 'Int' for invocant of type 'Any'␤»\n=end code\n\nA simple way to avoid this issue is to declare your sub or method a multi,\nso the candidate is eliminated during dispatch and the code never gets to\nbinding anything inside the sub, thus never entering the routine's body:\n\n=begin code\nmulti foo(Int) {\n    my $x = 42;\n    LEAVE say $x.Int;\n}\nsay foo rand; # OUTPUT: «Cannot resolve caller foo(Num); none of these signatures match: (Int)␤»\n=end code\n\nAnother alternative is placing the C<LEAVE> into another block (assuming it's\nappropriate for it to be executed when I<that> block is left, not the\nroutine's body:\n\n=begin code\nsub foo(Int) {\n    my $x = 42;\n    { LEAVE say $x.Int; }\n}\nsay foo rand; # OUTPUT: «Type check failed in binding to parameter '<anon>'; expected Int but got Num (0.7289418947969465e0)␤»\n=end code\n\nYou can also ensure C<LEAVE> can be executed even if the routine is left\ndue to failed argument binding. In our example, we check C<$x>\nL<is defined|/routine/andthen> before doing anything with it.\n\n=begin code\nsub foo(Int) {\n    my $x = 42;\n    LEAVE $x andthen .Int.say;\n}\nsay foo rand; # OUTPUT: «Type check failed in binding to parameter '<anon>'; expected Int but got Num (0.8517160389079508e0)␤»\n=end code\n\n=head1 Grammars\n\n=head2 Using regexes within grammar's actions\n\n=begin code\n# Define a grammar\ngrammar will-fail {\n    token TOP {^ <word> $}\n    token word { \\w+ }\n}\n\n# Define an action class\nclass will-fail-actions {\n    method TOP ($/) {      # <- note the $/ in the signature, which is readonly\n        my $foo = ~$/;\n        say $foo ~~ /foo/; # <- the regex tries to assign the result to $/ and will fail\n    }\n}\n\n# Try to parse something...\nwill-fail.parse('word', :actions(will-fail-actions));\nCATCH { default { put .^name, ': ', .Str } };\n# OUTPUT: «X::AdHoc: Cannot assign to a readonly variable or a value␤»\n=end code\n\nWill fail with C<Cannot assign to a readonly variable ($/) or a value>\non method C<TOP>. The problem here is that regular expressions also\naffect C<$/>. Since it is in C<TOP>'s signature, it is a read-only\nvariable, which is what produces the error. You can safely either use\nanother variable in the signature or add C<is copy>, this way:\n\n=begin code\nmethod TOP ($/ is copy) { my $foo = ~$/; my $v = $foo ~~ /foo/;  }\n=end code\n\n=head2 Using certain names for rules/token/regexes\n\nGrammars are actually a type of classes.\n\n    grammar G {};\n    say G.^mro; # OUTPUT: «((G) (Grammar) (Match) (Capture) (Cool) (Any) (Mu))␤»\n\nC<^mro> prints the class hierarchy of this empty grammar, showing all the\nsuperclasses. And these superclasses have their very own methods. Defining a\nmethod in that grammar might clash with the ones inhabiting the class hierarchy:\n\n=begin code :skip-test<throws exception>\ngrammar g {\n    token TOP { <item> };\n    token item { 'defined' }\n};\nsay g.parse('defined');\n# OUTPUT: «Too many positionals passed; expected 1 argument but got 2␤  in regex item at /tmp/grammar-clash.raku line 3␤  in regex TOP at /tmp/grammar-clash.raku line 2␤  in block <unit> at /tmp/grammar-clash.raku line 5»\n=end code\n\nC«item» seems innocuous enough, but it is a L<C<sub> defined in class\nC<Mu>|/routine/item>. The message is a bit cryptic and totally unrelated to that\nfact, but that is why this is listed as a trap. In general, all subs defined in\nany part of the hierarchy are going to cause problems; some methods will too.\nFor instance, C<CREATE>, C<take> and C<defined> (which are defined in L<C<Mu>|/type/Mu>). In\ngeneral, multi methods and simple methods will not have any problem, but it\nmight not be a good practice to use them as rule names.\n\nAlso avoid L<phasers|/language/objects#Object_construction> for rule/token/regex\nnames: C<TWEAK>, C<BUILD>, C<BUILD-ALL> will throw another kind of exception if\nyou do that: C<Cannot find method 'match': no method cache and no\n.^find_method>, once again only slightly related to what is actually going on.\n\n=head1 Unfortunate generalization\n\n=head2 C<:exists> with more than one key\n\nLet's say you have a hash and you want to use C<:exists> on more than\none element:\n\n=begin code\nmy %h = a => 1, b => 2;\nsay ‘a exists’ if %h<a>:exists;   # ← OK; True\nsay ‘y exists’ if %h<y>:exists;   # ← OK; False\nsay ‘Huh‽’     if %h<x y>:exists; # ← WRONG; returns a 2-item list\n=end code\n\nDid you mean “if C<any> of them exists”, or did you mean that C<all>\nof them should exist? Use C<any> or C<all> L<C<Junction>|/type/Junction> to clarify:\n\n=begin code\nmy %h = a => 1, b => 2;\nsay ‘x or y’     if any %h<x y>:exists;   # ← RIGHT (any); False\nsay ‘a, x or y’  if any %h<a x y>:exists; # ← RIGHT (any); True\nsay ‘a, x and y’ if all %h<a x y>:exists; # ← RIGHT (all); False\nsay ‘a and b’    if all %h<a b>:exists;   # ← RIGHT (all); True\n=end code\n\nThe reason why it is always C<True> (without using a junction) is that\nit returns a list with L<C<Bool>|/type/Bool> values for each requested\nlookup. Non-empty lists always give C<True> when you L<C<Bool>|/type/Bool>ify them,\nso the check always succeeds no matter what keys you give it.\n\n=head2 Using C<[…]> metaoperator with a list of lists\n\nEvery now and then, someone gets the idea that they can use C<[Z]> to\ncreate the transpose of a list-of-lists:\n\n=begin code\nmy @matrix = <X Y>, <a b>, <1 2>;\nmy @transpose = [Z] @matrix; # ← WRONG; but so far so good ↙\nsay @transpose;              # OUTPUT: «[(X a 1) (Y b 2)]␤»\n=end code\n\nAnd everything works fine, until you get an input @matrix with\nI<exactly one> row (child list):\n\n=begin code\nmy @matrix = <X Y>,;\nmy @transpose = [Z] @matrix; # ← WRONG; ↙\nsay @transpose;              # OUTPUT: «[(X Y)]␤» – not the expected transpose [(X) (Y)]\n=end code\n\nThis happens partly because of the\nL<single argument rule|/language/functions#Slurpy_conventions>, and\nthere are other cases when this kind of a generalization may not work.\n\n\n=head2 Using [~] for concatenating a list of blobs\n\nThe L<C<~> infix operator|/routine/~#(Operators)_infix_~> can be used\nto concatenate L<C<Str>|/type/Str>s I<or> L<C<Blob>|/type/Blob>s. However, an empty list will\nI<always> be reduced to an empty L<C<Str>|/type/Str>. This is due to the fact that,\nin the presence of a list with no elements, the\nL<reduction|/language/operators#Reduction_operators> metaoperator\nreturns the\nL<identity element|/language/operators#Identity>\nfor the given operator. Identity element for C<~> is an empty string,\nregardless of the kind of elements the list could be populated with.\n\n=for code\nmy Blob @chunks;\nsay ([~] @chunks).raku; # OUTPUT: «\"\"␤»\n\n\nThis might cause a problem if you attempt to use the result while\nassuming that it is a Blob:\n\n=for code\nmy Blob @chunks;\nsay ([~] @chunks).decode;\n# OUTPUT: «No such method 'decode' for invocant of type 'Str'. Did you mean 'encode'?␤…»\n\n\nThere are many ways to cover that case. You can avoid C<[ ]>\nmetaoperator altogether:\n\n=for code\nmy @chunks;\n# …\nsay Blob.new: |«@chunks; # OUTPUT: «Blob:0x<>␤»\n\n\nAlternatively, you can initialize the array with an empty Blob:\n\n=for code\nmy @chunks = Blob.new;\n# …\nsay [~] @chunks; # OUTPUT: «Blob:0x<>␤»\n\nOr you can utilize L<C<||>|/language/operators#infix_%7C%7C > operator to\nmake it use an empty Blob in case the list is empty:\n\n=for code\nmy @chunks;\n# …\nsay [~] @chunks || Blob.new; # OUTPUT: «Blob:0x<>␤»\n\n\nPlease note that a similar issue may arise when reducing lists with\nother operators.\n\n=head1 Maps\n\n=head2 Beware of nesting L<C<Map>|/type/Map>s in sink context\n\nMaps apply an expression to every element of a L<C<List>|/type/List> and return a L<C<Seq>|/type/Seq>:\n\n    say <þor oðin loki>.map: *.codes; # OUTPUT: «(3 4 4)␤»\n\nMaps are often used as a compact substitute for a loop, performing some\nkind of action in the map code block:\n\n    <þor oðin loki>.map: *.codes.say; # OUTPUT: «3␤4␤4␤»\n\nThe problem might arise when maps are nested and L<in a sink\ncontext|/language/contexts#Sink>.\n\n    <foo bar ber>.map: { $^a.comb.map: { $^b.say}}; # OUTPUT: «»\n\nYou might expect the innermost map to I<bubble> the result up to the outermost\nmap, but it simply does nothing. Maps return L<C<Seq>|/type/Seq>s, and in sink context the\ninnermost map will iterate and discard the produced values, which is why it\nyields nothing.\n\nSimply using C<say> at the beginning of the sentence will save the result from\nsink context:\n\n    say <foo bar ber>.map: *.comb.map: *.say ;\n    # OUTPUT: «f␤o␤o␤b␤a␤r␤b␤e␤r␤((True True True) (True True True) (True True True))␤»\n\nHowever, it will not be working as intended; the first C«f␤o␤o␤b␤a␤r␤b␤e␤r␤» is\nthe result of the innermost C<say>, but then L<C<say>|/routine/say#(Mu)_method_say> returns a\nL<C<Bool>|/type/Bool>, C<True> in this case. Those C<True>s are\nwhat get printed by the outermost C<say>, one for every letter. A much better\noption would be to C<flat>ten the outermost sequence:\n\n    <foo bar ber>.map({ $^a.comb.map: { $^b.say}}).flat\n    # OUTPUT: «f␤o␤o␤b␤a␤r␤b␤e␤r␤»\n\nOf course, saving C<say> for the result will also produce the intended result,\nas it will be saving the two nested sequences from void context:\n\n    say <foo bar ber>.map: { $^þ.comb }; # OUTPUT: « ((f o o) (b a r) (b e r))␤»\n\n=head1 Smartmatching\n\nThe\nL<smartmatch operator|/language/operators#index-entry-smartmatch_operator>\nshortcuts to the right-hand side I<accepting> the left-hand side. This\nmay cause some confusion.\n\n=head2 Smartmatch and L<C<WhateverCode>|/type/WhateverCode>\n\nUsing L<C<WhateverCode>|/type/WhateverCode> in the left-hand side of a smartmatch does not\nwork as expected, or at all:\n\n=begin code\nmy @a = <1 2 3>;\nsay @a.grep( *.Int ~~ 2 );\n# OUTPUT: «Cannot use Bool as Matcher with '.grep'.  Did you mean to\n# use $_ inside a block?␤␤␤»\n=end code\n\nThe error message does not make a lot of sense. It does, however, if you\nput it in terms of the C<ACCEPTS> method: that code is equivalent to\nC<2.ACCEPTS( *.Int )>, but C<*.Int> cannot be\nL<coerced to L<C<Numeric>|/type/Numeric>|/type/Numeric#method_ACCEPTS>,\nbeing as it is a L<C<Block>|/type/Block>.\n\nSolution: don't use L<C<WhateverCode>|/type/WhateverCode> in the left-hand side of a\nsmartmatch:\n\n=begin code\nmy @a = <1 2 3>;\nsay @a.grep( 2 ~~ *.Int ); # OUTPUT: «(2)␤»\n=end code\n\n=head1 Libraries\n\n=head2 Filesystem repositories\n\nAdding large directories to the library search path can negatively impact\nmodule load time, even when the module being loaded doesn't reside in any of\nthe added paths.  This is because the compiler needs to traverse and checksum\nall relevant files in the tree before loading the requested module, unless the\ndirectory contains a C<META6.json> file.\n\nThere are three common ways to add directories to the search path:\n\n=item Providing a switch to Raku on the command line: C<$ raku -Idir>\n\n=item Setting an environment variable: C<$ env RAKULIB=dir raku>\n\n=item Using the C<lib> L<pragma|/language/pragmas#lib> (i.e. C<use lib 'dir'>)\n\nPerformance penalties are evident when I<any> of these methods are used to add\nan especially large or deeply nested directory.  For example, adding\nC</usr/lib> to the search path on a typical Unix machine has a perceptible\nperformance impact when loading a module,\n\n=begin code :lang<text>\n    $ time raku -e 'use Test'\n    real    0m0.511s\n    user    0m0.554s\n    sys     0m0.118s\n\n    # no penalty, since we don't load anything:\n    $ time raku -I/usr/lib -e ''\n    real    0m0.247s\n    user    0m0.254s\n    sys     0m0.066s\n\n    $ time raku -I/usr/lib -e 'use Test'\n    real    0m6.344s\n    user    0m6.232s\n    sys     0m0.356s\n\n    $ time raku -e 'use lib \"/usr/lib\"; use Test'\n    real    0m6.555s\n    user    0m6.445s\n    sys     0m0.326s\n\n    $ time env RAKULIB=/usr/lib raku -e 'use Test'\n    real    0m6.479s\n    user    0m6.368s\n    sys     0m0.383s\n=end code\n\nNote that the increased runtime occurs even when requesting modules that were\nalready installed elsewhere (L<C<Test>|/type/Test> is provided as part of Rakudo but\nC</usr/lib> was nevertheless scanned before loading it).\n\nThe best way to avoid this trap is to install modules that reside in large\ntrees and omit those directories from the search path altogether.\nAlternatively, adding a C<META6.json> file to a tree will prevent time\nconsuming traversals.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/typesystem.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Type system\n\n=SUBTITLE Introduction to the type system of Raku\n\n=head1 Definition of a Raku type\n\nA type defines a new object by creating a type object that provides an\ninterface to create instances of objects or to check values against. Any type\nobject is a subclass of L<C<Any>|/type/Any> or L<C<Mu>|/type/Mu>. Introspection\nmethods are provided via inheritance from those base classes and the\nintrospection metamethods (L<.^|/language/operators#methodop_.^>). A new type is\nintroduced to the current scope by one of the following type declarators at\ncompile time or with the L<metaobject protocol|/language/mop> at runtime. All\ntype names must be unique in their scope.\n\n=head2 Default types\n\nIf no type is provided by the user Raku assumes the type to be L<C<Any>|/type/Any>. This\nincludes L<containers|/language/containers>, base-classes,\nL<parameters|/language/signatures#Type_constraints> and return types.\n\n    my $a = 1;\n    $a = Nil;\n    say $a.^name;\n    # OUTPUT: «Any␤»\n\n    class C {};\n    say C.^parents(:all);\n    # OUTPUT: «((Any) (Mu))␤»\n\nFor containers the default type is L<C<Any>|/type/Any> but the default type constraint is\nL<C<Mu>|/type/Mu>. Please note that binding replaces the container, not just the value. The\ntype constraint may change in this case.\n\n=head2 Type objects\n\nTo test if an object is a type object, use\nL<smartmatch|/language/operators#index-entry-smartmatch_operator>\nagainst a type constrained with a\nL<type smiley|/language/signatures#Constraining_argument_definiteness> or\nL«C<.DEFINITE>|/language/mop#DEFINITE» method:\n\n=begin code :ok-test<WHAT>\nmy $a = Int;\nsay $a ~~ Mu:U;\n# OUTPUT: «True␤»\nsay not $a.DEFINITE;\n# OUTPUT: «True␤»\n=end code\n\nC<.DEFINITE> will return C<True> if the invocant is an instance. If it returns\nC<False>, then the invocant is a type object.\n\n=head3 Undefinedness\n\nUndefined objects maintain type information in Raku. Type objects are used to\nrepresent both undefinedness and the type of the undefined value. To provide a\ngeneral undefined value use L<C<Any>|/type/Any>. If differentiation from L<C<Any>|/type/Any>,\nthe default type for containers and arguments, is required use L<C<Mu>|/type/Mu>.\n\nInstances of objects created by L<.CREATE|/type/Mu#method_CREATE> are by\nconvention defined. The method L<.defined|/type/Mu#routine_defined> will return\nC<Bool::True> to indicate definedness. The exceptions to that rule are\nL<C<Nil>|/type/Nil> and L<C<Failure>|/type/Failure>. Please note that any object is\nable to overload C<.defined> and as such can carry additional information.\nAlso, Raku makes a clear distinction between definedness and trueness. Many\nvalues are defined even though they carry the meaning of wrongness or\nemptiness. Such values are C<0>, L<Bool::False|/type/Bool>,\nL<()|/language/operators#term_(_)> (empty list) and L<C<NaN>|/type/Num#NaN>.\n\nValues can become undefined at runtime via L<mixin|/language/operators#infix_but>.\n\n    my Int $i = 1 but role :: { method defined { False } };\n    say $i // \"undefined\";\n    # OUTPUT: «undefined␤»\n\nTo test for definedness call C<.defined>, use\nL<//|/language/operators#infix_//>,\n L<with/without|/language/control#with_orwith_without> and\nL<signatures|/language/signatures#Constraining_argument_definiteness>.\n\n=head3 Coercion\n\nTurning one type into another is done with coercion methods that have the same\nname as the target type. This convention is made mandatory by\nL<Signatures|/language/signatures#Coercion_type>. The source type has to know how to\nturn itself into the target type. To allow built-in types to turn themselves\ninto user defined types use\nL<augment|/language/variables#The_augment_declarator> or the\nL<MOP|/language/mop>.\n\n    class C {\n        has $.int;\n        method this-is-c { put 'oi' x $!int ~ '‽' }\n    }\n\n    use MONKEY-TYPING;\n    augment class Int {\n        method C { C.new(:int(self))}\n    }\n\n    my $i = 10;\n    $i.=C;\n    $i.this-is-c();\n    # OUTPUT: «oioioioioioioioioioi‽␤»\n\nRaku provides methods defined in L<C<Cool>|/type/Cool> to convert to a target\ntype before applying further operations. Most built-in types descend from\nL<C<Cool>|/type/Cool> and as such may provide implicit coercion that may be undesired. It is\nthe responsibility of the user to care about trap-free usage of those\nmethods.\n\n    my $whatever = \"123.6\";\n    say $whatever.round;\n    # OUTPUT: «124␤»\n    say <a b c d>.starts-with(\"ab\");\n    # OUTPUT: «False␤»\n\n=head1 Type declarators\n\nType declarators introduce a new type into the given scope. Nested scopes can\nbe separated by C<::>. New L<packages|/language/packages> are created\nautomatically if no such scope exists already.\n\n    class Foo::Bar::C {};\n    put Foo::Bar::.keys;\n    # OUTPUT: «C␤»\n\nX«|Syntax,... (forward declaration)»\nX«Forward declarations|Language,Forward declarations» can be provided with a block containing only C<...>,\nthe L<\"stub\" operator|/language/operators#listop_...>. The\ncompiler will check at the end of the current scope if the type is defined.\n\n    class C {...}\n    # many lines later\n    class C { has $.attr }\n\n=head2 C<class>\n\nThe C<class> declarator creates a compile time construct that is compiled into a\ntype object. The latter is a simple Raku object and provides methods to\nconstruct instances by executing initializers and sub methods to fill all\nattributes declared in a class, and any parent class, with values. Initializers\ncan be provided with the declaration of attributes or in constructors. It's the\nresponsibility of the L<C<Metamodel::ClassHOW>|/type/Metamodel::ClassHOW> to know\nhow to run them. This is the only magic part of building objects in Raku. The\ndefault parent type is L<C<Any>|/type/Any>, which in turn inherits from L<C<Mu>|/type/Mu>. The latter\nprovides the default constructor C<.new> which is named like this by convention.\nAside from this, C<.new> does not carry any special meaning nor is treated in\nany special way.\n\nFor more information how to use classes see the L<Classes and objects|/language/classtut>\ntutorial.\n\n=head3 Mixins\n\nThe type introduced by C<class> can be extended with\nL«infix:<but>|/language/operators#infix_but» at runtime. The original type is\nnot modified, instead a new type object is returned and can be stored in\na container that type checks successful against the original type or the role\nthat is mixed in.\n\n    class A {}\n    role R { method m { say 'oi‽' } }\n    my R $A = A but R;\n    my $a1 = $A.new;\n    $a1.m;\n    say [$A ~~ R, $a1 ~~ R];\n    # OUTPUT: «oi‽␤[True True]␤»\n\n=head3 Introspection\n\n=head4 Metaclass\n\nTo test if a given type object is a class, test the metaobject method C<.HOW>\nagainst L<C<Metamodel::ClassHOW>|/type/Metamodel::ClassHOW>.\n\n    class C {};\n    say C.HOW ~~ Metamodel::ClassHOW;\n    # OUTPUT: «True␤»\n\n=head3 Private attributes\n\nPrivate L<C<Attribute>|/type/Attribute>s are addressed with any of the twigils\nC<$!>, C<@!> and C<%!>. They do not have public accessor methods generated\nautomatically.  As such they can not be altered from outside the class they are\ndefined in.\n\n    class C {\n        has $!priv;\n        submethod BUILD { $!priv = 42 }\n    };\n\n    say (.name, .package, .has_accessor) for C.new.^attributes;\n    # OUTPUT: «($!priv (C) False)␤»\n\nX«|Syntax,method (declarator)»\n=head3 Methods\n\nThe C<method> declarator defines objects of type L<C<Method>|/type/Method> and\nbinds them to the provided name in the scope of a class. Methods in a class are\nC<has> scoped by default. Methods that are C<our> scoped are not added to the\nmethod cache by default and as such can not be called with the accessor sigil\nC<$.>. Call them with their fully qualified name and the invocant as the\nfirst argument.\n\n=head4 Inheritance and multis\n\nFor a normal method in a subclass, there is no competition from multi methods in a parent class.\n\n    class Parent {\n        multi method m(Numeric $i){ say 'Numeric' }\n        multi method m(Int $i){ say 'Int' }\n    }\n\n    class Child is Parent {\n        method m(Numeric $i){ say 'Child::Numeric' }\n    }\n\n    my Int $i;\n    Child.new.m($i);\n    # OUTPUT: «Child::Numeric␤»\n\nX«|Syntax,only method»\n=head4 Only method\n\nTo explicitly state that a method is not a multi method use the C<only> method\ndeclarator.\n\n=for code :skip-test<compile time error>\nclass C {\n    only method m {};\n    multi method m {};\n};\n# OUTPUT: «X::Comp::AdHoc: Cannot have a multi candidate for 'm' when an only method is also in the package 'C'␤»\n\n=head4 submethod BUILD\n\nThe L<submethod|/type/Submethod> C<BUILD> is (indirectly) called by\nL<.bless|/type/Mu#method_bless>. It\nis meant to set private and public attributes of a class and receives all named\nattributes passed into C<.bless>. The default\nconstructor L<.new|/type/Mu#method_new> defined in L<C<Mu>|/type/Mu> is the method that\ninvokes C<.bless>. Given that public accessor methods are not available in C<BUILD>,\nyou must use private attribute notation instead.\n\n    class C {\n        has $.attr;\n        submethod BUILD (:$attr = 42) {\n            $!attr = $attr\n        };\n        multi method new($positional) {\n            self.bless(:attr($positional), |%_)\n       }\n    };\n\n    C.new.say; C.new('answer').say;\n    # OUTPUT: «C.new(attr => 42)␤\n    #          C.new(attr => \"answer\")␤»\n\nX<|Language,FALLBACK (method)>\n=head4 Fallback method\n\nA method with the special name C<FALLBACK> will be called when other means to\nresolve the name produce no result. The first argument holds the name and all\nfollowing arguments are forwarded from the original call. Multi methods and\nL«sub-signatures|/language/signatures#Sub-signatures» are supported.\n\n    class Magic {\n        method FALLBACK ($name, |c(Int, Str)) {\n        put \"$name called with parameters {c.raku}\"  }\n    };\n    Magic.new.simsalabim(42, \"answer\");\n\n    # OUTPUT: «simsalabim called with parameters ⌈\\(42, \"answer\")⌋␤»\n\nX<|Language,DEFINITE (reserved method)>X<|Language,HOW (reserved method)>\nX<|Language,REPR (reserved method)>X<|Language,VAR (reserved method)>\nX<|Language,WHAT (reserved method)>X<|Language,WHERE (reserved method)>\nX<|Language,WHICH (reserved method)>X<|Language,WHO (reserved method)>\n=head4 Reserved method names\n\nSome built-in introspection methods are actually special syntax provided by the\ncompiler, namely C<WHAT>, C<WHO>, C<HOW>, C<VAR>,\nand (since Rakudo v2026.01) C<WHERE>, C<DEFINITE>, and C<REPR>.\nDeclaring methods with those names will silently fail. A dynamic call will work,\nwhich allows to call methods from foreign objects.\n\n=begin code :ok-test<WHAT>\nclass A {\n    method WHAT { \"ain't gonna happen\" }\n};\n\nsay A.new.WHAT;    # OUTPUT: «(A)␤»\nsay A.new.\"WHAT\"() # OUTPUT: «ain't gonna happen␤»\n=end code\n\n=head4 Methods in package scope\n\nAny C<our> scoped method will be visible in the package scope of a class.\n\n    class C {\n        our method packaged {};\n        method loose {}\n    };\n    say C::.keys\n    # OUTPUT: «(&packaged)␤»\n\n=head4 Setting attributes with namesake variables and methods\n\nInstead of writing C«attr => $attr» or C<:attr($attr)>, you can save some\ntyping if the variable (or method call) you're setting the attribute with\nshares the name with the attribute:\n\n    class A { has $.i = 42 };\n    class B {\n        has $.i = \"answer\";\n        method m() { A.new(:$.i) }\n        #                  ^^^^  Instead of i => $.i or :i($.i)\n    };\n    my $a = B.new.m;\n    say $a.i; # OUTPUT: «answer␤»\n\nSince C<$.i> method call is named C<i> and the attribute is also named C<i>,\nRaku lets us shortcut. The same applies to C<:$var>, C<:$!private-attribute>,\nC<:&attr-with-code-in-it>, and so on.\n\n=head3 trait C<is nodal>\n\nMarks a L<C<List>|/type/List> method to indicate to L<hyperoperators|/language/operators#Hyper_operators> to not descend into inner\nL<C<Iterable>|/type/Iterable>s to call this method. This trait generally isn't\nsomething end users would be using, unless they're subclassing or augmenting\ncore L<C<List>|/type/List> type.\n\nIn order to demonstrate the difference consider the following examples, the first\nusing a method (C<elems>) that C<is nodal> and the second using a method (L<C<Int>|/type/Int>)\nwhich is not nodal.\n\n    say ((1.0, \"2\", 3e0), [^4], '5')».elems; # OUTPUT: «(3, 4, 1)␤»\n    say ((1.0, \"2\", 3e0), [^4], '5')».Int    # OUTPUT: «((1 2 3) [0 1 2 3] 5)␤»\n\n=head3 trait X<C<handles>|Traits,handles trait>\n\n    multi trait_mod:<handles>(Attribute:D $target, $thunk)\n\nThe L<trait|/type/Sub#Traits> C<handles> applied to an attribute of a class will\ndelegate all calls to the provided method name to the method with the same name\nof the attribute. The object referenced by the attribute must be initialized. A\ntype constraint for the object that the call is delegated to can be provided.\n\n    class A      { method m(){ 'A::m has been called.' } }\n    class B is A { method m(){ 'B::m has been called.' } }\n    class C {\n        has A $.delegate handles 'm';\n        method new($delegate){ self.bless(delegate => $delegate) }\n    };\n    say C.new(B.new).m(); # OUTPUT: «B::m has been called.␤»\n\nInstead of a method name, a L<C<Pair>|/type/Pair> (for renaming), a list of names or\nL<C<Pair>|/type/Pair>s, a L<C<Regex>|/type/Regex> or a L<C<Whatever>|/type/Whatever> can be provided. In the latter case\nexisting methods, both in the class itself and its inheritance chain, will take\nprecedence. If even local X«C<FALLBACK>|Language,FALLBACK (trait handles)»s should be\nsearched, use a L<C<HyperWhatever>|/type/HyperWhatever>.\n\n    class A {\n        method m1(){ 'A::m1 has been called.' }\n        method m2(){ 'A::m2 has been called.' }\n    }\n\n    class C {\n        has $.delegate handles <m1 m2> = A.new()\n    }\n    say C.new.m2; # OUTPUT: «A::m2 has been called.␤»\n\n    class D {\n        has $.delegate handles /m\\d/ = A.new()\n    }\n    say D.new.m1; # OUTPUT: «A::m1 has been called.␤»\n\n    class E {\n        has $.delegate handles (em1 => 'm1') = A.new()\n    }\n    say E.new.em1; # OUTPUT: «A::m1 has been called.␤»\n\n    class F {\n      # Delegates all methods from A\n      has A $.delegate handles *;\n    }\n    say F.new.m1; # OUTPUT: «A::m1 has been called.␤»\n    say F.new.m2; # OUTPUT: «A::m2 has been called.␤»\n\n=head3  X<trait C<is>|Traits,is (class)>\n\n    multi trait_mod:<is>(Mu:U $child, Mu:U $parent)\n\nThe L<trait|/type/Sub#Traits> C<is> accepts a type object to be\nadded as a parent class of a class in its definition. To allow multiple\ninheritance the trait can be applied more than once. Adding parents to a class\nwill import their methods into the target class. If the same method name occurs\nin multiple parents, the first added parent will win.\n\nIf no C<is> trait is provided the default of L<C<Any>|/type/Any> will be used\nas a parent class. This forces all Raku objects to have the same set of basic\nmethods to provide an interface for introspection and coercion to basic types.\n\n    class A {\n        multi method from-a(){ 'A::from-a' }\n    }\n    say A.new.^parents(:all).raku;\n    # OUTPUT: «(Any, Mu)␤»\n\n    class B {\n        method from-b(){ 'B::from-b ' }\n        multi method from-a(){ 'B::from-A' }\n    }\n\n    class C is A is B {}\n    say C.new.from-a();\n    # OUTPUT: «A::from-a␤»\n\n=head3 trait X«C<is rw>|Traits,is rw (class)»\n\n    sub trait_mod:<is>(Mu:U $type, :$rw!)\n\nThe L<trait|/type/Sub#Traits> C<is rw> on a class will create writable accessor\nmethods on all public attributes of that class.\n\n    class C is rw {\n        has $.a;\n    };\n    my $c = C.new.a = 42;\n    say $c; # OUTPUT: «42␤»\n\n=head3 trait C<is required>\n\n    multi trait_mod:<is>(Attribute $attr, :$required!)\n    multi trait_mod:<is>(Parameter:D $param, :$required!)\n\nMarks a class or roles attribute as required. If the attribute is not\ninitialized at object construction time throws\nL<C<X::Attribute::Required>|/type/X::Attribute::Required>.\n\n    class Correct {\n        has $.attr is required;\n    }\n    say Correct.new(attr => 42);\n    # OUTPUT: «Correct.new(attr => 42)␤»\n\n    class C {\n        has $.attr is required;\n    }\n    C.new;\n    CATCH { default { say .^name => .Str } }\n    # OUTPUT: «X::Attribute::Required => The attribute '$!attr' is required, but you did not provide a value for it.␤»\n\nNote a class with a private attribute will give the same error:\n\n    class D {\n        has $!attr is required;\n    }\n    D.new;\n    CATCH { default { say .^name => .Str } }\n    # OUTPUT: «X::Attribute::Required => The attribute '$!attr' is required, but you did not provide a value for it.␤»\n\nYou can provide a reason why it's required as an argument to C<is required>\n\n=for code\nclass Correct {\n    has $.attr is required(\"it's so cool\")\n};\nsay Correct.new();\n# OUTPUT: «The attribute '$!attr' is required because it's so cool,␤but you did not provide a value for it.␤»\n\n=head3 trait C<hides>\n\nThe trait C<hides> provides inheritance without being subject to\nL<re-dispatching|/language/functions#Re-dispatching>.\n\n    class A {\n        method m { say 'i am hidden' }\n    }\n    class B hides A {\n        method m { nextsame }\n        method n { self.A::m }\n    };\n\n    B.new.m;  # No output\n    B.new.n;  # OUTPUT: «i am hidden␤»\n\nThe trait C<is hidden> allows a class to hide itself from\nL<re-dispatching|/language/functions#Re-dispatching>.\n\n    class A is hidden {\n        method m { say 'i am hidden' }\n    }\n    class B is A {\n        method m { nextsame }\n        method n { self.A::m }\n    }\n\n    B.new.m; # No output\n    B.new.n; # OUTPUT: «i am hidden␤»\n\nClasses declared with C<is hidden> also generate slightly different method\nsignatures.  To facilitate re-dispatch, typical methods are automatically\nprovided with an extra C<*%_> parameter that L<captures extra named\narguments|/type/Method#index-entry-*%___(extra_named_arguments)>.  Because classes\ndeclared with C<is hidden> don't participate in re-dispatch, their methods don't\nreceive this extra parameter.\n\n=head3 trait C<trusts>\n\nTo allow one class to access the private methods of another class use the trait\nC<trusts>. A forward declaration of the trusted class may be required.\n\n    class B {...};\n    class A {\n        trusts B;\n        has $!foo;\n        method !foo { return-rw $!foo }\n        method raku { \"A.new(foo => $!foo)\" }\n    };\n    class B {\n        has A $.a .= new;\n        method change { $!a!A::foo = 42; self }\n    };\n    say B.new.change;\n    # OUTPUT: «B.new(a => A.new(foo => 42))␤»\n\n=head3 Augmenting a class\n\nTo add methods and attributes to a class at compile time use C<augment> in\nfront of a class definition fragment. The compiler will demand the pragmas\nC<use MONKEY-TYPING> or C<use MONKEY> early in the same scope. Please note that\nthere may be performance implications, hence the pragmas.\n\n    use MONKEY; augment class Str {\n        method mark(Any :$set){\n            state $mark //= $set; $mark\n        }\n    };\n    my $s = \"42\";\n    $s.mark(set => \"answer\");\n    say $s.mark\n    # OUTPUT: «answer␤»\n\nThere are few limitations of what can be done inside the class fragment. One of\nthem is the redeclaration of a method or sub into a multi. Using added\nattributes is not implemented. Please note that adding a multi candidate\nthat differs only in its named parameters will add that candidate behind the\nalready defined one and as such it won't be picked by the dispatcher.\n\n=head2 C<role>\n\nX<|Language,role (typesystem)>\nRoles are class fragments, which allow the definition of interfaces that are\nshared by classes. The C<role> declarator also introduces a type object that\ncan be used for type checks. Roles can be mixed into classes and objects at\nruntime and compile time. The C<role> declarator returns the created type\nobject thus allowing the definition of anonymous roles and in-place mixins.\n\n    role Serialize {\n        method to-string { self.Str }\n        method to-number { self.Num }\n    }\n\n    class A does Serialize {}\n    class B does Serialize {}\n\n    my Serialize @list;\n    @list.push: A.new;\n    @list.push: B.new;\n\n    say @list».to-string;\n    # OUTPUT: «[A<57192848> B<57192880>]␤»\n\nUse C<...> as the only element of a method body to declare a method to be\nabstract. Any class getting such a method mixed in has to overload it. If the\nmethod is not overloaded before the end of the compilation unit\nL<C<X::Comp::AdHoc>|/type/X::Comp::AdHoc> will be thrown.\n\n    EVAL 'role R { method overload-this(){...} }; class A does R {}; ';\n    CATCH { default { say .^name, ' ', .Str } }\n    # OUTPUT: «X::Comp::AdHoc Method 'overload-this' must be implemented by A because it is required by roles: R.␤»\n\n=head3 Auto-punning\n\nA role can be used instead of a class to create objects. Since roles can't\nexist at runtime, a class of the same name is created that will type check\nsuccessful against the role.\n\n    role R { method m { say 'oi‽' } };\n    R.new.^mro.say;\n    # OUTPUT: «((R) (Any) (Mu))␤»\n    say R.new.^mro[0].HOW.^name;\n    # OUTPUT: «Perl6::Metamodel::ClassHOW␤»\n    say R.new ~~ R;\n    # OUTPUT: «True␤»\n\n=head3 trait C<does>\n\nThe trait C<does> can be applied to roles and classes providing compile time\nmixins. To refer to a role that is not defined yet, use a forward declaration.\nThe type name of the class with mixed in roles does not reflect the mixin, a\ntype check does. If methods are provided in more than one mixed in role, the\nmethod that is defined first takes precedence. A list of roles separated by\ncomma can be provided. In this case conflicts will be reported at compile time.\n\n    role R2 {...};\n    role R1 does R2 {};\n    role R2 {};\n    class C does R1 {};\n\n    say [C ~~ R1, C ~~ R2];\n    # OUTPUT: «[True True]␤»\n\nFor runtime mixins see L<but|/language/operators#infix_but> and L<does|/language/operators#infix_does>.\n\n=head3 Parameterized\n\nRoles can be provided with parameters in-between C<[]> behind a roles name.\n\n    role R[$d] { has $.a = $d };\n    class C does R[\"default\"] { };\n\n    my $c = C.new;\n    say $c;\n    # OUTPUT: «C.new(a => \"default\")␤»\n\nParameters can have type constraints, C<where> clauses are not supported for\ntypes but can be implemented via L<C<subset>s|#subset>.\nX<|Language,Type Capture (role)>L<Type captures|/language/signatures#Type_captures> are supported.\n\n    class A {};\n    class B {};\n    subset A-or-B where * ~~ A|B;\n    role R[A-or-B ::T] {};\n    R[A.new].new;\n\nDefault parameters can be provided.\n\n    role R[$p = fail(\"Please provide a parameter to role R\")] {};\n    my $i = 1 does R;\n    CATCH { default { say .^name, ': ', .Str} }\n    # OUTPUT: «X::AdHoc: Could not instantiate role 'R':␤Please provide a parameter to role R␤»\n\n=head3 As type constraints\n\nRoles can be used as type constraints wherever a type is expected. If a role is\nmixed in with C<does> or C<but>, its type-object is added to the type-object\nlist of the object in question. If a role is used instead of a class (using\nauto-punning), the auto-generated class' type-object, of the same name as the\nrole, is added to the inheritance chain.\n\n=begin code\nrole Unitish[$unit = fail('Please provide a SI unit quantifier as a parameter to the role Unitish')] {\n    has $.SI-unit-symbol = $unit;\n    method gist {\n        given self {\n            # ...\n            when * < 1 { return self * 1000 ~ 'm' ~ $.SI-unit-symbol }\n            when * < 1000 { return self ~ $.SI-unit-symbol }\n            when * < 1_000_000 { return self / 1_000 ~ 'k' ~ $.SI-unit-symbol }\n            # ...\n        }\n    }\n}\n\nrole SI-second   does Unitish[<s>] {}\nrole SI-meter    does Unitish[<m>] {}\nrole SI-kilogram does Unitish[<g>] {}\n\nsub postfix:<s>(Numeric $num) { ($num) does SI-second }\nsub postfix:<m>(Numeric $num) { ($num) does SI-meter }\nsub postfix:<g>(Numeric $num) { ($num) does SI-kilogram }\nsub postfix:<kg>(Numeric $num){ ($num * 1000) does SI-kilogram }\n\nconstant g = 9.806_65;\n\nrole SI-Newton does Unitish[<N>] {}\n\nmulti N(SI-kilogram $kg, SI-meter $m, SI-second $s --> SI-Newton ){ ($kg * ($m / $s²)) does SI-Newton }\nmulti N(SI-kilogram $kg --> SI-Newton)                            { ($kg * g) does SI-Newton }\n\nsay [75kg, N(75kg)];\n# OUTPUT: «[75kg 735.49875kN]␤»\nsay [(75kg).^name, N(75kg).^name];\n# OUTPUT: «[Int+{SI-kilogram} Rat+{SI-Newton}]␤»\n=end code\n\n=head2 X<C<enum>|Reference,Enumeration>\n\nX<|Reference,Enums>\nX<|Syntax,enum>\nEnumerations provide constant key-value-pairs with an associated type. Any key\nis of that type and injected as a symbol into the current scope. If the symbol\nis used, it is treated as a constant expression and the symbol is replaced with\nthe value of the enum-pair. Any Enumeration inherits methods from the role\nL<C<Enumeration>|/type/Enumeration>. Complex expressions for generating\nkey-value pairs are not supported. In general, an C<enum> is a L<C<Map>|/type/Map>\nwhose elements have the L<C<Enumeration>|/type/Enumeration> role mixed in; this role includes, for\neach element, an index which creates an order on the map.\n\nStringification of the symbol, which is done automatically in string context and\nis exactly equal to its name, which is also the key of the enum-pair.\n\n    enum Names ( name1 => 1, name2 => 2 );\n    say name1, ' ', name2; # OUTPUT: «name1 name2␤»\n    say name1.value, ' ', name2.value; # OUTPUT: «1 2␤»\n\nComparing symbols will use type information and the value of the enum-pair. As\nvalue types L<C<Num>|/type/Num> and L<C<Str>|/type/Str> are supported.\n\n    enum Names ( name1 => 1, name2 => 2 );\n    sub same(Names $a, Names $b){\n       $a eqv $b\n    }\n\n    say same(name1, name1); # OUTPUT: «True␤»\n    say same(name1, name2); # OUTPUT: «False␤»\n    my $a = name1;\n    say $a ~~ Names; # OUTPUT: «True␤»\n    say $a.^name;    # OUTPUT: «Names␤»\n\nAll keys have to be of the same type.\n\n    enum Mass ( mg => 1/1000, g => 1/1, kg => 1000/1 );\n\n    say Mass.enums;\n    # OUTPUT: «Map.new((g => 1, kg => 1000, mg => 0.001))␤»\n\nAnd you can use any kind of symbol:\n\n    enum Suit <♣ ♦ ♥ ♠>;\n\nAs long as you refer to that symbol using the full syntax:\n\n=for code :preamble<< enum Suit<♣> >>\nsay Suit::<♣>; # OUTPUT: «♣␤»\nmy $heart = '♥';\nsay Suit::«$heart»; # OUTPUT: «♥␤»\n\nAttempting to access unicode enum keys without said syntax will result in an\nerror:\n\n=for code :skip-test<example of bad code>\nsay ♣ ; # OUTPUT: «(exit code 1) ===SORRY!===␤Argument to \"say\" seems to be malformed…\n\nIf no value is given L<C<Int>|/type/Int> will be assumed as the values type and incremented\nby one per key starting at zero. As enum key types L<C<Int>|/type/Int>, L<C<Num>|/type/Num>, L<C<Rat>|/type/Rat> and\nL<C<Str>|/type/Str> are supported.\n\n    enum Numbers <one two three four>;\n\n    say Numbers.enums;\n    # OUTPUT: «Map.new((four => 3, one => 0, three => 2, two => 1))␤»\n\nA different starting value can be provided.\n\n    enum Numbers «:one(1) two three four»;\n\n    say Numbers.enums;\n    # OUTPUT: «Map.new((four => 4, one => 1, three => 3, two => 2))␤»\n\nYou can also do this with the B<()> form of the initializer, but will need to\nquote keys that do not have a value:\n\n    enum Numbers (\n      one => 1,\n      'two',\n      'three',\n      'four'\n    );\n\nEnums can also be anonymous, with the only difference with named C<enum>s being\nthat you cannot use it in L<C<Signature>|/type/Signature>s or to declare variables.\n\n    my $e = enum <one two three>;\n    say two;       # OUTPUT: «two␤»\n    say one.^name; # OUTPUT: «␤»\n    say $e.^name;  # OUTPUT: «Map␤»\n\nThere are various methods to get access to the keys and values of the symbols\nthat have been defined. All of them turn the values into L<C<Str>|/type/Str>, which may not\nbe desirable. By treating the enum as a package, we can get a list of types for\nthe keys.\n\n    enum E <one two>;\n    my @keys = E::.values;\n    say @keys.map: *.raku;\n    # OUTPUT: «(E::one E::two)␤» or «(E::two E::one)␤»\n\nNote that, as the output above indicates, the iteration order of enums\nis not guaranteed.  This is because the methods that \"iterate over\" an\nenum do not iterate I<directly> on the enum (which, after all, is not\niterable).  Instead, these iteration methods create a L<C<Map>|/type/Map> with the\nsame keys and values as the enum.  Because L<C<Map>|/type/Map>s provide only unordered,\niteration the iteration methods on an enum do as well.  If you need to\niterate an enum in order, you can sort on its C<value>, for example\nwith C<E.enums.sort(*.value)>.\n\nWith the use of B<()> parentheses, an enum can be defined using any\narbitrary dynamically defined list. The list should consist of Pair\nobjects:\n\nFor example, in file C<config> we have:\n\n=for code :lang<text>\na 1\nb 2\n\nWe can create an enum using it with this code:\n\n=for code :skip-test<needs filesystem>\nenum ConfigValues ('config'.IO.lines.map({ my ($key, $value) = $_.words; $key => $value }));\nsay ConfigValues.enums;          # OUTPUT: «Map.new((a => 1, b => 2))␤»\n\nFirstly, we read lines from C<config> file, split every line using\nC<words> method and return resulting pair for every line, thus\ncreating a List of Pairs.\n\n=head3 Typing Enums\n\nWhen declaring enums with an explicit scope, a type may be provided,\nwhich will be used to typecheck the enum's values:\n\n=for code\nmy Str enum Foo (foo => 'foo');\n\nAll enum pairs are typed as L<C<Enumeration>|/type/Enumeration>. In\naddition, when the enum values are typed as L<C<Numeric>|/type/Numeric>, L<C<Stringy>|/type/Stringy>, or a\ncombination of these two types, enum pairs also do the\nC<NumericEnumeration>, C<StringyEnumeration>, and\nC<NumericStringyEnumeration> roles respectively.  These simply determine\nhow enum pairs get stringified with the L<C<Str>|/type/Str> method.\n\nGiven that these types are roles, naturally you can provide your own\nroles when declaring an enum, which allows you to give them custom\nbehavior and state. For example, to make it simpler to check if a number\nmatches a flag in a bitmask enum, you could write a\nC<BitmaskEnumeration> role with an C<ACCEPTS> method to handle this via\nsmartmatching:\n\n=begin code\nrole BitmaskEnumeration {\n    multi method ACCEPTS(::?CLASS:D: Int:D $value --> Bool:D) {\n        so $value +& self.value\n    }\n}\n\nenum Flags does BitmaskEnumeration (\n    FLAG_FOO => 0b001,\n    FLAG_BAR => 0b010,\n    FLAG_BAZ => 0b100,\n);\n\nsay 0b111 ~~ FLAG_FOO & FLAG_BAR & FLAG_BAZ; # OUTPUT: «True␤»\n=end code\n\n=head3 Metaclass\n\nTo test if a given type object is an C<enum>, test the metaobject method\nC<.HOW> against L<C<Metamodel::EnumHOW>|/type/Metamodel::EnumHOW> or simply test\nagainst the L<C<Enumeration>|/type/Enumeration> role.\n\n    enum E(<a b c>);\n    say E.HOW ~~ Metamodel::EnumHOW; # OUTPUT: «True␤»\n    say E ~~ Enumeration;            # OUTPUT: «True␤»\n\n=head3 Methods\n\nSee the L«C<Enumeration>|/type/Enumeration» role for available methods on\nenum types and enum-pairs.\n\n=head3 Coercion\n\nIf you want to coerce the value of an enum element to its proper\nenum object, use the coercer with the name of the enum:\n\n    my enum A (sun => 42, mon => 72);\n    A(72).pair.say;   # OUTPUT: «mon => 72␤»\n    A(1000).say; # OUTPUT: «(A)␤»\n\nThe last example shows what happens if there is no enum-pair that includes that\nas a value.\n\n=head2 C<module>\n\nModules are usually one or more source files that expose Raku constructs,\nsuch as classes, roles, grammars, subroutines and variables. Modules are\nusually used for distributing Raku code as libraries which can be used in\nanother Raku program.\n\nFor a full explanation see L<Modules|/language/using-modules/introduction>\nand linked pages.\n\n=head2 C<package>\n\nPackages are nested namespaces of named program elements. Modules, classes and\ngrammars are all types of package.\n\nFor a full explanation see L<Packages|/language/packages>.\n\n=head2 C<grammar>\n\nGrammars are a specific type of class intended for parsing text. Grammars are\ncomposed of rules, tokens and regexes which are actually methods, since grammars\nare classes.\n\nFor a full explanation see L<Grammars|/language/grammars>.\n\n=head2 C<subset>\n\nA X<C<subset>|Syntax,subset> declares a new type that will re-dispatch to its base\ntype. If a L<C<where>|/language/signatures#index-entry-where_clause> clause is supplied any assignment\nwill be checked against the given code object.\n\n    subset Positive of Int where * > -1;\n    my Positive $i = 1;\n    $i = -42;\n    CATCH { default { put .^name,': ', .Str } }\n    # OUTPUT: «X::TypeCheck::Assignment: Type check failed in assignment to $i; expected Positive but got Int (-42)␤»\n\nSubsets can be used in signatures, e.g. by typing the output:\n\n    subset Foo of List where (Int,Str);\n    sub a($a, $b, --> Foo) { $a, $b }\n    # Only a List with the first element being an Int and the second a Str will pass the type check.\n    a(1, \"foo\");  # passes\n    a(\"foo\", 1);  # fails\n\nIf you skip the base type, it defaults to L<C<Any>|/type/Any>. So the following two are equivalent:\n\n=for code :preamble<class A {}; class B {}>\nsubset A-or-B where * ~~ A | B\n\n=for code :preamble<class A {}; class B {}>\nsubset A-or-B of Any where * ~~ A | B\n\nSubsets can be anonymous, allowing inline placements where a subset is required\nbut a name is neither needed nor desirable.\n\n    my enum E1 <A B>;\n    my enum E2 <C D>;\n    sub g(@a where { .all ~~ subset :: where E1|E2 } ) {\n        say @a\n    }\n    g([A, C]);\n    # OUTPUT: «[A C]␤»\n\nSubsets can be used to check types dynamically, which can be useful in conjunction\nwith L<require|/language/modules#require>.\nX<|Language,dynamic subset>\n\n=for code\nrequire ::('YourModule');\nsubset C where ::('YourModule::C');\n\nX«|Syntax,:ver<>»X«|Syntax,:auth<>»X«|Syntax,:api<>»\n=head1 Versioning, authorship, and API version.\n\nWhen you declare a type you can pass it a version, author, and/or API number,\nall of which you can subsequently introspect. The versioning, authorship,\nand/or API number of a type can be applied via the adverbs C«:ver<>»,\nC«:auth<>», and C«:api<>» respectively. All of them take a string as argument;\nfor C<:ver> the string is converted to a L«C«Version»|/type/Version» object, and\nfor C<:api> the string is converted into an\nL<allomorph|/language/glossary#Allomorph>\nL«C«IntStr»|/type/IntStr» object. C<:auth> generally takes the form\nC<hosting:ID>, as in C<github:github-user> or C<gitlab:gitlab-user>.\n\n\nTo query the version, author, and API version\nof a type use L<C<.^ver>|/type/Metamodel::Versioning#method_ver>,\nL<C<.^auth>|/type/Metamodel::Versioning#method_auth>, and\nL<C<.^api>|/type/Metamodel::Versioning#method_api> respectively, as illustrated\ndown below by querying a C<class>.\n\n    class C:ver<4.2.3>:auth<github:jane>:api<1> {}\n    say C.^ver;       # OUTPUT: «v4.2.3␤»\n    say C.^ver.parts; # OUTPUT: «(4 2 3)␤»\n    say C.^auth;      # OUTPUT: «github:jane␤»\n    say C.^api;       # OUTPUT: «1␤»\n\nIn a similar fashion, C<role>s, C<grammar>s, and C<module>s can be queried about\nthe aforementioned information.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/unicode.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Unicode\n\n=SUBTITLE Unicode support in Raku\n\nRaku has a high level of support of Unicode, with the latest version supporting\nUnicode 17.0. This document aims to be both an overview as well as description\nof Unicode features which don't belong in the documentation for routines and\nmethods.\n\nWhile it is specifically part of the VM used by C<Rakudo>, this\nL<overview|https://github.com/MoarVM/MoarVM/blob/master/docs/strings.asciidoc>\non MoarVM's internal representation of strings provides some interesting details.\n\n=begin nested\nFor security reasons, browsers (e.g.:  Firefox) may restrict the display of Unicode\nglyphs not in a trusted font, even if the OS has a font installed that displays the glyph.\nTo overcome this problem for Firefox, set the `privacy.fingerprintingProtection` config option to `False`.\n=end nested\n\n=head1 Filehandles and I/O\n\nX<|Reference,Normalization>\n=head2 Normalization\n\nRaku applies normalization by default to all input and output except for file\nnames, which are read and written as L<C<UTF8-C8>|#UTF8-C8>; graphemes, which are\nuser-visible forms of the characters, will use a normalized representation.\nFor example, the grapheme C<á> can be represented in two ways,\neither using one codepoint:\n\n=for code :lang<text>\ná (U+E1 \"LATIN SMALL LETTER A WITH ACUTE\")\n\nOr two codepoints:\n\n=for code :lang<text>\na +  ́ (U+61 \"LATIN SMALL LETTER A\" + U+301 \"COMBINING ACUTE ACCENT\")\n\nRaku will turn both these inputs into one codepoint, as is specified for\nNormalization Form C (B<X<NFC|Reference,NFC>>). In most cases this is useful and means\nthat two inputs that are equivalent are both treated the same. Unicode has a concept\nof canonical equivalence which allows us to determine the canonical form of a string,\nthus allowing us to properly compare strings and manipulate them without having to worry\nabout the text losing these properties. By default, any text you process or output\nfrom Raku will be in this “canonical” form, even when making modifications or\nconcatenations to the string (see below for how to avoid this). For more detailed information\nabout Normalization Form C and canonical equivalence, see the Unicode Foundation's page on\nL<Normalization and Canonical Equivalence|https://unicode.org/reports/tr15/#Canon_Compat_Equivalence>.\n\nOne case where we don't default to this is for the names of files. This is because\nthe names of files must be accessed exactly as the bytes are written on the disk.\n\nTo avoid normalization you can use a special encoding format called L<UTF8-C8|#UTF8-C8>.\nUsing this encoding with any filehandle will allow you to read the exact bytes as they are\non disk without normalization. They may look funny when printed out if you use a\nUTF8 handle. If you print it out to a handle where the output encoding is UTF8-C8,\nthen it will render as you would normally expect as a byte-for-byte exact\ncopy. More technical details on L<UTF8-C8|#UTF8-C8> on MoarVM are described below.\n\n=head2 X<UTF8-C8|Reference,UTF8-C8>\n\nX<UTF-8 Clean-8|Reference,UTF-8 Clean-8> is an encoder/decoder that primarily works as the UTF-8 one.\nHowever, upon encountering a byte sequence that will either not decode as valid\nUTF-8, or that would not round-trip due to normalization, it will use\nL<NFG synthetics|/language/glossary#NFG>\nto keep track of the original bytes involved.\nThis means that encoding back to UTF-8 Clean-8 will be able to recreate the\nbytes as they originally existed. The synthetics contain four codepoints:\n\n=item The codepoint 0x10FFFD (which is a private use codepoint)\n=item The codepoint 'x'\n=item The upper 4 bits of the non-decodable byte as a hex char (0..9A..F)\n=item The lower 4 bits as the non-decodable byte as a hex char (0..9A..F)\n\nUnder normal UTF-8 encoding, this means the unrepresentable characters will\ncome out as something like C<?xFF>.\n\nUTF-8 Clean-8 is used in places where MoarVM receives strings from the\nenvironment, command line arguments, and filesystem queries; for instance when decoding buffers:\n\n    say Buf.new(ord('A'), 0xFE, ord('Z')).decode('utf8-c8');\n    #  OUTPUT: «A􏿽xFEZ␤»\n\nYou can see how the two initial codepoints used by UTF8-C8 show up below right\nbefore the 'FE'. You can use this type of encoding to read files with unknown\nencoding:\n\n    my $test-file = \"/tmp/test\";\n    given open($test-file, :w, :bin) {\n      .write: Buf.new(ord('A'), 0xFA, ord('B'), 0xFB, 0xFC, ord('C'), 0xFD);\n      .close;\n    }\n\n    say slurp($test-file, enc => 'utf8-c8');\n    # OUTPUT: «(65 250 66 251 252 67 253)␤»\n\nReading with this type of encoding and encoding them back to UTF8-C8 will give you back the original bytes; this would not have been possible with the default UTF-8 encoding.\n\nPlease note that this encoding so far is not supported in the JVM implementation of Rakudo.\n\n=head1 Defining Unicode characters with Unicode codepoints and codepoint sequences\n\n=head2 Entering codepoints in strings by number\n\nX<|Syntax,\\c[N+] Unicode decimal codepoint>\nX<|Syntax,\\xN+ Unicode hexadecimal codepoint>\nX<|Syntax,\\oN+ Unicode octal codepoint>\nYou can insert Unicode codepoints by number (decimal or hexadecimal or octal).\nFor example, the character named \"latin capital letter ae with macron\" has\ndecimal codepoint 482, hexadecimal codepoint 0x1E2, and octal codepoint 0o742:\n\n    say \"\\c[482]\"; # OUTPUT: «Ǣ␤» (mnemonic aid: 'c - character name or decimal')\n    say \"\\x1E2\";   # OUTPUT: «Ǣ␤» (mnemonic aid: 'x - hexadecimal')\n    say \"\\o742\";   # OUTPUT: «Ǣ␤» (mnemonic aid: 'o - octal')\n\nNote any character following the hexadecimal and octal examples above will\nbe interpreted as part of the conversion unless it is not valid for the number type.\nFor example:\n\n    say \"\\x1E2\";   # OUTPUT: «Ǣ␤»\n    say \"\\x1E2P\";  # OUTPUT: «ǢP␤» ('P' is not a hexadecimal digit, result: 2 chars)\n    say \"\\x1E2 \";  # OUTPUT: «Ǣ ␤» (' ' is not a hexadecimal digit, result: 2 chars)\n    say \"\\x1E20\";  # OUTPUT: «Ḡ␤»  ('0' is a hexadecimal digit', result: 1 char)\n\nThe same type of result would occur for the octal version if the ending character\nwas not in the set (0..7).\n\n=head2 Inserting codepoints in strings by name\n\nYou can also access Unicode codepoints by name, and\nRaku supports all Unicode names. X<|Syntax,\\c[some name] Unicode name>\n\n    say \"\\c[PENGUIN]\"; # OUTPUT: «🐧␤»\n    say \"\\c[BELL]\";    # OUTPUT: «🔔␤» (U+1F514 BELL)\n\nAll Unicode codepoint names and name sequences are now case-insensitive:\n[Starting in Rakudo 2017.02]\n\n    say \"\\c[latin capital letter ae with macron]\"; # OUTPUT: «Ǣ␤»\n    say \"\\c[latin capital letter E]\";              # OUTPUT: «E␤» (U+0045)\n\n(However, those names will be shown in uppercase when interrogating the character's\nuniname.)\n\nYou can specify multiple characters by using a comma separated list inside\na single C<\\c[]> instance. You can combine numeric and named styles as well:\n\n    say \"\\c[482,PENGUIN]\"; # OUTPUT: «Ǣ🐧␤»\n\nIn addition to using C<\\c[]> inside interpolated strings, you can also use\nthe L<uniparse|/routine/uniparse> to show its character:\n\n    say \"DIGIT ONE\".uniparse;  # OUTPUT: «1␤»\n    say uniparse(\"DIGIT ONE\"); # OUTPUT: «1␤»\n\nSee L<uniname|/routine/uniname> and L<uninames|/routine/uninames> for routines\nthat work in the opposite direction with a single codepoint and multiple\ncodepoints, respectively.\n\n=head2 Codepoint sequences\n\nCodepoint sequences can be inserted into a single string by following a codepoint entry\nwith others or intermingling them with single characters, words, and spaces as normal\ntext. Such codepoint entries are very useful for users who do not have ready access to\na Unicode capable keyboard. Strings may use any or all of the methods\nof Unicode insertion. For example, to use a French acute accent, create the text like this:\n\n    say \"Le Caf\\xe9 Marly\"; # OUTPUT: «Le Café Marly␤»\n\nFinally, here is a more complete example showing many of the methods in one string:\n\n    say \"\\c[PENGUIN] went looking for \\x1F41F but found only \\o[375274,40,373046].\"\n    # Output: «🐧 went looking for 🐟 but found only 🪼 😦.␤»\n\n=head2 Name aliases\n\nName Aliases are used mainly for codepoints without an official\nname, for abbreviations, or for corrections (Unicode names never change).\nFor a full list of them see L<here|https://www.unicode.org/Public/UCD/latest/ucd/NameAliases.txt>.\n\nControl codes without any official name:\n\n    say \"\\c[ALERT]\";     # Not visible (U+0007 control code (also accessible as \\a))\n    say \"\\c[LINE FEED]\"; # Not visible (U+000A same as \"\\n\")\n\nCorrections:\n\n    #   Correct name as input:\n    say                     \"\\c[LATIN CAPITAL LETTER GHA]\"; # OUTPUT: «Ƣ␤»\n    #   Original, erroneous name as output:\n    say \"Ƣ\".uniname; # OUTPUT: «LATIN CAPITAL LETTER OI␤»\n\n    # This one is a spelling mistake that was corrected in a Name Alias:\n    #   Correct name as input:\n    say    \"\\c[PRESENTATION FORM FOR VERTICAL RIGHT WHITE LENTICULAR BRACKET]\".uniname;\n    #   Original, erroneous name as output:\n    # OUTPUT: «PRESENTATION FORM FOR VERTICAL RIGHT WHITE LENTICULAR BRAKCET␤»\n\nAbbreviations:\n\n    say \"\\c[ZWJ]\".uniname;   # OUTPUT: «ZERO WIDTH JOINER␤»\n    say \"\\c[NBSP]\".uniname;  # OUTPUT: «NO-BREAK SPACE␤»\n    say \"\\c[NNBSP]\".uniname; # OUTPUT: «NARROW NO-BREAK SPACE␤»\n\n=head2 Named sequences\n\nYou can also use any of the L<Named Sequences|https://www.unicode.org/Public/UCD/latest/ucd/NamedSequences.txt>,\nthese are not single codepoints, but sequences of them. [Starting in Rakudo 2017.02]\n\n    say \"\\c[LATIN CAPITAL LETTER E WITH VERTICAL LINE BELOW AND ACUTE]\";      # OUTPUT: «É̩␤»\n    say \"\\c[LATIN CAPITAL LETTER E WITH VERTICAL LINE BELOW AND ACUTE]\".ords; # OUTPUT: «(201 809)␤»\n\n=head3 Emoji sequences\n\nRaku supports Emoji sequences.\nFor all of them see:\nL<Emoji ZWJ Sequences|https://www.unicode.org/Public/emoji/4.0/emoji-zwj-sequences.txt>\nand L<Emoji Sequences|https://www.unicode.org/Public/emoji/4.0/emoji-sequences.txt>.\nNote that any names with commas should have their commas removed since Raku uses\ncommas to separate different codepoints/sequences inside the same C<\\c> sequence.\n\n    say \"\\c[woman gesturing OK]\";         # OUTPUT: «🙆‍♀️␤»\n    say \"\\c[family: man woman girl boy]\"; # OUTPUT: «👨‍👩‍👧‍👦␤»\n\n=head2 Confusability\n\nBecause of the number of characters in unicode, wider support means you may find some that are\nconfusable. For general tips on how to avoid issues, see\nL<Confusability|https://www.unicode.org/reports/tr39/#Confusable_Detection>\nat the unicode.org site.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/unicode_ascii.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Unicode versus ASCII symbols\n\n=SUBTITLE Unicode symbols and their ASCII equivalents\n\nThe following Unicode symbols can be used in Raku without needing to\nload any additional modules. Some of them have equivalents\nwhich can be typed with ASCII-only characters.\n\nReference is made below to various properties of unicode codepoints.\nThe definitive list can be found here:\nL<https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt>.\n\n=head1 Alphabetic characters\n\nAny codepoint that has the C<Ll> (Letter, lowercase), C<Lu> (Letter,\nuppercase), C<Lt> (Letter, titlecase), C<Lm> (Letter, modifier), or\nthe C<Lo> (Letter, other) property can be used just like any other\nalphabetic character from the ASCII range.\n\n=begin code\nmy $Δ = 1;\n$Δ++;\nsay $Δ;\n=end code\n\n=head1 Numeric characters\n\nAny codepoint that has the C<Nd> (Number, decimal digit) property, can\nbe used as a digit in any number.  For example:\n\n  my $var = １９; # U+FF11 U+FF19\n  say $var + 2;   # OUTPUT: «21␤»\n\n=head1 Numeric values\n\nAny codepoint that has the C<No> (Number, other) or C<Nl> (Number, letter)\nproperty can be used standalone as a numeric value, such as ½ and ⅓. (These\naren't decimal digit characters, so can't be combined.) For example:\n\n  my $var = ⅒ + 2 + Ⅻ; # here ⅒ is No and Rat and Ⅻ is Nl and Int\n  say $var;              # OUTPUT: «14.1␤»\n\n=head1 X<Whitespace characters|Language,Whitespace>\n\nBesides spaces and tabs, you can use any other unicode whitespace\ncharacter that has the C<Zs> (Separator, space), C<Zl> (Separator,\nline), or C<Zp> (Separator, paragraph) property.\n\nSee Wikipedia's L<Whitespace|https://en.m.wikipedia.org/wiki/Whitespace_character>\nsection for detailed\ntables of the Unicode codepoints with (or associated with)\nwhitespace characteristics. This is an important section for Raku\nauthors of digital typography modules for print or web use.\n\n=head1 Other acceptable single codepoints\n\nThis list contains the single codepoints [and their ASCII\nequivalents] that have a special meaning in Raku.\n\nX<|Reference,«>X<|Reference,»>X<|Reference,×>X<|Reference,÷>\nX<|Reference,≤>X<|Reference,≥>X<|Reference,≠>X<|Reference,−>\nX<|Reference,∘>X<|Reference,≅>X<|Reference,π>X<|Reference,τ>\nX<|Reference,𝑒>X<|Reference,∞>X<|Reference,…>X<|Reference,‘>\nX<|Reference,’>X<|Reference,‚>X<|Reference,“>X<|Reference,”>\nX<|Reference,„>X<|Reference,｢>X<|Reference,｣>X<|Reference,⁺>\nX<|Reference,⁻>X<|Reference,¯>X<|Reference,⁰>X<|Reference,¹>\nX<|Reference,²>X<|Reference,³>X<|Reference,⁴>X<|Reference,⁵>\nX<|Reference,⁶>X<|Reference,⁷>X<|Reference,⁸>X<|Reference,⁹>\nX<|Reference,∈>X<|Reference,∉>X<|Reference,∋>X<|Reference,∌>\nX<|Reference,≡>X<|Reference,≢>X<|Reference,⊆>X<|Reference,⊈>\nX<|Reference,⊂>X<|Reference,⊄>X<|Reference,⊇>X<|Reference,⊉>\nX<|Reference,⊃>X<|Reference,⊅>X<|Reference,≼>X<|Reference,≽>\nX<|Reference,∪>X<|Reference,∩>X<|Reference,∖>X<|Reference,⊖>\nX<|Reference,⊍>X<|Reference,⊎>\n=table\n  Symbol | Codepoint | ASCII      | Remarks\n  =======|===========|============|=========================\n  «      |  U+00AB   | <<         | as part of «» or .« or regex left word boundary\n  »      |  U+00BB   | >>         | as part of «» or .» or regex right word boundary\n  ×      |  U+00D7   | *          |\n  ÷      |  U+00F7   | /          |\n  ≤      |  U+2264   | <=         |\n  ≥      |  U+2265   | >=         |\n  ⩵      |  U+2A75   | ==         |\n  ≠      |  U+2260   | !=         |\n  −      |  U+2212   | -          |\n  ∘      |  U+2218   | o          |\n  ⩶      |  U+2A76   | ===        |\n  ≅      |  U+2245   | =~=        |\n  π      |  U+03C0   | pi         | 3.14159_26535_89793_238e0\n  τ      |  U+03C4   | tau        | 6.28318_53071_79586_476e0\n  𝑒      |  U+1D452  | e          | 2.71828_18284_59045_235e0\n  ∞      |  U+221E   | Inf        |\n  …      |  U+2026   | ...        |\n  ‘      |  U+2018   | '          | as part of ‘’ or ’‘\n  ’      |  U+2019   | '          | as part of ‘’ or ‚’ or ’‘\n  ‚      |  U+201A   | '          | as part of ‚‘ or ‚’\n  “      |  U+201C   | \"          | as part of “” or ”“\n  ”      |  U+201D   | \"          | as part of “” or ”“ or ””\n  „      |  U+201E   | \"          | as part of „“ or „”\n  ｢      |  U+FF62   | Q//        | as part of ｢｣ (Note: Q// variant cannot be used bare in regexes)\n  ｣      |  U+FF63   | Q//        | as part of ｢｣ (Note: Q// variant cannot be used bare in regexes)\n  ⁺      |  U+207A   | \\+          | (must use explicit number) as part of exponentiation\n  ⁻      |  U+207B   | -          | (must use explicit number) as part of exponentiation\n  ¯      |  U+00AF   | -          | (must use explicit number) as part of exponentiation (macron is an alternative way of writing a minus)\n  ⁰      |  U+2070   | **0        | can be combined with ⁰..⁹\n  ¹      |  U+00B9   | **1        | can be combined with ⁰..⁹\n  ²      |  U+00B2   | **2        | can be combined with ⁰..⁹\n  ³      |  U+00B3   | **3        | can be combined with ⁰..⁹\n  ⁴      |  U+2074   | **4        | can be combined with ⁰..⁹\n  ⁵      |  U+2075   | **5        | can be combined with ⁰..⁹\n  ⁶      |  U+2076   | **6        | can be combined with ⁰..⁹\n  ⁷      |  U+2077   | **7        | can be combined with ⁰..⁹\n  ⁸      |  U+2078   | **8        | can be combined with ⁰..⁹\n  ⁹      |  U+2079   | **9        | can be combined with ⁰..⁹\n  ∅      |  U+2205   | set()      | (empty set)\n  ∈      |  U+2208   | (elem)     |\n  ∉      |  U+2209   | !(elem)    |\n  ∋      |  U+220B   | (cont)     |\n  ∌      |  U+220C   | !(cont)    |\n  ≡      |  U+2261   | (==)       |\n  ≢      |  U+2262   | !(==)      |\n  ⊆      |  U+2286   | (<=)       |\n  ⊈      |  U+2288   | !(<=)      |\n  ⊂      |  U+2282   | (<)        |\n  ⊄      |  U+2284   | !(<)       |\n  ⊇      |  U+2287   | (>=)       |\n  ⊉      |  U+2289   | !(>=)      |\n  ⊃      |  U+2283   | (>)        |\n  ⊅      |  U+2285   | !(>)       |\n  ∪      |  U+222A   | (|)        |\n  ∩      |  U+2229   | (&)        |\n  ∖      |  U+2216   | (-)        |\n  ⊖      |  U+2296   | (^)        |\n  ⊍      |  U+228D   | (.)        |\n  ⊎      |  U+228E   | (+)        |\n\n=head2 Atomic operators\n\nThe atomic operators have C<U+269B ⚛ ATOM SYMBOL> incorporated into them. Their\nASCII equivalents are ordinary subroutines, not operators:\n\n    my atomicint $x = 42;\n    $x⚛++;                # Unicode version\n    atomic-fetch-inc($x); # ASCII version\n\nThe ASCII alternatives are as follows:\n\nX<|Reference,⚛=>X<|Reference,⚛>X<|Reference,⚛+=>\nX<|Reference,⚛-=>X<|Reference,⚛−=>X<|Reference,++⚛>\nX<|Reference,⚛++>X<|Reference,--⚛>X<|Reference,⚛-->\n=table\n  Symbol | ASCII            | Remarks\n  ===============================================================\n  ⚛=  | atomic-assign    |\n  ⚛   | atomic-fetch     | this is the prefix:<⚛> operator\n  ⚛+= | atomic-add-fetch |\n  ⚛-= | atomic-sub-fetch |\n  ⚛−= | atomic-sub-fetch | this operator uses U+2212 minus sign\n  ++⚛ | atomic-inc-fetch |\n  ⚛++ | atomic-fetch-inc |\n  --⚛ | atomic-dec-fetch |\n  ⚛-- | atomic-fetch-dec |\n\n=head1 Multiple codepoints\n\nThis list contains multiple-codepoint operators that require special\ncomposition for their ASCII equivalents.  Note the codepoints\nare shown space-separated but should be entered as adjacent codepoints\nwhen used.\n\nX<|Reference,»=»>X<|Reference,«=«>X<|Reference,«=»>X<|Reference,»=«>\n=table\n  Symbol | Codepoints       | ASCII   | Since | Remarks\n  =======|==================|=========|=======|=========================\n  »=»    | U+00BB = U+00BB  | >>[=]>> | v6.c  | uses ASCII '='\n  «=«    | U+00AB = U+00AB  | <<[=]<< | v6.c  | uses ASCII '='\n  «=»    | U+00AB = U+00BB  | <<[=]>> | v6.c  | uses ASCII '='\n  »=«    | U+00BB = U+00AB  | >>[=]<< | v6.c  | uses ASCII '='\n\n=end pod\n"
  },
  {
    "path": "doc/Language/unicode_entry.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"tutorial\")\n\n=TITLE Entering unicode characters\n\n=SUBTITLE Input methods for unicode characters in terminals, the shell, and editors\n\nRaku allows the use of unicode characters as variable names.  Many\noperators are defined with unicode symbols (in particular the L<set/bag\noperators|/language/setbagmix#Operators_with_set_semantics>) as well as some quoting\nconstructs.  Hence it is good to know how to enter these symbols into editors,\nthe Raku shell and the command line, especially if the symbols aren't\navailable as actual characters on a keyboard.\n\nGeneral information about entering unicode under various operating systems\nand environments can be found on the Wikipedia L<unicode input page|https://en.wikipedia.org/wiki/Unicode_input>.\n\nX<|Reference,XCompose>\n=head1 XCompose (Linux)\n\nXorg includes digraph support using a\nL<I<Compose key>|https://en.wikipedia.org/wiki/Compose_key#GNU.2FLinux> .\nThe default of C<AltGr + Shift> can be remapped to something easier such as\nC<Capslock>. In I<GNOME 2> and I<MATE> this can be setup under\nC<Preferences → Keyboard → Layouts → Options → Position of Compose Key>.\nSo, for example, to input C<»+«> you could type\nC«CAPSLOCK > > + CAPSLOCK < <».\n\nI<XCompose> allows customizing the digraph sequences using a C<.XCompose>\nfile and\nL<https://github.com/kragen/xcompose/blob/master/dotXCompose> is an extremely\ncomplete one. In I<GNOME>, I<XCompose> was overridden and replaced with a\nhardcoded list, but it is possible to restore I<XCompose> by setting\nC<GTK_IM_MODULE=xim> in your environment. It might be necessary to install\na xim bridge as well, such as C<uim-xim>.\n\n=head2 Getting compose working in all programs\n\nYou may have issues using the compose key in all programs. In that case you can\ntry C<ibus>.\n\n=for code :lang<shell>\ninput_module=xim\nexport GTK_IM_MODULE=$input_module\nexport XMODIFIERS=@im=$input_module\nexport QT_IM_MODULE=$input_module\n\nIf you want this to be for all users you can put this in a file C</etc/profile.d/compose.sh>,\nwhich is the easiest way, since you won't have to deal with how different GUI\nenvironments set up their environment variables.\n\nIf you use KDE you can put this file in C<~/.config/plasma-workspace/env/compose.sh>\nand that should work. Other desktop environments will be different. Look up\nhow to set environment variables in yours or use the system-wide option above.\n\nX<|Reference,ibus>\n=head2 ibus\n\nIf you have problems entering high codepoint symbols such as B<🐧> using the\nC<xim> input module, you can instead use ibus. You will have to install the ibus\npackage for your distribution. Then you will have to set it to start on load of your\nDesktop environment. The command that needs to be run is:\n\n=for code :lang<shell>\nibus-daemon --xim --verbose --daemonize --replace\n\nSetting C<--xim> should also allow programs not using ibus to still use the xim\ninput method and be backward compatible.\n\nX<|Reference,Xkb>\n=head1 XKB (Linux)\n\nThe X Window System receives keyboard events using the XKB extension, which makes it possible to read the output of various kinds of keyboards, provided that there's a configuration file available.\n\nXKB provides the concept of I<multi-layout> or I<shift levels>.\nFor example the symbol C<a> is the output of the key marked as \"A\" at level 1; the symbol C<A> belongs to the level 2 layout, which is normally reached using the shift key.\nThere are more levels available; one can configure a certain key, let's say the right alt key (or AltGr), as a switch to a third level. The combination of the level-3 modifier and the shift key would switch to a fourth layout: level 4.\nXKB provides for the possibility to add a level 5 switch key which, used in combination with the shift key, would switch to a level 6 layout.\n\nFor an in-depth explanation see L<I<this page>|https://www.x.org/wiki/XKB/> .\n\nThe advantage of this method is that input of characters usually unreachable on a normal keyboard is as easy as pressing the combination of the shift plus another key to output an uppercase letter.\n\n=head2 Single-user configuration\n\nFor a personal configuration it's enough to create a .xkb file and a symbol file in a C<symbols> subdirectory.\nThe .xkb file can be created with this command:\n\n=for code :lang<shell>\nsetxkbmap -print > raku.xkb\n\nHere's an example of such a file:\n\n=for code :lang<text>\nxkb_keymap {\n  xkb_keycodes  { include \"evdev+aliases(qwerty)\" };\n  xkb_types     { include \"complete\" };\n  xkb_compat    { include \"complete\" };\n  xkb_symbols   { include \"pc+raku(raku)+inet(evdev)+level3(ralt_switch)+compose(caps)\" };\n};\n\nThis file declares the keycodes generated by the keyboard and the symbols produced on the screen.\n\nIn this case there's a PC-type keyboard whose configuration is in the file C<symbols/raku>, which may contain several variants among which the chosen is the one named C<raku>. The L<I<evdev generic input event interface>|https://en.wikipedia.org/wiki/Evdev> manages the event collection. This configuration uses the right Alt key as a third level switch and the Caps Lock as the Compose key.\n\nOnce chosen the base directory for the configuration files (it might be C<$HOME/.config/xkb> for example) and put the raku.xkb in it, one has to create a I<symbols> directory and put a key layout file in it.\nHere's an example of such a file, named C<raku>:\n\n=begin code :lang<text>\ndefault  partial alphanumeric_keys modifier_keys\nxkb_symbols \"basic\" {\n\n    name[Group1]= \"English (US)\";\n\n    key <TLDE> {  [     grave,  asciitilde  ]  };\n    key <AE01> {  [    1,  exclam     ]  };\n    key <AE02> {  [    2,  at    ]  };\n    key <AE03> {  [    3,  numbersign  ]  };\n    key <AE04> {  [    4,  dollar    ]  };\n    key <AE05> {  [    5,  percent    ]  };\n    key <AE06> {  [    6,  asciicircum  ]  };\n    key <AE07> {  [    7,  ampersand  ]  };\n    key <AE08> {  [    8,  asterisk  ]  };\n    key <AE09> {  [    9,  parenleft  ]  };\n    key <AE10> {  [    0,  parenright  ]  };\n    key <AE11> {  [     minus,  underscore  ]  };\n    key <AE12> {  [     equal,  plus    ]  };\n\n    key <AD01> {  [    q,  Q     ]  };\n    key <AD02> {  [    w,  W    ]  };\n    key <AD03> {  [    e,  E    ]  };\n    key <AD04> {  [    r,  R    ]  };\n    key <AD05> {  [    t,  T    ]  };\n    key <AD06> {  [    y,  Y    ]  };\n    key <AD07> {  [    u,  U    ]  };\n    key <AD08> {  [    i,  I    ]  };\n    key <AD09> {  [    o,  O    ]  };\n    key <AD10> {  [    p,  P    ]  };\n    key <AD11> {  [ bracketleft,  braceleft  ]  };\n    key <AD12> {  [ bracketright,  braceright  ]  };\n\n    key <AC01> {  [    a,  A     ]  };\n    key <AC02> {  [    s,  S    ]  };\n    key <AC03> {  [    d,  D    ]  };\n    key <AC04> {  [    f,  F    ]  };\n    key <AC05> {  [    g,  G    ]  };\n    key <AC06> {  [    h,  H    ]  };\n    key <AC07> {  [    j,  J    ]  };\n    key <AC08> {  [    k,  K    ]  };\n    key <AC09> {  [    l,  L    ]  };\n    key <AC10> {  [ semicolon,  colon    ]  };\n    key <AC11> {  [ apostrophe,  quotedbl  ]  };\n\n    key <AB01> {  [    z,  Z     ]  };\n    key <AB02> {  [    x,  X    ]  };\n    key <AB03> {  [    c,  C    ]  };\n    key <AB04> {  [    v,  V    ]  };\n    key <AB05> {  [    b,  B    ]  };\n    key <AB06> {  [    n,  N    ]  };\n    key <AB07> {  [    m,  M    ]  };\n    key <AB08> {  [     comma,  less    ]  };\n    key <AB09> {  [    period,  greater    ]  };\n    key <AB10> {  [     slash,  question  ]  };\n\n    key <BKSL> {  [ backslash,         bar  ]  };\n};\n\npartial alphanumeric_keys\nxkb_symbols \"raku\" {\n\n   include \"raku(basic)\"\n   name[Group1]= \"English (raku operators, with AltGr)\";\n\n   key <TLDE> { [     grave, asciitilde, dead_grave, leftsinglequotemark   ] }; //‘\n   key <AE01> { [         1,     exclam,      U00B9                        ] }; //¹\n   key <AE02> { [         2,         at,      U00B2                        ] }; //²\n   key <AE03> { [         3, numbersign,      U00B3,      U2026            ] }; //³…\n   key <AE04> { [         4,     dollar,      U2074                        ] }; //⁴\n   key <AE05> { [         5,    percent,      U2075                        ] }; //⁵\n   key <AE06> { [         6,asciicircum,      U2076                        ] }; //⁶\n   key <AE07> { [         7,  ampersand,      U2077                        ] }; //⁷\n   key <AE08> { [         8,   asterisk,      U2078,      multiply         ] }; //⁸×\n   key <AE09> { [         9,  parenleft,      U2079                        ] }; //⁹\n   key <AE10> { [         0, parenright,      U2070                        ] }; //⁰\n   key <AE11> { [     minus, underscore,      U2212,      U207B            ] }; //⁻−\n   key <AE12> { [     equal,       plus,      U2261,      U207A            ] }; //≡⁺\n   key <BKSL> { [ backslash,        bar,      U2262,      U221E            ] }; //≢∞\n   key <AD03> { [         e,          E,   EuroSign,      U1D452           ] }; //€𝑒\n   key <AD05> { [         t,          T,      U03C4,      U2296            ] }; //τ⊖\n   key <AD07> { [         u,          U,      U222A,      U2229            ] }; //∪∩\n   key <AD09> { [         o,          O,      U2218                        ] }; //∘\n   key <AD10> { [         p,          P,      U03C0                        ] }; //π\n   key <AD11> { [ bracketleft,  braceleft,    U2260,      U201E            ] }; //≠„\n   key <AD12> { [ bracketright, braceright,   U2245,      U201A            ] }; //≅‚\n   key <AC01> { [         a,          A,      U2208,      U2209            ] }; //∈∉\n   key <AC02> { [         s,          S,      U220B,      U220C            ] }; //∋∌\n   key <AC09> { [         l,          L,      UFF62,      UFF63            ] }; //｢｣\n   key <AC10> { [ semicolon,      colon,      U201C,      U201D            ] }; //“”\n   key <AC11> { [apostrophe,   quotedbl,  rightsinglequotemark             ] }; //’\n   key <AB02> { [         x,          X,      U2284,      U2285            ] }; //⊄ ⊅\n   key <AB03> { [         c,          C,      U2282,      U2283            ] }; //⊂ ⊃\n   key <AB05> { [         b,          B,      U228E,      U228D            ] }; //⊎⊍\n   key <AB06> { [         n,          N,      U269B                        ] }; //⚛\n   key <AB08> { [     comma,       less,   guillemotleft, U2264            ] }; //«≤\n   key <AB09> { [    period,    greater,  guillemotright, U2265            ] }; //»≥\n   key <AB10> { [     slash,   question,   division,      U2216            ] }; //÷∖\n\n   include \"level3(ralt_switch)\"\n};\n=end code\n\nThis file contains two layouts: the first is the basic layout of a US keyboard with just two shift levels, the second one includes the first and adds several Unicode symbols to some of the keys using two additional shift levels.\nThe format of this file is documented L<I<here>|https://www.x.org/releases/X11R7.5/doc/input/XKB-Enhancing.html>.\n\nFor a different keyboard one needs to change the first layout, marked C<basic>, with the one pertaining to the specific national layout. Usually these layouts are located in the C</usr/share/X11/xkb/symbols> directory. After that one has to modify the second layout to conform to the specific language key layout.\n\nIf one's base directory is $HOME/.config/xkb, this command will load the new configuration:\n\n=for code :lang<shell>\nxkbcomp -I$HOME/.config/xkb $HOME/.config/xkb/raku.xkb $DISPLAY\n\n(There might be some warnings for symbols not defined)\n\nWhile this is a non-invasive method, one has to load manually the configuration file whenever is needed.\n\n=head2 System-wide configuration\n\nThe advantage of this method is that since it modifies the system files, the user can choose the new layout using the usual interface provided by their desktop manager and make it permanent.\n\nThe drawbacks are that one has to have root access to the system and that a system upgrade might overwrite one's layout file.\n\nTo modify the system-wide configuration one has to locate the specific file describing their language mapping and add the C<raku> part shown in the previous section.\n\nIn order for the new layout to show in the system menus one has to add a specific description in the C<evdev> rule file, usually in C</usr/share/X11/xkb/rules/evdev.xml>. Locate the section corresponding the one's language keyboard layout. For example the C<us> layout starts like this:\n\n=for code :lang<xml>\n  […]\n  <layoutList>\n    <layout>\n      <configItem>\n        <name>us</name>\n        <!-- Keyboard indicator for English layouts -->\n        <shortDescription>en</shortDescription>\n        <description>English (US)</description>\n        <languageList>\n          <iso639Id>eng</iso639Id>\n        </languageList>\n      </configItem>\n      <variantList>\n        <variant>\n          <configItem>\n          […]\n\nOne has to add the newly defined variant:\n\n=for code :lang<xml>\n        <variant>\n          <configItem>\n            <name>raku</name>\n            <description>raku (Raku operators, with AltGr)</description>\n            <languageList>\n              <iso639Id>eng</iso639Id>\n            </languageList>\n          </configItem>\n        </variant>\n\nAfter logging out and in again, the new variant should appear in the list of the layouts and variants.\nAlternatively one can now load the layout with this command:\n\n=for code :lang<shell>\nsetxkbmap -layout us -variant raku\n\nThis actually reloads the C<raku> variant of the C<us> keyboard, but unfortunately disables other keyboard layouts in case of multi-keyboard use.\n\n=head3 KDE\n\nIf you are using KDE, open the start menu and type in “Autostart” and click B<Autostart>\nwhich should be the first result. In the settings window that opens, click\nB<Add program>, type in C<ibus-daemon> and click OK. Then go into the Application\ntab of the window that pops up. In the C<Command> field, enter in the full\nibus-daemon command as shown above, with the C<--desktop> option set to\nC<--desktop=plasma>. Click OK. It should now launch automatically when you\nlog in again.\n\n=head3 How to enter Unicode characters using a two-key combination\n\nUsing the XCompose input method it is possible to enter Unicode characters using simple two-key combinations.\nHere's an example of a configuration which would enable entering all the Unicode characters used by Raku.\nThis example uses both Super keys as C<dead keys>. For example, to enter the C<π> symbol one has to press and\nrelease the right C<Super> (or \"Windows\") key, then press and release the C<p> key.\n\n=for code :lang<shell>\n<Super_R> <less>               : \"«\" guillemotleft\n<Super_R> <greater>            : \"»\" guillemotright\n<Super_R> <minus>              : \"⁻\"   U207B\n<Super_R> <0>                  : \"⁰\"   U2070\n<Super_R> <1>                  : \"¹\"   U00B9\n<Super_R> <2>                  : \"²\"   U00B2\n<Super_R> <3>                  : \"³\"   U00B3\n<Super_R> <4>                  : \"⁴\"   U2074\n<Super_R> <5>                  : \"⁵\"   U2075\n<Super_R> <6>                  : \"⁶\"   U2076\n<Super_R> <7>                  : \"⁷\"   U2077\n<Super_R> <8>                  : \"⁸\"   U2078\n<Super_R> <9>                  : \"⁹\"   U2079\n<Super_R> <asterisk>           : \"×\"   U00D7\n<Super_R> <slash>              : \"÷\"   U00F7\n<Super_R> <E>                  : \"𝑒\"   U1D452\n<Super_R> <p>                  : \"π\"   U03C0\n<Super_R> <t>                  : \"τ\"   U03C4\n<Super_R> <grave>              : \"‘\"   U2018\n<Super_R> <apostrophe>         : \"’\"   U2019\n<Super_R> <comma>              : \"‚\"   U201A\n<Super_R> <colon>              : \"“\"   U201C\n<Super_R> <quotedbl>           : \"”\"   U201D\n<Super_R> <L>                  : \"„\"   U201E\n<Super_R> <period>             : \"…\"   U2026\n<Super_R> <bracketleft>        : \"≡\"   U2261\n<Super_R> <bracketright>       : \"≢\"   U2262\n<Super_L> <8>                  : \"∞\"   U221E\n<Super_L> <O>                  : \"∅\"   U2205\n<Super_L> <e>                  : \"∈\"   U2208\n<Super_L> <E>                  : \"∉\"   U2209\n<Super_L> <3>                  : \"∋\"   U220B\n<Super_L> <numbersign>         : \"∌\"   U220C\n<Super_L> <minus>              : \"−\"   U2212\n<Super_L> <slash>              : \"∖\"   U2216\n<Super_L> <o>                  : \"∘\"   U2218\n<Super_L> <U>                  : \"∩\"   U2229\n<Super_L> <u>                  : \"∪\"   U222A\n<Super_L> <asciitilde>         : \"≅\"   U2245\n<Super_L> <equal>              : \"≠\"   U2260\n<Super_L> <less>               : \"≤\"   U2264\n<Super_L> <greater>            : \"≥\"   U2265\n<Super_L> <c>                  : \"⊂\"   U2283\n<Super_L> <C>                  : \"⊃\"   U2283\n<Super_L> <v>                  : \"⊄\"   U2284\n<Super_L> <V>                  : \"⊅\"   U2285\n<Super_R> <d>                  : \"⊆\"   U2286\n<Super_R> <D>                  : \"⊇\"   U2287\n<Super_R> <f>                  : \"⊈\"   U2288\n<Super_R> <F>                  : \"⊉\"   U2289\n<Super_R> <U>                  : \"⊍\"   U228D\n<Super_R> <u>                  : \"⊎\"   U228E\n<Super_L> <t>                  : \"⊖\"   U2296\n<Super_L> <L>                  : \"｢\"   UFF62\n<Super_L> <l>                  : \"｣\"   UFF63\n\nOne can add these lines to their ~/.XCompose file. To activate the changes one needs to exit their X session\nand login back again.\nNote that since Ubuntu Gnome uses one C<Super> key for its own purposes, one might want to substitute one or\nboth the Super_* keys with, for example, Meta_R.\n\nX<|Reference,WinCompose>\n=head1 WinCompose (Windows)\n\nL<WinCompose|https://github.com/samhocevar/wincompose> adds\nL<compose key|https://en.wikipedia.org/wiki/Compose_key> functionality to Windows.\nIt can be installed either via the L<WinCompose releases|https://github.com/samhocevar/wincompose/releases>\npage on GitHub, or with the L<Chocolatey package manager|https://chocolatey.org/packages/wincompose>.\n\nOnce the program is installed and running, right click the tray icon and\nselect C<Options → Composing → Behavior → Compose Key> to set your desired key.\n\nWinCompose has multiple sources to choose from in C<Options → Composing → Sequences>.\nIt is recommended to enable C<XCompose> and disable C<Xorg>, as there are a handful\nof operators which C<Xorg> does not provide sequences for, and C<Xorg> also has\nsequences which conflict with operator sequences present in C<XCompose>.\nSequences can be viewed by right clicking the tray icon and selecting C<Show Sequences>.\nIf you wish to add your own sequences, you can do so by either adding/modifying\nC<.XCompose> in C<%USERPROFILE%>, or editing user-defined sequences in the options menu.\n\n=head1 Terminals, shells, and editors:\n\n=head2 XTerm\n\nUnicode support is enabled in XTerm primarily by setting its C<utf8> and\nC<utf8Fonts> options to C<1>, along with its C<locale> option to C<UTF-8>, in\nC<~/.Xdefaults>. Here is a sample configuration that supports displaying enough\nof unicode to program in Raku:\n\n    =begin code :lang<.Xdefaults>\n    XTerm*faceName:           xft:Noto Mono:style=Regular\n    XTerm*faceNameDoublesize: xft:Noto Emoji:style=Regular\n    XTerm*faceSize:           10\n    XTerm*locale:             UTF-8\n    XTerm*titleModes:         16\n    XTerm*utf8:               1\n    XTerm*utf8Fonts:          1\n    XTerm*utf8Title:          true\n    =end code\n\n=head2 URxvt\n\nSimilarly to XTerm, unicode support is enabled in URxvt primarily by setting\nits C<locale> option to C<en_US.UTF-8> in C<~/.Xdefaults>. Here is a sample\nconfiguration that supports displaying enough of unicode to program in Raku:\n\n    =begin code :lang<.Xdefaults>\n    URxvt*font:              xft:Noto Mono:pixelsize=14:style=Regular,\\\n                             xft:Noto Emoji:pixelsize=14:style=Regular\n    URxvt*letterSpace:       -1\n    URxvt*locale:            en_US.UTF-8\n    URxvt*skipBuiltInGlyphs: true\n    =end code\n\n=head2 Unix shell\n\nAt the bash shell, one enters unicode characters by using entering\nC<Ctrl-Shift-u>, then the unicode code point value followed by enter.  For\ninstance, to enter the character for the element-of operator (∈) use the\nfollowing key combination (whitespace has been added for clarity):\n\n    =begin code :lang<shell>\n    Ctrl-Shift-u 2208 Enter\n    =end code\n\nThis also the method one would use to enter unicode characters into the\nC<raku> L<REPL|/language/REPL>, if one has started the REPL inside a Unix shell.\n\n=head2 Screen\n\nL<GNU Screen|https://www.gnu.org/software/screen/> does sport a B<digraph>\ncommand but with a rather limited digraph table. Thanks to B<bindkey> and\nB<exec> an external program can be used to insert characters to the current\nscreen window.\n\n    =begin code :lang<screen>\n    bindkey ^K exec .! digraphs\n    =end code\n\nThis will bind control-k to the shell command digraphs. You can use\nL<digraphs|https://github.com/gfldex/digraphs> if you prefer a Raku friendly\ndigraph table over L<RFC 1345|https://tools.ietf.org/html/rfc1345> or change it\nto your needs.\n\nX<|Reference,Vim>\n=head2 Vim\n\nIn L<Vim|https://www.vim.org/>, unicode characters are entered (in\ninsert-mode) by pressing first C<Ctrl-V> (also denoted C<^V>), then C<u> and\nthen the hexadecimal value of the unicode character to be entered.  For\nexample, the Greek letter λ (lambda) is entered via the key combination:\n\n    =begin code :lang<vim>\n    ^Vu03BB\n    =end code\n\nYou can also use C<Ctrl-K>/C<^K> along with a digraph to type in some\ncharacters.  So an alternative to the above using digraphs looks like this:\n\n    =begin code :lang<vim>\n    ^Kl*\n    =end code\n\nThe list of digraphs Vim provides is documented\nL<here|http://vimdoc.sourceforge.net/htmldoc/digraph.html>; you can add\nyour own with the C<:digraph> command.\n\nFurther information about entering special characters in Vim can be found on\nthe Vim Wikia page about L<entering special characters|http://vim.wikia.com/wiki/Entering_special_characters>.\n\n=head3 vim-raku\n\nThe L<vim-raku|https://github.com/Raku/vim-raku> plugin for Vim can be\nconfigured to optionally replace ASCII based ops with their Unicode based\nequivalents. This will convert the ASCII based ops on the fly while typing\nthem.\n\nX<|Reference,Emacs>\n=head2 Emacs\n\nIn L<Emacs|https://www.gnu.org/software/emacs/>, unicode characters are\nentered by first entering the chord C<C-x 8 RET> at which point the\ntext C<Unicode (name or hex):> appears in the minibuffer.  One then enters\nthe unicode code point hexadecimal number followed by the enter key.  The\nunicode character will now appear in the document.  Thus, to enter the Greek\nletter λ (lambda), one uses the following key combination:\n\n    =begin code :lang<emacs>\n    C-x 8 RET 3bb RET\n    =end code\n\nFurther information about unicode and its entry into Emacs can be found on\nthe L<Unicode Encoding Emacs wiki page|https://www.emacswiki.org/emacs/UnicodeEncoding>.\n\nYou can also use L<RFC 1345|https://tools.ietf.org/html/rfc1345> character\nmnemonics by typing:\n\n    =begin code :lang<emacs>\n    C-x RET C-\\ rfc1345 RET\n    =end code\n\nOr C<C-u C-\\ rfc1345 RET>.\n\nTo type special characters, type C<&> followed by a mnemonic.\nEmacs will show the possible characters in the echo area.\nFor example, Greek letter λ (lambda) can be entered by typing:\n\n    =begin code :lang<emacs>\n    &l*\n    =end code\n\nYou can use C<C-\\> to toggle\nL<input method|https://www.gnu.org/software/emacs/manual/html_node/emacs/Select-Input-Method.html>.\n\nAnother L<input method|https://www.emacswiki.org/emacs/InputMethods>\nyou can use to insert special characters is\nL<TeX|https://www.emacswiki.org/emacs/TeXInputMethod>.\nSelect it by typing C<C-u C-\\ TeX RET>. You can enter a special character\nby using a prefix such as C<\\>. For example, to enter λ, type:\n\n    =begin code :lang<tex>\n    \\lambda\n    =end code\n\nTo view characters and sequences provided by an input method,\nrun the C<describe-input-method> command:\n\n    =begin code :lang<tex>\n    C-h I TeX\n    =end code\n\n=head1 Some characters useful in Raku\n\n=head2 L<Smart quotes|https://en.wikipedia.org/wiki/Quotation_mark#Curved_quotes_and_Unicode>\n\nThese characters are used in different languages as quotation marks. In Raku\nthey are used as L<quoting characters|/language/quoting>\n\nConstructs such as these are now possible:\n\n    say ｢What?!｣;\n    say ”Whoa!“;\n    say „This works too!”;\n    say „There are just too many ways“;\n    say “here: “no problem” at all!”; # You can nest them!\n\nThis is very useful in shell:\n\n    =begin code :lang<shell>\n    raku -e 'say ‘hello world’'\n    =end code\n\nsince you can just copy and paste some piece of code and not worry about quotes.\n\n=head2 L<Guillemets|https://en.wikipedia.org/wiki/Guillemet>\n\nThese characters are used in French and German as quotation marks. In Raku\nthey are used as L<interpolation word quotes|/language/quoting#Word_quoting_with_interpolation_and_quote_protection:_qqww>,\nL<hyper operators|/language/operators#Hyper_operators> and as an angle bracket\nalternative in POD6.\n\n=begin table\n    symbol   unicode code point   ascii equivalent\n    ------   ------------------   ----------------\n    «        U\\+00AB              <<\n    »        U\\+00BB              >>\n=end table\n\nThus constructs such as these are now possible:\n\n    say (1, 2) »+« (3, 4);     # OUTPUT: «(4 6)␤» - element-wise add\n    [1, 2, 3] »+=» 42;         # add 42 to each element of @array\n    say «moo»;                 # OUTPUT: «moo␤»\n\n    my $baa = \"foo bar\";\n    say «$baa $baa ber».raku;  # OUTPUT: «(\"foo\", \"bar\", \"foo\", \"bar\", \"ber\")␤»\n\n=head2 Set/bag operators\n\nThe L<set/bag operators|/language/setbagmix#Operators_with_set_semantics> all\nhave set-theory-related symbols, the unicode code points and their ascii\nequivalents are listed below.  To compose such a character, it is merely\nnecessary to enter the character composition chord (e.g. C<Ctrl-V u> in Vim;\nC<Ctrl-Shift-u> in Bash) then the unicode code point hexadecimal number.\n\n=begin table\n    operator   unicode code point   ascii equivalent\n    --------   ------------------   ----------------\n    ∈          U\\+2208              (elem)\n    ∉          U\\+2209              !(elem)\n    ∋          U\\+220B              (cont)\n    ∌          U\\+220C              !(cont)\n    ≡          U\\+2261              (==)\n    ≢          U\\+2262              !(==)\n    ⊆          U\\+2286              (<=)\n    ⊈          U\\+2288              !(<=)\n    ⊂          U\\+2282              (<)\n    ⊄          U\\+2284              !(<)\n    ⊇          U\\+2287              (>=)\n    ⊉          U\\+2289              !(>=)\n    ⊃          U\\+2283              (>)\n    ⊅          U\\+2285              !(>)\n    ∪          U\\+222A              (\\|)\n    ∩          U\\+2229              (&)\n    ∖          U\\+2216              (-)\n    ⊖          U\\+2296              (^)\n    ⊍          U\\+228D              (.)\n    ⊎          U\\+228E              (\\+)\n=end table\n\n=head2 Mathematical symbols\n\nWikipedia contains a full list of L<mathematical operators and symbols in unicode|https://en.wikipedia.org/wiki/Mathematical_operators_and_symbols_in_Unicode>\nas well as links to their mathematical meaning.\n\n=head2 Greek characters\n\nGreek characters may be used as variable names.  For a list of Greek and\nCoptic characters and their unicode code points see the L<Greek in Unicode Wikipedia article|https://en.wikipedia.org/wiki/Greek_alphabet#Greek_in_Unicode>.\n\nFor example, to assign the value 3 to C<$π>, enter the following in Vim\n(whitespace added to the compose sequences, listed in between « and », for\nclarity):\n\n    =begin code :lang<vim>\n    my $«Ctrl-V u 03C0» = 3;  # same as: my $π = 3;\n    say $«Ctrl-V u 03C0»;     # same as: say $π;\n    =end code\n\n=head2 Superscripts and subscripts\n\nA limited set of\nL<superscripts and subscripts|https://en.wikipedia.org/wiki/Superscripts_and_Subscripts>\ncan be created directly in unicode by using the C<U+207x>, C<U+208x> and\n(less often) the C<U+209x> ranges.  However, to produce a value squared (to\nthe power of 2) or cubed (to the power of 3), one needs to use C<U+00B2> and\nC<U+00B3> since these are defined in the\nL<Latin1 supplement Unicode block|https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)>.\n\nThus, to write the L<Taylor series|https://en.wikipedia.org/wiki/Taylor_series>\nexpansion around zero of the function C<exp(x)> one would input into e.g.\nvim the following:\n\n    =begin code :lang<vim>\n    exp(x) = 1 + x + x«Ctrl-V u 00B2»/2! + x«Ctrl-V u 00B3»/3!\n    + ... + x«Ctrl-V u 207F»/n!\n    # which would appear as\n    exp(x) = 1 + x + x²/2! + x³/3! + ... + xⁿ/n!\n    =end code\n\nOr to specify the elements in a list from C<1> up to C<k>:\n\n    =begin code :lang<vim>\n    A«Ctrl-V u 2081», A«Ctrl-V u 2082», ..., A«Ctrl-V u 2096»\n    # which would appear as\n    A₁, A₂, ..., Aₖ\n    =end code\n\n=head1 Font issues\n\nSome distributions contain fonts that do not contain all Unicode glyphs. If you have\ntrouble viewing some glyphs, you may need to install a font like\nL<GNU Unifont|https://unifoundry.com/unifont/index.html>.\n\n=end pod\n"
  },
  {
    "path": "doc/Language/using-modules/code.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Modules\") :category(\"tutorial\")\n\n=TITLE Using modules: the code\n\n=SUBTITLE How to use Raku modules in your code\n\n=head1 X<Loading and basic importing|Language,compunit>\n\nLoading a module makes the packages in the same namespace declared\nwithin available in the file scope of the loader. Importing from a\nmodule makes the symbols exported available in the lexical scope of\nthe importing statement.\n\n=head2 X<C<need>|Syntax,need>\n\nC<need> loads a C<compunit> at compile time\n(see L<here|/language/compilation> for technical details).\n\n=for code :skip-test<needs dummy module>\nneed MyModule;\n\nAny packages in the namespace defined within will also be available.\n\n=begin code :solo\n# MyModule.rakumod\nunit module MyModule;\n\nclass Class {}\n=end code\n\nC<MyModule::Class> will be defined when C<MyModule> is loaded, and you can use\nit directly employing its fully qualified name (FQN). Classes and other types\ndefined that way are not automatically exported; you will need to explicitly\nexport it if you want to use it by its short name:\n\n=begin code :solo\n# MyModule.rakumod\nunit module MyModule;\n\nclass Class is export {}\n=end code\n\nAnd then\n\n=begin code :skip-test<needs dummy module>\nuse MyModule;\n\nmy $class = Class.new();\nsay $class.raku;\n=end code\n\n=head2 X<C<use>|Syntax,use>\n\nC<use> loads and then L<imports|/language/using-modules/introduction#Working_with_modules>\nfrom a compunit at compile time. It will look for\nfiles that end in C<.rakumod>. See L<here|/language/using-modules/finding-installing#Finding_installed_modules>\nfor where the runtime will look for modules.\n\n=for code :skip-test<needs dummy module>\nuse MyModule;\n\nThis is equivalent to:\n\n=begin code :skip-test<needs dummy module>\nneed MyModule;\nimport MyModule;\n=end code\n\nSee also\nL<selective importing|/language/using-modules/code#Exporting_and_selective_importing>\nto restrict what you import.\n\n=head2 X<C<require>|Syntax,require>\n\nC<require> loads a compunit at runtime and makes the contents of its namespace\naccessible. That is, you can access definite symbols (meaning :D and not :U)\nusing their fully-qualified names. The FQN is necessary because the lexical\nscope can't be added to at runtime.\n\n    say \"loading MyModule\";\n    require MyModule;\n\nThe compunit name can be in a runtime variable if you put it inside an\nindirect lookup.\n\n    my $name = 'MyModule';\n    require ::($name);\n\nThe symbols provided by the loaded module will not be imported into the\ncurrent lexical scope. You may use\nL<dynamic lookup|/language/packages#index-entry-::()> or\nL<dynamic subsets|/language/typesystem#subset> to use them by providing\nthe fully qualified name of a symbol, for instance:\n\n    require ::(\"Test\");\n    my &mmk = ::(\"Test::EXPORT::DEFAULT::&ok\");\n    mmk('oi‽'); # OUTPUT: «ok 1 - ␤»\n\nThe FQN of C<ok> is C<Test::EXPORT::DEFAULT::&ok>. We are aliasing it to\nC<mmk> so that we can use that symbol provided by L<C<Test>|/type/Test> in the current\nscope.\n\nTo import symbols you must define them at compile time. B<NOTE:>\nC<require> is lexically scoped:\n\n    sub do-something {\n       require MyModule <&something>;\n       say ::('MyModule'); # MyModule symbol exists here\n       something() # &something will be defined here\n    }\n    say ::('MyModule'); # This will NOT contain the MyModule symbol\n    do-something();\n    # &something will not be defined here\n\nIf C<MyModule> doesn't export C<&something> then C<require> will fail.\n\nA C<require> with compile-time symbol will install a placeholder\nC<package> that will be updated to the loaded module, class, or package.\nNote that the placeholder will be kept, B<even if require failed to load\nthe module.> This means that checking if a module loaded like this is\nwrong:\n\n    # *** WRONG: ***\n    try require Foo;\n    if ::('Foo') ~~ Failure { say \"Failed to load Foo!\"; }\n    # *** WRONG: ***\n\nAs the compile-time installed package causes C<::('Foo')> to never be\na L<C<Failure>|/type/Failure>. The correct way is:\n\n    # Use return value to test whether loading succeeded:\n    (try require Foo) === Nil and say \"Failed to load Foo!\";\n\n    # Or use a runtime symbol lookup with require, to avoid compile-time\n    # package installation:\n    try require ::('Foo');\n    if ::('Foo') ~~ Failure {\n        say \"Failed to load Foo!\";\n    }\n\nIn the current (6.d) version of the language, C<require>d symbols are no longer\ntransitively exposed, which means that you need to import symbols from the\nmodule they were originally declared, not from the module where they have\nbeen imported.\n\n=head2 Lexical module loading\n\nRaku takes great care to avoid global state, i.e. whatever you do in\nyour module, it should not affect other code. For instance, that's why\nsubroutine definitions are lexically (C<my>) scoped by default. If you want\nothers to see them, you need to explicitly make them C«our» scoped or export\nthem.\n\nClasses are exported by default on the assumption that loading a module will not\nbe of much use when you cannot access the classes it contains. Loaded classes\nare thus registered only in the scope which loaded them in the first place\nN<This change was introduced in late 2016. If you are using versions older than\nthis, behavior will be different>. This means that we will have to C<use> a\nclass in every scope in which we actually employ it.\n\n=for code :skip-test<needs dummy module>\nuse Foo;           # Foo has \"use Bar\" somewhere.\nuse Bar;\nmy $foo = Foo.new;\nmy $bar = Bar.new;\n\n=head2 Exporting and selective importing\n\n=head3 is export\n\nPackages, subroutines, variables, constants, and enums are exported by marking\nthem with the L<is export|/routine/is export> trait (also note the tags available for indicating\nauthors and versions).\n\n    =begin code :solo\n    unit module MyModule:ver<1.0.3>:auth<John Hancock (jhancock@example.com)>;\n    our $var is export = 3;\n    sub foo is export { ... };\n    constant FOO is export = \"foobar\";\n    enum FooBar is export <one two three>;\n\n    # for multi methods, if you declare a proto you\n    # only need to mark the proto with is export\n    proto quux(Str $x, |) is export { * };\n    multi quux(Str $x) { ... };\n    multi quux(Str $x, $y) { ... };\n\n    # for multi methods, you only need to mark one with is export\n    # but the code is most consistent if all are marked\n    multi quux(Str $x) is export { ... };\n    multi quux(Str $x, $y) is export { ... };\n\n    # Packages like classes can be exported too\n    class MyClass is export {};\n\n    # If a subpackage is in the namespace of the current package\n    # it doesn't need to be explicitly exported\n    class MyModule::MyClass {};\n    =end code\n\nAs with all traits, if applied to a routine, C«is export» should appear after\nany argument list.\n\n    =begin code\n    sub foo(Str $string) is export { ... }\n    =end code\n\nYou can pass named parameters to C<is export> to group symbols for exporting\nso that the importer can pick and choose. There are three predefined\ntags: C<ALL>, C<DEFAULT> and C<MANDATORY>.\n\n    =begin code :solo\n    # lib/MyModule.rakumod\n    unit module MyModule;\n    sub bag        is export             { ... }\n    # objects with tag ':MANDATORY' are always exported\n    sub pants      is export(:MANDATORY) { ... }\n    sub sunglasses is export(:day)       { ... }\n    sub torch      is export(:night)     { ... }\n    sub underpants is export(:ALL)       { ... }\n    =end code\n\n    =begin code :skip-test<needs dummy module>\n    # main.raku\n    use lib 'lib';\n    use MyModule;          # bag, pants\n    use MyModule :DEFAULT; # the same\n    use MyModule :day;     # pants, sunglasses\n    use MyModule :night;   # pants, torch\n    use MyModule :ALL;     # bag, pants, sunglasses, torch, underpants\n    =end code\n\nB<Note>: there currently is no way for the user to import a single\nobject if the module author hasn't made provision for that, and it is\nnot an easy task at the moment (see\nL<RT #127305|https://github.com/Raku/old-issue-tracker/issues/5063>).\nOne way\nthe author can provide such access is to give each C<export> trait its\nown unique tag. (And the tag can be the object name!). Then the user can\neither (1) import all objects:\n\n=begin code :skip-test<needs dummy module>\nuse Foo :ALL;\n=end code\n\nor (2) import one or more objects selectively:\n\n    =begin code :skip-test<needs dummy module>\n    use Foo :bar, :s5;\n    =end code\n\nNotes:\n\n1. The C<:MANDATORY> tag on an exported sub ensures it will be exported\nno matter whether the using program adds any tag or not.\n\n2. All exported subs without an explicit tag are implicitly C<:DEFAULT>.\n\n3. The space after the module name and before the tag is mandatory.\n\n4. Multiple import tags may be used (separated by commas).  For example:\n\n    =begin code :skip-test<needs dummy module>\n    # main.raku\n    use lib 'lib';\n    use MyModule :day, :night; # pants, sunglasses, torch\n    =end code\n\n5. Multiple tags may be used in the C<export> trait, but they must\n   all be separated by commas or whitespace.\n\n   =begin code\n   sub foo() is export(:foo :s2 :net) {}\n   sub bar() is export(:bar, :s3, :some) {}\n   =end code\n\n=head3 UNIT::EXPORT::*\n\nBeneath the surface, C<is export> is adding the symbols to a C<UNIT>\nscoped package in the C<EXPORT> namespace. For example, C<is\nexport(:FOO)> will add the target to the C<UNIT::EXPORT::FOO>\npackage. This is what Raku is really using to decide what to import.\n\n    =begin code :solo\n    unit module MyModule;\n\n    sub foo is export { ... }\n    sub bar is export(:other) { ... }\n    =end code\n\nIs the same as:\n\n    =begin code :solo\n    unit module MyModule;\n\n    my package EXPORT::DEFAULT {\n        our sub foo { ... }\n    }\n\n    my package EXPORT::other {\n        our sub bar { ... }\n    }\n    =end code\n\nFor most purposes, C<is export> is sufficient but the C<EXPORT>\npackages are useful when you want to produce the exported symbols\ndynamically. For example:\n\n    =begin code :solo\n    # lib/MyModule.rakumod\n    unit module MyModule;\n\n    my package EXPORT::DEFAULT {\n       for <zero one two three four>.kv -> $number, $name {\n          for <sqrt log> -> $func {\n             OUR::{'&' ~ $func ~ '-of-' ~ $name } := sub { $number.\"$func\"() };\n          }\n       }\n    }\n    =end code\n\n    =begin code :skip-test<needs dummy module>\n    # main.raku\n    use MyModule;\n    say sqrt-of-four; # OUTPUT: «2␤»\n    say log-of-zero;  # OUTPUT: «-Inf␤»\n    =end code\n\n=head3 X<EXPORT|Subroutines,sub EXPORT>\n\nYou can export arbitrary symbols with an C<EXPORT> sub. C<EXPORT>\nmust return a L<C<Map>|/type/Map>, where the keys are the symbol names and\nthe values are the desired values. The names should include the sigil\n(if any) for the associated type.\n\n=begin code\n# lib/MyModule.rakumod\n\nclass MyModule::Class { }\n\nsub EXPORT {\n    Map.new:\n      '$var'      => 'one',\n      '@array'    => <one two three>,\n      '%hash'     => %( one => 'two', three => 'four' ),\n      '&doit'     => sub { say 'Greetings from exported sub' },\n      'ShortName' => MyModule::Class\n}\n=end code\n\nWhich is going to be used from this main file:\n\n=begin code :skip-test<needs dummy module>\n# main.raku\nuse lib 'lib';\nuse MyModule;\nsay $var;          # OUTPUT: «one␤»\nsay @array;        # OUTPUT: «(one two three)␤»\nsay %hash;         # OUTPUT: «{one => two, three => four}␤»\ndoit();            # OUTPUT: «Greetings from exported sub␤»\nsay ShortName.new; # OUTPUT: «MyModule::Class.new␤»\n=end code\n\nPlease note that C<EXPORT> can't be declared inside a\nL<package|/language/packages> because it is part of the compunit rather than the\npackage.\n\nWhereas C<UNIT::EXPORT> packages deal with the named parameters passed to\nC<use>, the C<EXPORT> sub handles positional parameters. If you pass positional\nparameters to C<use>, they will be passed to C<EXPORT>. If a positional is\npassed, the module no longer exports default symbols. You may still import them\nexplicitly by passing C<:DEFAULT> to C<use> along with your positional\nparameters.\n\n=begin code\n# lib/MyModule\n\nclass MyModule::Class {}\n\nsub EXPORT($short_name?) {\n    Map.new: do $short_name => MyModule::Class if $short_name\n}\n\nsub always is export(:MANDATORY) { say \"works\" }\n\n#import with :ALL or :DEFAULT to get\nsub shy is export { say \"you found me!\" }\n=end code\n\nUsed from this main program\n\n=begin code :skip-test<needs dummy module>\n# main.raku\nuse lib 'lib';\nuse MyModule 'foo';\nsay foo.new(); # OUTPUT: «MyModule::Class.new␤»\n\nalways();      # OK   - is imported\nshy();         # FAIL - «shy used at line 8. Did you mean 'say'?»\n=end code\n\nYou can combine C<EXPORT> with type captures for interesting effect. This\nexample creates a C<?> postfix which will only work on L<C<Cool>|/type/Cool>s;\nplease note that, by using C<$_> as an argument, we don't need to use a\nvariable in the routine body and use just C<.so>, acting by default on the\ntopic variable.\n\n=begin code\n# lib/MakeQuestionable.rakumod\nsub EXPORT(::Questionable) {\n    my multi postfix:<?>(Questionable $_) { .so };\n    Map.new: '&postfix:<?>' => &postfix:<?>,\n}\n=end code\n\nWhich is used from here:\n\n=begin code :skip-test<needs dummy module>\nuse lib 'lib';\nuse MakeQuestionable Cool;\nsay ( 0?, 1?, {}?, %( a => \"b\" )? ).join(' '); # OUTPUT: «False True False True␤»\n=end code\n\nBe careful I<not> to put C<sub EXPORT> after L«C<unit> declarator|/syntax/unit».\nIf you do so, it'll become just a sub inside your package, rather than the\nspecial export sub:\n\n=for code :solo\nunit module Bar;\nsub EXPORT { Map.new: Foo => &say } # WRONG!!! Sub is scoped wrong\n\nAs explained in L<its definition|/language/using-modules/code#EXPORT>, C<sub EXPORT> is\npart of the I<compunit>, not the package. So this would be the right way to\ndo it:\n\n=for code :solo\nsub EXPORT { Map.new: Foo => &say } # RIGHT!!! Sub is outside the module\nunit module Bar;\n\n\n=head2 Introspection\n\nTo list exported symbols of a module first query the export tags supported by\nthe module.\n\n    use URI::Escape;\n    say URI::Escape::EXPORT::.keys;\n    # OUTPUT: «(DEFAULT ALL)␤»\n\nThen use the tag you like and pick the symbol by its name.\n\n    say URI::Escape::EXPORT::DEFAULT::.keys;\n    # OUTPUT: «(&uri-escape &uri-unescape &uri_escape &uri_unescape)␤»\n    my &escape-uri = URI::Escape::EXPORT::DEFAULT::<&uri_escape>;\n\n\n=head1 Documentation about Modules\n\n=item1 L<Using Modules: An Introduction|/language/using-modules/introduction>\n=item2 L<Using Modules: Finding and Installing|/language/using-modules/finding-installing>\n=item2 L<Using Modules: The Code|/language/using-modules/code> (this page)\n\n=item1 L<Making Modules: Introduction|/language/making-modules/introduction>\n=item2 L<Making Modules: The Code|/language/making-modules/code>\n\nWant to distribute your modules?\n=item1 L<Distributions: An introduction|/language/distributions/introduction>\n=item2 L<Distributions: The Configuration and Structure|/language/distributions/configuration-structure>\n=item2 L<Distributions: The Tools|/language/distributions/tools>\n=item2 L<Distributions: Testing|/language/distributions/testing>\n=item2 L<Distributions: Uploading|/language/distributions/uploading>\n\n\n=end pod\n"
  },
  {
    "path": "doc/Language/using-modules/finding-installing.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Modules\") :category(\"tutorial\")\n\n=TITLE Using modules: finding and installing\n\n=SUBTITLE How to find and install Raku modules\n\n=head1 Finding a module for your needs\n\n=head2 Quick Search\n\nThe quick way to find modules from the command line is by using C<zef search>:\n\n=for code :lang<shell>\nzef search WWW\n\nwill return a list of modules that includes WWW in their name, for\ninstance.\n\n=head2 Powerful Search\n\nModules are listed in L<the Raku ecosystem|https://raku.land> and can be\nsearched there.  This is particularly useful when the quick search\ndoesn't come up with exactly one hit.\n\n=head1 Installing the module\n\nL<C<zef>|https://github.com/ugexe/zef> is the application used for installing\nmodules in Raku.\n\n=for code :lang<shell>\nzef install WWW\n\nwill install the module with that particular name, if it is not already\ninstalled N<If it's installed, it will reinstall only if the version of\nthe module is newer than the one installed>.\n\n=head1 Finding installed modules\n\nIt is up to the module installer to know where C<compunit> expects modules to be\nplaced. There will be a location provided by the\nL<distribution|/routine/distribution> and in the current home directory. In\nany case, letting the module installer deal with your modules is a safe bet.\n\n=begin code :lang<shell>\ncd your-module-dir\nzef --force install .\n=end code\n\nX<|Syntax,use lib>\nA user may have a collection of modules not found in the normal ecosystem,\nmaintained by a module or package manager, but needed regularly.  Instead of\nusing the C<use lib> L<pragma|/language/pragmas#lib> one\ncan use the C<RAKULIB> environment variable to point to module locations.\nFor example:\n\n=for code :lang<shell>\nexport RAKULIB=/path/to/my-modules,/path/to/more/modules\n\nNote that the comma (',') is used as the directory separator.\n\nThe directories in the C<RAKULIB> path will be searched for modules when\nRaku C<need>s, C<use>s or C<require>s them. Directories that start with a\ndot are ignored and symlinks are followed.\n\nTo avoid performance penalties at module load time, you may need to ensure\nthat directories added to this path are not too large; see\nL<here|/language/traps#Filesystem_repositories> for more information.\n\n\n=head1 Documentation about Modules\n\n=item1 L<Using Modules: An Introduction|/language/using-modules/introduction>\n=item2 L<Using Modules: Finding and Installing|/language/using-modules/finding-installing> (this page)\n=item2 L<Using Modules: The Code|/language/using-modules/code>\n\n=item1 L<Making Modules: Introduction|/language/making-modules/introduction>\n=item2 L<Making Modules: The Code|/language/making-modules/code>\n\nWant to distribute your modules?\n=item1 L<Distributions: An introduction|/language/distributions/introduction>\n=item2 L<Distributions: The Configuration and Structure|/language/distributions/configuration-structure>\n=item2 L<Distributions: The Tools|/language/distributions/tools>\n=item2 L<Distributions: Testing|/language/distributions/testing>\n=item2 L<Distributions: Uploading|/language/distributions/uploading>\n\n\n=end pod\n"
  },
  {
    "path": "doc/Language/using-modules/introduction.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Modules\") :category(\"tutorial\")\n\n=TITLE Modules: an introduction\n\n=SUBTITLE Modules and how they work\n\nI<N.B.> \"Module\" is an overloaded term in Raku; this document\nfocuses on use of the C<module> declarator.\n\n=head1 What are modules?\n\nModules, like classes and grammars, are a kind of\nL<package|/language/packages>. Module objects are instances of the\nC<ModuleHOW> metaclass; this provides certain capabilities useful for\ncreating namespaces, versioning, delegation and data encapsulation (see\nalso L<class|/syntax/class> and L<role|/syntax/role>).\n\nTo create a module, use the C<module> declarator:\n\n    module M {}\n    say M.HOW;   # OUTPUT: «Perl6::Metamodel::ModuleHOW.new␤»\n\nHere we define a new module named C<M>; introspection with C<HOW>\nconfirms that the metaclass underlying C<M> is\nC<Perl6::Metamodel::ModuleHOW>.\n\n\n=head2 When to use modules\n\nModules are primarily useful for encapsulating code and data that\ndo not belong inside a class or role definition. Module contents\n(classes, subroutines, variables, etc.) can be exported from a\nmodule with the C<is export> trait; these are available in the\ncaller's namespace once the module has been imported with C<import>\nor C<use>. A module can also selectively expose symbols within its\nnamespace for qualified reference via C<our>.\n\n=head2 X<Working with modules|Language,import>\n\nTo illustrate module scoping and export rules, let's begin by\ndefining a simple module C<M>:\n\n    module M {\n      sub greeting ($name = 'Camelia') { \"Greetings, $name!\" }\n      our sub loud-greeting (--> Str)  { greeting().uc       }\n      sub friendly-greeting is export  { greeting('friend')  }\n    }\n\nRecall that subroutines are lexically scoped unless otherwise specified\n(declarator L<C<sub>|/syntax/sub> is equivalent to C<my sub>), so\nC<greeting> in the above example is lexically scoped to the module and\ninaccessible outside of it. We've also defined C<loud-greeting> with the\nC<our> declarator, which means that in addition to being lexically\nscoped it is aliased in the module's symbol table. Finally,\nC<friendly-greeting> is marked for export; it will be registered in the\nI<caller's> symbol table when the module is imported:\n\n=begin code :skip-test<needs dummy module>\nimport M;               # import the module\nsay M::loud-greeting;   # OUTPUT: «GREETINGS, CAMELIA!␤»\nsay friendly-greeting;  # OUTPUT: «Greetings, friend!␤»\n=end code\n\n\n=head1 Documentation about Modules\n\n=item1 L<Using Modules: An Introduction|/language/using-modules/introduction> (this page)\n=item2 L<Using Modules: Finding and Installing|/language/using-modules/finding-installing>\n=item2 L<Using Modules: The Code|/language/using-modules/code>\n\n=item1 L<Making Modules: Introduction|/language/making-modules/introduction>\n=item2 L<Making Modules: The Code|/language/making-modules/code>\n\nWant to distribute your modules?\n=item1 L<Distributions: An introduction|/language/distributions/introduction>\n=item2 L<Distributions: The Configuration and Structure|/language/distributions/configuration-structure>\n=item2 L<Distributions: The Tools|/language/distributions/tools>\n=item2 L<Distributions: Testing|/language/distributions/testing>\n=item2 L<Distributions: Uploading|/language/distributions/uploading>\n\n\n=end pod\n"
  },
  {
    "path": "doc/Language/variables.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Variables\n\n=SUBTITLE Variables in Raku\n\nVariables are symbolic names for values or L<containers|/language/containers>.\nVariable declarations or assignment of values may create a container on the fly.\nVariable names can start with or without a special character called a I<sigil>,\nfollowed optionally by a second special character named I<twigil> and then an\nL<identifier|/language/syntax#Identifiers>.\n\nX<|Syntax,$>\nX<|Syntax,@>\nX<|Syntax,% (sigil)>\nX<|Syntax,&>\n=head1 Sigils\n\nThere are four sigils. The scalar-sigil C<$>, the positional-sigil C<@>, the\nassociative-sigil C<%> and the callable-sigil C<&>.\n\nSigils provide a link between syntax, the type system and\nL<containers|/language/containers>. They provide a shortcut for the most\ncommon type constraints when declaring variables, and serve as markers\nfor L<string interpolation|/language/quoting#Interpolation:_qq>. The\nL<positional-sigil|/language/containers#Flattening,_items_and_containers>\nand the\nL<associative-sigil|/language/containers#Flattening,_items_and_containers>\nprovide type constraint that enforce base type\nL<subscripts|/language/subscripts> required to know what\nmethods to dispatch to. The\nL<callable-sigil|/language/containers#Callable_containers> does the same\nfor function calls. The latter also tells the compiler where parentheses\nfor calls can be omitted. The positional and associative-sigil also\nsimplify assignment by flattening by default.\n\n=begin table\n\nSigil   Type constraint          Default type  Assignment  Examples\n=====   ===============          ============  ==========  ========\n$       Mu (no type constraint)  Any           item        Int, Str, Array, Hash\n@       Positional               Array         list        List, Array, Range, Buf\n%       Associative              Hash          list        Hash, Map, Pair\n&       Callable                 Callable      item        Sub, Method, Block, Routine\n\n=end table\n\nExamples:\n\n    my $square = 9 ** 2;\n    my @array  = 1, 2, 3;   # Array variable with three elements\n    my %hash   = London => 'UK', Berlin => 'Germany';\n\nX<|Syntax,is (type of variable)>\nThe type to which the variable will be bound can be set with C<is> in the\ndeclaration of the variable.  Assuming we have a C<FailHash> class:\n\n    class FailHash is Hash {\n        has Bool $!final = False;\n        multi method AT-KEY ( ::?CLASS:D: Str:D \\key ){\n            fail X::OutOfRange.new(:what(\"Hash key\"), :got(key),\n              :range(self.keys)) if $!final && !self.EXISTS-KEY(key);\n            callsame  # still not final, so do normal action from Hash\n        }\n\n        method finalize() {\n            $!final = True\n        }\n    }\n\nOne can then define a C<%h> variable of this type using C<is>:\n\n=for code :preamble<class FailHash {}>\nmy %h is FailHash = oranges => \"round\", bananas => \"bendy\";\n\nAnd then run the following code:\n\n=for code :preamble<my %h>\nsay %h<oranges>;\n# OUTPUT: «round␤»\n%h.finalize;\nsay %h<cherry>;\nCATCH { default { put .^name, ': ', .Str } }\n# OUTPUT: «X::OutOfRange: Hash key out of range. Is: cherry, should be in (oranges bananas)»\n\nFor information on variables without sigils, see\nL<sigilless variables|#Sigilless_variables>.\n\n=head2 Item and list assignment\n\nThere are two types of variable assignment, I<item assignment> and I<list\nassignment>.\n\nAn item assignment copies a single value from the right-hand side into a Scalar\nvariable on the left. An assignment to anything other than a simple Scalar\nvariable is parsed as a list assignment. A list assignment leaves the choice of\nwhat the assignment operation entails to the variable on the left. For example,\nL<C<Array>|/type/Array> variables (C<@> sigil) empty themselves on list assignment,\nand then iteratively copy all values from the right-hand side into themselves as\nelements.\n\nThe two types of assignment both use the equal sign C<=> as their operator and\nare both right associative, but differ in operator precedence: item assignment\nhas a higher precedence level (level: Item assignment) than list assignment\n(level: List prefix). In situations in which a comma-separated list of elements\nis assigned, these precedences should in particular be contrasted with that of\nthe comma operator C<,> which sits in between. So without any list-delimiting\nparentheses (or other construct to hold the list's elements together), item\nassignment will only assign the first element of the specified list, and not the\nfull list.\n\nIn an assignment expression the context of the left-hand side determines whether\nan C<=> means item or list assignment. As mentioned, item assignment is\nrestricted to simple Scalar variables. Accordingly, assignment to a Scalar\ncontainer (scalar-context) triggers item assignment, unless the Scalar is\nexplicitly put in list-context by surrounding parentheses C<( )>:\n\n    my $a;\n    $a = 1,2,3;        # item assignment to Scalar\n    say $a;            # OUTPUT: «1␤» ( '=' has higher precedence than ',' )\n\n    my $b = 1,2,3;     # item assignment to Scalar (same as preceding example)\n    say $b;            # OUTPUT: «1␤»\n\n    my $c;\n    ($c) = 4,5,6;      # list assignment to Scalar; '( )' is list-contextualizer\n    say $c;            # OUTPUT:  «(4,5,6)␤»\n\n    (my $d) = 4,5,6;   # list assignment to Scalar (same as preceding example)\n    say $d;            # OUTPUT:  «(4,5,6)␤»\n\nAssignment to a List container (list-context) always triggers list assignment:\n\n    my @e;\n    @e = 7,8,9;                    # list assignment to Array\n    say @e;                        # OUTPUT:  «[7,8,9]␤»\n\n    my $f;\n    ($f,) = 7,8,9;                 # list assignment to List with one element\n    say $f;                        # OUTPUT:  «7␤»\n    say ( ($f,) ).VAR.^name;       # OUTPUT:  «List␤»\n\n    # ATTENTION: special declaration syntax!\n    my ($g) = 7,8,9;               # list assignment to List with one element\n    say $g;                        # OUTPUT:  «7␤»\n    say ( ($g) ).VAR.^name         # OUTPUT:  «List␤»\n\nThe last two examples above are simple I<destructuring assignments> that select\nthe first item of the right-hand side list. See for a more elaborate discussion\nof destructuring assignments in the context of variable declarations the section\non L<declaring a list of variables with lexical or package\nscope|/language/variables#index-entry-declaring_a_list_of_variables>.\n\nChained assignments are parsed having regard to the precedence of the assignment\noperators and, where applicable, their right associativity. For instance, in the\nexample below there is one chained assignment statement comprising two\nassignment operators. The assignment to C<@array> is a list assignment having a\nlower precedence than the item assignment to the Scalar variable C<$num>. The\nassignment expression involving the item assignment to the Scalar variable\nC<$num> is thus evaluated first. It returns the assigned value C<42>, which in\nturn forms part of the List C<(42, \"str\")> constructed by the comma operator\nthat also has a higher precedence than the list assignment. Finally, the\nList C<(42, \"str\")> is list-assigned to C<@array>:\n\n    my @array;\n    @array = my $num = 42, \"str\";   # parsed as @array = ( (my $num = 42), \"str )\n    say @array.raku;                # OUTPUT: «[42, \"str\"]␤» (an Array)\n    say $num.raku;                  # OUTPUT: «42␤» (a Num)\n\nHere's a variant:\n\n    my ( @foo, $bar );\n    @foo = ($bar) = 42, \"str\";       # parsed as @foo = ( $bar = (42, \"str\") )\n    say $bar.raku;                   # OUTPUT: «$(42, \"str\")␤» (a List)#\n    say @foo.raku;                   # OUTPUT: «[(42, \"str\"),]␤» (an Array)\n\nIn this case, the list contextualizer C<( )> puts C<$bar> in a list context, and\nthus triggers a list assignment to the Scalar variable C<$bar>. This means that\nthere are two chained list assignments, both having a lower precedence than the\ncomma operator C<,> that constructs the List C<(42, \"str\")>. Due to their right\nassociativity, the list assignment expression that is evaluated first is the\nassignment to C<$bar>, which returns the assigned value C<$(42, \"str\")>, i.e. a\nScalar containing a two-element List. This value is in turn list-assigned to\nC<@array>, such that it becomes an Array with a single element, namely a List.\n\nSee L<operators|/language/operators> for more details on precedence and\nassociativity.\n\nX<|Syntax,\\ (sigilless variables)>\n=head2 Sigilless variables\n\nUsing the C<\\> prefix, it's possible to create variables that do not\nhave a sigil:\n\n    my \\degrees = pi / 180;\n    my \\θ       = 15 * degrees;\n\nNote that sigilless variable do not have associated\nL<containers|/language/containers>. This means C<degrees> and C<θ>, above,\nactually directly represent L<C<Num>|/type/Num>s. To illustrate, try assigning to one after\nyou've defined it:\n\n=begin code :skip-test<dies deliberately>\nθ = 3; # Dies with the error \"Cannot modify an immutable Num\"\n=end code\n\nSigilless variables do not enforce L<context|/language/contexts>, so they can be\nused to pass something on as-is:\n\n    sub logged(&f, |args) {\n        say('Calling ' ~ &f.name ~ ' with arguments ' ~ args.raku);\n        my \\result = f(|args);\n        #  ^^^^^^^ not enforcing any context here\n        say(&f.name ~ ' returned ' ~ result.raku);\n        return |result;\n    }\n\nSigilless variables can also be used for binding.\nSee L<Binding|/language/containers#Binding> for more information.\n\n=head1 X<Twigils|Syntax,Twigil>\n\nWe use the term twigils, a word play with I<sigil>, that indicates it uses two\nsymbols in front of an identifier; the second symbol will be placed between\nthe sigil and the identifier, and it will be related to the scoping of a\nvariable, that is, where that variable is defined and can be changed.\n\n=begin table\n\n    Twigil  Scope\n    ======  =====\n     none   Based only on declarator\n     *      Dynamic\n     ?      Compile-time variable\n     !      Attribute (class member)\n     .      Method (not really a variable)\n     <      Index into match object (not really a variable)\n     ^      Self-declared formal positional parameter\n     :      Self-declared formal named parameter\n     =      Pod variables\n     ~      The sublanguage seen by the parser at this lexical spot\n\n=end table\n\nX<|Language,Dynamically scoped variables>\nX<|Syntax,*>X<|Syntax,$*>X<|Syntax,@*>X<|Syntax,%*>X<|Syntax,&*>\n=head2 The C<*> twigil\n\nThis twigil is used for dynamic variables which are looked up through the\ncaller's, not through the outer, scope. Look at the example below.N<The example\nbelow cannot run correctly in the L<REPL|/language/REPL>, yielding an error about not finding the\ndynamic variables. Please test it by copy-pasting it into a file, then run the\nfile.>\n\n=begin code\nmy $lexical   = 1;\nmy $*dynamic1 = 10;\nmy $*dynamic2 = 100;\n\nsub say-all() {\n    say \"$lexical, $*dynamic1, $*dynamic2\";\n}\n\nsay-all();    # OUTPUT: 1, 10, 100\n\n{\n    my $lexical   = 2;\n    my $*dynamic1 = 11;\n    $*dynamic2    = 101;\n\n    say-all(); # OUTPUT: 1, 11, 101\n}\n\nsay-all();  # OUTPUT: 1, 10, 101\n=end code\n\nThe first time C<&say-all> is called, it prints \"C<1, 10, 100>\" just as one\nwould expect. The second time though, it prints \"C<1, 11, 101>\". This is\nbecause C<$lexical> isn't looked up in the caller's scope but in the scope\nC<&say-all> was defined in. The two dynamic variables are looked up in the\ncaller's scope and therefore have the values C<11> and C<101>. The third\ntime C<&say-all> is called C<$*dynamic1> isn't C<11> anymore, but\nC<$*dynamic2> is still C<101>. This stems from the fact that we declared a\nnew dynamic variable C<$*dynamic1> in the block and did not assign to the\nold variable as we did with C<$*dynamic2>.\n\nThe dynamic variables differ from other variable types in that referring\nto an undeclared dynamic variable is not a compile time error but a\nruntime L<C<Failure>|/type/Failure>, so a dynamic variable can be used\nundeclared as long as it's checked for definedness or used in a\nBoolean context before using it for anything else:\n\n=begin code\nsub foo() {\n    $*FOO // 'foo';\n}\n\nsay foo; # OUTPUT: «foo␤»\n\nmy $*FOO = 'bar';\n\nsay foo; # OUTPUT: «bar␤»\n=end code\n\nSee also L<trait is dynamic|/type/Variable#trait_is_dynamic>.\n\nDynamic variables can have lexical scope when declared with C<my> or package\nscope when declared with C<our>. Dynamic resolution and resolution through\nsymbol tables introduced with C<our> are two orthogonal issues.\n\nX<|Syntax,$?>X<|Syntax,?>X<|Syntax,$?>X<|Syntax,@?>X<|Syntax,%?>X<|Syntax,&?>\n=head2 The C<?> twigil\n\nCompile-time variables may be addressed via the C<?> twigil. They are known\nto the compiler and may not be modified after being compiled in. A popular\nexample for this is:\n\n    say \"$?FILE: $?LINE\"; # OUTPUT: \"hello.raku: 23\"\n                          # if this is the line 23 of a\n                          # file named \"hello.raku\"\n\nFor a list of these special variables, see\nL<compile-time variables|/language/variables#Compile-time_variables>.\n\nX<|Syntax,!>X<|Syntax,$!>X<|Syntax,@!>X<|Syntax,%!>X<|Syntax,&!>\n=head2 The C<!> twigil\n\nL<Attributes|/language/objects#Attributes> are variables that exist per instance\nof a class. They may be directly accessed from within the class via C<!>:\n\n    my class Point {\n        has $.x;\n        has $.y;\n\n        method Str() {\n            \"($!x, $!y)\"\n        }\n    }\n\nNote how the attributes are declared as C<$.x> and C<$.y> but are still\naccessed via C<$!x> and C<$!y>. This is because in Raku all attributes are\nprivate and can be directly accessed within the class by using\nC<$!attribute-name>. Raku may automatically generate accessor methods for\nyou though. For more details on objects, classes and their attributes see\nL<object orientation|/language/objects>.\n\n\nX<|Syntax,.>X<|Syntax,$.>X<|Syntax,@.>X<|Syntax,%.>X<|Syntax,&.>\n=head2 The C<.> twigil\n\nThe C<.> twigil isn't really for variables at all. In fact, something along\nthe lines of\n\n    my class Point {\n        has $.x;\n        has $.y;\n\n        method Str() {\n            \"($.x, $.y)\" # note that we use the . instead of ! this time\n        }\n    }\n\njust calls the methods C<x> and C<y> on C<self>, which are automatically\ngenerated for you because you used the C<.> twigil when the attributes were\ndeclared.  Note, however, that subclasses may override those methods. If you\ndon't want this to happen, use C<$!x> and C<$!y> instead.\n\nThe fact that the C<.> twigil does a method call implies that the following\nis also possible:\n\n    class SaySomething {\n        method a() { say \"a\"; }\n        method b() { $.a; }\n    }\n\n    SaySomething.b; # OUTPUT: «a␤»\n\nFor more details on objects, classes and their attributes and methods see\nL<object orientation|/language/objects>.\n\nX<|Syntax,^>X<|Syntax,$^>X<|Syntax,@^>X<|Syntax,%^>X<|Syntax,&^>\n=head2 The C<^> twigil\n\nThe C<^> twigil declares a formal positional parameter to blocks or subroutines;\nthat is, variables of the form C<$^variable> are a type of placeholder variable.\nThey may be used in bare blocks to declare formal parameters to that block. So\nthe block in the code\n\n    my @powers-of-three = 1,3,9…100;\n    say reduce { $^b - $^a }, 0, |@powers-of-three;\n    # OUTPUT: «61␤»\n\nhas two formal parameters, namely C<$a> and C<$b>. Note that even though C<$^b>\nappears before C<$^a> in the code, C<$^a> is still the first formal parameter\nto that block. This is because the placeholder variables are sorted in Unicode\norder.\n\nAlthough it is possible to use nearly any valid identifier as a placeholder\nvariable, it is recommended to use short names or ones that can be trivially\nunderstood in the correct order, to avoid surprise on behalf of the reader.\n\nNormal blocks and subroutines may also make use of placeholder variables but\nonly if they do not have an explicit parameter list.\n\n=begin code :skip-test<illustrates error>\nsub say-it    { say $^a; } # valid\nsub say-it()  { say $^a; } # invalid\n              { say $^a; } # valid\n-> $x, $y, $x { say $^a; } # invalid\n=end code\n\nPlaceholder variables cannot have type constraints or a variable name with a\nsingle uppercase letter (this is disallowed to enable catching some\nPerl-isms).\n\nThe C<^> twigil can be combined with any sigil to create a placeholder variable\nwith that sigil.  The sigil will have its normal semantic effects, as described\nin the L<Sigils table|#Sigils>. Thus C<@^array>, C<%^hash>, and C<&^fun> are all\nvalid placeholder variables.\n\n\nX<|Syntax,:>X<|Syntax,$:>X<|Syntax,@:>X<|Syntax,%:>X<|Syntax,&:>\n=head2 The C<:> twigil\n\nThe C<:> twigil declares a formal named parameter to a block or subroutine.\nVariables declared using this form are a type of placeholder variable too.\nTherefore the same things that apply to variables declared using the C<^>\ntwigil also apply here (with the exception that they are not positional and\ntherefore not ordered using Unicode order). For instance:\n\n    say { $:add ?? $^a + $^b !! $^a - $^b }( 4, 5 ) :!add\n    # OUTPUT: «-1␤»\n\nSee L<^|/syntax/$CIRCUMFLEX_ACCENT> for more details about placeholder variables.\n\n=head3 A note on C<^> and C<:>\n\nUnlike other twigils, C<^> and C<:> I<declare> variables, which can then be\nreferred to without that twigil.  Thus, the previous example could be written as:\n\n    say { $:add ?? $^a + $^b !! $a - $b }( 4, 5 ) :!add      # OUTPUT: «-1␤»\n\nThat is, once you have used C<$^a> to declare C<$a>, you can refer to that variable\nin the same scope with I<either> C<$^a> or C<$a>.  The same is true for C<:>: after\ndeclaring C<$:add>, you are free to refer to that declared variable with C<$add> if\nyou prefer.\n\nIn some instances, this is just a convenience – but it can be much more significant\nwhen dealing with nested blocks.  For example:\n\n    { say $^a; with \"inner\" { say $^a } }(\"outer\");       # OUTPUT: «outer␤inner␤»\n    { say $^a; with \"inner\" { say $a } }(\"outer\");        # OUTPUT: «outer␤outer␤»\n\nThe first line declares I<two> formal positional parameters, while the second declares\nonly one (but refers to it twice).  This can be especially significant with constructs\nsuch as C<with>, C<for>, and C<if> that are often used without much consideration of\nthe fact that they create blocks.\n\nJust like the C<^>twigil, the C<:> twigil can be combined with any sigil; using\nC<:> with a sigil will create a formal named parameter with that sigil (applying\nthe L<semantics of that sigil|#Sigils>).  Thus C<@:array>, C<%:hash>, and\nC<&:fun> are all valid, and each creates a formal named parameter with the\nspecified sigil.\n\nX<|Syntax,=>X<|Syntax,$=>X<|Syntax,@=>X<|Syntax,%=>X<|Syntax,&=>\n=head2 The C<=> twigil\n\nThe C<=> twigil is used to access Pod variables. Every Pod block in the\ncurrent file can be accessed via a Pod object, such as C<$=data>,\nC<$=SYNOPSIS> or C<=UserBlock>. That is: a variable with the same name of\nthe desired block and a C<=> twigil.\n\n=begin code\n=begin Foo\n...\n=end Foo\n# after that, $=Foo gives you all Foo-Pod-blocks\n=end code\n\nYou may access the Pod tree which contains all Pod structures as a\nhierarchical data structure through C<$=pod>.\n\nNote that all those C<$=someBlockName> support the L<C<Positional>|/type/Positional> and the\nL<C<Associative>|/type/Associative> roles.\n\n=head2 The C<~> twigil\n\nThe C<~> twigil is for referring to sublanguages (called slangs). The\nfollowing are useful:\n\nX<|Variables,$~MAIN>X<|Variables,$~Quote>X<|Variables,$~Quasi>\nX<|Variables,$~Regex>X<|Variables,$~Trans>X<|Variables,$~P5Regex>\n\n=begin table\n    $~MAIN       the current main language (e.g., Raku statements)\n    $~Quote      the current root of quoting language\n    $~Quasi      the current root of quasiquoting language\n    $~Regex      the current root of regex language\n    $~Trans      the current root of transliteration language\n    $~P5Regex    the current root of the Perl regex language\n=end table\n\nYou C<augment> these languages in your current lexical scope.\n\n=begin code :solo\nuse MONKEY-TYPING;\naugment slang Regex {  # derive from $~Regex and then modify $~Regex\n    token backslash:std<\\Y> { YY };\n}\n=end code\n\nSee L<I<slangs>|/language/slangs> for more.\n\nX<|Syntax,supersede>\n=head1 Variable declarators and scope\n\nMost of the time it's enough to create a new variable using the C<my>\nkeyword:\n\n    my $amazing-variable = \"World\";\n    say \"Hello $amazing-variable!\"; # OUTPUT: «Hello World!␤»\n\nHowever, there are many declarators that change the details of scoping\nbeyond what L<Twigils|#Twigils> can do.\n\n=for table\n    Declarator    Effect\n    ==========    ======\n    my            Introduces lexically scoped names\n    our           Introduces package-scoped names\n    has           Introduces attribute names\n    anon          Introduces names that are private to the construct\n    state         Introduces lexically scoped but persistent names\n    constant      Introduces names that are immutably bound at compile time\n    augment       Adds definitions to an existing name\n    supersede     Replaces definitions of an existing name\n\nThere are also two keywords that act on predefined variables:\n\n=for table\n    Keyword   Effect\n    =======   ======\n    temp      Restores a variable's value at the end of scope\n    let       Restores a variable's value at the end of scope if the block exits unsuccessfully\n\n=head2 The C<my> declarator\n\nDeclaring a variable with C<my> gives it lexical scope. This means it only\nexists within the current block. For example:\n\n=begin code :skip-test<illustrates error>\n{\n    my $foo = \"bar\";\n    say $foo; # OUTPUT: «\"bar\"␤»\n}\nsay $foo; # Exception! \"Variable '$foo' is not declared\"\n=end code\n\nThis dies because C<$foo> is only defined as long as we are in the same\nscope.\n\nIn order to create more than one variable with a lexical scope in the same\nsentence surround the variables with parentheses:\n\n   my ( $foo, $bar );\n\nsee also L<Declaring a list of variables with lexical or package scope|/language/variables#index-entry-declaring_a_list_of_variables>.\n\nAdditionally, lexical scoping means that variables can be temporarily\nredefined in a new scope:\n\n    my $location = \"outside\";\n\n    sub outer-location {\n        # Not redefined:\n        say $location;\n    }\n\n    outer-location; # OUTPUT: «outside␤»\n\n    sub in-building {\n        my $location = \"inside\";\n        say $location;\n    }\n\n    in-building;    # OUTPUT: «inside␤»\n\n    outer-location; # OUTPUT: «outside␤»\n\nIf a variable has been redefined, any code that referenced the outer\nvariable will continue to reference the outer variable. So here,\nC<&outer-location> still prints the outer C<$location>:\n\n=begin code :skip-test<continued example>\nsub new-location {\n    my $location = \"nowhere\";\n    outer-location;\n}\n\nnew-location; # OUTPUT: «outside␤»\n=end code\n\nTo make C<new-location()> print C<nowhere>, make C<$location> a dynamic variable\nusing L<the * twigil|#The_*_twigil>. This twigil makes the compiler look up the\nsymbol in the calling scope instead of the outer scope after trying the local\nscope.\n\nC<my> is the default scope for subroutines, so C<my sub x() {}> and\nC<sub x() {}> do exactly the same thing.\n\nThis makes it easy for the compiler take care of several things\nbefore runtime, including:\n\n=item binding subroutine names as read-only (similar to C<constant>)\n=item reporting undeclared subroutines\n=item argument checking\n=item resolving multiple dispatch\n=item more detailed error messages\n=item optimizations\n\nIn general, when an item's visibility is directly associated with\nits location in the code, this makes it easier to understand and\nreason about the program, which enables not only a more helpful\ncompiler but also other tools, such as IDEs and debuggers.\n\nAlso note that although declarations of constants, enumerations,\nmodules, and types of various kinds (classes, subsets, grammars,\nroles) all default to package scoping (see C<our> below), you can\nprefix such a declaration with C<my> to keep it from being exposed\nin the API, which frees you to modify it in future revisions without\nbreaking dependents.  For example:\n\n    class Foo {                           # visible in GLOBAL\n        my class ImplementationDetail {   # hidden from users of Foo\n            # ...\n        }\n        # ...\n    }\n\n=head2 The C<our> declarator\n\nC<our> variables are created in the scope of the surrounding package. They also create\nan alias in the lexical scope, therefore they can be used like C<my> variables as well.\n\n    module M {\n        our $Var;\n        # $Var available here\n    }\n\n    # Available as $M::Var here.\n\nAlthough lexical scoping with C<my> has many advantages, sometimes\nwe need to share more widely than within a given lexical scope,\nand using the C<is export> trait can lead to namespace conflicts.\nPackage scoping with C<our> assigns symbols to distinct namespaces,\navoiding conflicts.  For example, to use the Cro clients for both\nHTTP and WebSockets in the same code, just refer to them as\nC<Cro::HTTP::Client> and C<Cro::WebSocket::Client> respectively.\n\nPackages are introduced by package declarators, such as C<class>,\nC<module>, C<grammar>, and (with caveats) C<role>.  An C<our> declaration\nwill make an installation in the enclosing package construct.  Then\nusers of your code (literally, with C<use>) can refer to C<our>-scoped\nentities in your package by providing the full package-qualified\nname of the entity.\n\nAll packages exist within a top-level package named C<GLOBAL> and\nthus are globally visible, so declaring an C<our>-scoped variable\nis declaring a global variable, even with namespace control.\nAnything that ends up visible via C<GLOBAL> is effectively part of\nyour API, so consider accordingly.\n\nThe kind of elements that are most likely to be shared default to\npackage (C<our>) scope, namely:\n=item type declarations, including C<class>, C<role>, C<grammar>, and C<subset>\n=item constants\n=item enumerations\n=item C<module> declarations\n\nItems that do I<not> default to package scope:\n=item subroutines default to lexical (C<my>) scope, as discussed above\n=item methods are scoped with C<has> (only visible through a method dispatch)\n=item variables have no default scope (although the most common choice here, C<my>, is also the shortest to type)\n\nIn order to create more than one variable with package scope,\nat the same time, surround the variables with parentheses:\n\n   our ( $foo, $bar );\n\nsee also L<the section on declaring a list of variables with lexical or package scope|/language/variables#index-entry-declaring_a_list_of_variables>.\n\n=head3 Scoping tips: C<my> vs C<our>\n\nIt can be a good idea to make an element I<less visible> than the default (for example, C<my> on constants for internal use or classes used to structure\nimplementation details). Whenever you need to expose something in the API, remember there are at least three ways:\n=item an C<our> scoped element, with access controlled by the package namespace\n=item a C<sub> (visible with the C<is export> trait), and potential access control through C<sub EXPORT>\n=item a C<method> (visible through its package-scoped C<class>)\n\nIn summary:\n=item Use C<my> scope for everything that's an implementation detail\n=item Also use C<my> scope for things that you plan to C<export>, but remember that exporting puts symbols into the single lexical scope of the consumer and\nrisks name clashes, so be thoughtful about exporting particularly generic names\n=item Use C<our> for things that are there to be shared, and when it's desired to use namespaces to avoid clashes\n=item The elements we'd most want to share default to C<our> scope anyway, so explicitly writing C<our> should give pause for thought\n\nX<|Language,declaring a list of variables>\n=head3 Declaring a list of variables with lexical (C<my>) or package (C<our>) scope\n\nIt is possible to scope more than one variable at a time, but both C<my>\nand C<our> require variables to be placed into parentheses:\n\n    my  (@a,  $s,  %h);   # same as my @a; my $s; my %h;\n    our (@aa, $ss, %hh);  # same as our @aa; our $ss; our %hh;\n\nThis can be used in conjunction with X«destructuring assignment|Language,destructuring assignment». Any\nassignment to such a list will take the number of elements provided in the left\nlist and assign corresponding values from the right list to them. Any missing\nelements are left will result in undefined values according to the type of the\nvariables.\n\n    my (Str $a, Str $b, Int $c) = <a b>;\n    say [$a, $b, $c].raku;\n    # OUTPUT: «[\"a\", \"b\", Int]␤»\n\nTo destructure a list into a single value, create a list literal with one\nelement by using C<($var,)>. When used with a variable declarator, providing\nparentheses around a single variable is sufficient.\n\n    sub f { 1,2,3 };\n    my ($a) = f;\n    say $a.raku;\n    # OUTPUT: «1␤»\n\nTo skip elements in the list use the anonymous state variable C<$>.\n\n    my ($,$a,$,%h) = ('a', 'b', [1,2,3], {:1th});\n    say [$a, %h].raku;\n    # OUTPUT: «[\"b\", {:th(1)}]␤»\n\n=head2 The C<has> declarator\n\nC<has> scopes attributes to instances of a class or role, and methods to\nclasses or roles. C<has> is implied for methods, so C<has method x() {}>\nand C<method x() {}> do the same thing.\n\nSee L<object orientation|/language/objects> for more documentation and some\nexamples.\n\n=head2 The C<anon> declarator\n\nThe C<anon> declarator prevents a symbol from getting installed in the lexical\nscope, the method table and everywhere else.\n\nFor example, you can use it to declare subroutines which know their own name,\nbut still aren't installed in a scope:\n\n    my %operations =\n        half   => anon sub half($x) { $x / 2 },\n        square => anon sub square($x) { $x * $x },\n        ;\n    say %operations<square>.name;       # square\n    say %operations<square>(8);         # 64\n\nSince it is a declarator, it can be applied anywhere anything is declared, for\ninstance for classes or even sigilless variables.\n\n    say anon class þ {};     # OUTPUT: «(þ)␤»\n    say anon sub þ  { 42 };  # OUTPUT: «&þ␤»\n\nSince these symbols are not installed in the scope, they can't be used by name.\nThey are useful, however, if they need to be assigned to an external variable\nand they need to know their own name, but this can be retrieved using\nintrospection.\n\n=for code\nmy $anon-class = anon class {\n    has $.bar;\n    method equal( ::?CLASS $foo ) {\n      return $foo.bar == $.bar;\n    }\n};\nsay $anon-class.new( :3bar).equal( $anon-class.new( :3bar ) );\n# OUTPUT: «True␤»\n\n\n\n\n=head2 The C<state> declarator\n\nC<state> declares lexically scoped variables, just like C<my>. However,\ninitialization happens exactly once, the first time the initialization\nis encountered in the normal flow of execution. Thus, state variables\nwill retain their value across multiple executions of the enclosing\nblock or routine.\n\nTherefore, the subroutine\n\n    sub a {\n        state @x;\n        state $l = 'A';\n        @x.push($l++);\n    };\n\n    say a for 1..6;\n\nwill continue to increment C<$l> and append it to C<@x> each time it is\ncalled. So it will output:\n\n=for code :lang<text>\n[A]\n[A B]\n[A B C]\n[A B C D]\n[A B C D E]\n[A B C D E F]\n\nSince they have a lexical scope, they are tied to the block in which they are\ndeclared.\n\n=for code\nsub foo () {\n  for 0..1 {\n    state $foo = 1;\n    say $foo++;\n  }\n};\nfoo;  # OUTPUT: «1␤2␤»\nfoo;  # OUTPUT: «1␤2␤»\n\nIn this case, a new state variable is created every time the block that\nruns the for loop is entered, which is why the state variable is reset\nin every call to C<foo>.\n\nThis works per \"clone\" of the containing code object, as in this\nexample:\n\n=for code\n({ state $i = 1; $i++.say; } xx 3).map: {$_(), $_()}; # OUTPUT: «1␤2␤1␤2␤1␤2␤»\n\nNote that this is B<not> a thread-safe construct when the same clone of\nthe same block is run by multiple threads.  Also remember that methods\nonly have one clone per class, not per object.\n\nAs with C<my>, a declaration of multiple C<state> variables must be placed\nin parentheses which can be omitted for a single variable.\n\nMany operators come with implicit binding which can lead to actions at a\ndistance.\n\nUse C<.clone> or coercion to create a new container that can be bound to.\n\n    my @a;\n    my @a-cloned;\n    sub f() {\n        state $i;\n        $i++;\n        @a       .push: \"k$i\" => $i;\n        @a-cloned.push: \"k$i\" => $i.clone;\n    };\n\n    f for 1..3;\n    say @a;        # OUTPUT: «[k1 => 3 k2 => 3 k3 => 3]␤»\n    say @a-cloned; # OUTPUT: «[k1 => 1 k2 => 2 k3 => 3]␤»\n\nState variables are shared between all threads. The result can be unexpected.\n\n    sub code(){ state $i = 0; say ++$i; $i };\n    await\n        start { loop { last if code() >= 5 } },\n        start { loop { last if code() >= 5 } };\n\n    # OUTPUT: «1␤2␤3␤4␤4␤3␤5␤»\n    # OUTPUT: «2␤1␤3␤4␤5␤»\n    # many other more or less odd variations can be produced\n\nX<|Language,anon state variables>X<|Language,nameless variables>X<|Variables,$ (variable)>\n=head3 The C<$> variable\n\nIn addition to explicitly declared named state variables, C<$> can be used\nas an anonymous state variable without an explicit C<state> declaration.\n\n    say \"1-a 2-b 3-c\".subst(:g, /\\d/, {<one two three>[$++]});\n    # OUTPUT: «one-a two-b three-c␤»\n\nFurthermore, state variables can be used outside of subroutines. You\ncould, for example, use C<$> in a one-liner to number the lines in a file.\n\n=begin code :lang<shell>\nraku -ne 'say ++$ ~ \" $_\"' example.txt\n=end code\n\nEach reference to C<$> within a lexical scope is in effect a separate\nvariable.\n\n=begin code :lang<shell>\nraku -e '{ say ++$; say $++  } for ^5'\n# OUTPUT: «1␤0␤2␤1␤3␤2␤4␤3␤5␤4␤»\n=end code\n\nThat is why, if you need to reference the same $ variable (or, for that matter,\nany of the other anon state variables C<@> and C<%>) more than once, a possible\nsolution is to bind another variable to it, although in this example it would be\nmore straightforward to just declare state $x and not use the magical/anonymous\nC<$> variable:\n\n=begin code\nsub foo () {\n    my $x := $;\n    $x++;\n    say $x;\n    $x = $x + 1;\n}\n\nfoo() for ^3; # OUTPUT: «1␤3␤5␤»\n=end code\n\nIn general, it is better style to declare a named state variable in case you\nhave to refer to it several times.\n\nNote that the implicit state declarator is only applied to the variable\nitself, not the expression that may contain an initializer. If the\ninitializer has to be called exactly once, the C<state> declarator has to be\nprovided.\n\n=begin code\nfor ^3 {       $ = .say } # OUTPUT: «0␤1␤2␤»\nfor ^3 { state $ = .say } # OUTPUT: «0␤»\n=end code\n\n=head3 The C<@> variable\n\nSimilar to the C<$> variable, there is also a L<C<Positional>|/type/Positional>\nanonymous state variable C<@>.\n\n    sub foo($x) {\n        say (@).push($x);\n    }\n\n    foo($_) for ^3;\n\n    # OUTPUT: «[0]\n    #          [0 1]\n    #          [0 1 2]␤»\n\nThe C<@> here is parenthesized in order to disambiguate the expression\nfrom a class member variable named C<@.push>.  Indexed access doesn't\nrequire this disambiguation but you will need to copy the value in order\nto do anything useful with it.\n\n    sub foo($x) {\n        my $v = @;\n        $v[$x] = $x;\n        say $v;\n    }\n\n    foo($_) for ^3;\n\n    # OUTPUT: «[0]\n    #          [0 1]\n    #          [0 1 2]␤»\n\nAs with C<$>, each mention of C<@> in a scope introduces a new anonymous\narray.\n\n=head3 The C<%> variable\n\nIn addition, there's an L<C<Associative>|/type/Associative> anonymous state\nvariable C<%>.\n\n    sub foo($x) {\n        say (%).push($x => $x);\n    }\n\n    foo($_) for ^3;\n\n    # OUTPUT: «{0 => 0}\n    #          {0 => 0, 1 => 1}\n    #          {0 => 0, 1 => 1, 2 => 2}␤»\n\nThe same caveat about disambiguation applies. As you may expect, indexed\naccess is also possible (with copying to make it useful).\n\n    sub foo($x) {\n        my $v = %;\n        $v{$x} = $x;\n        say $v;\n    }\n\n    foo($_) for ^3;\n\n    # OUTPUT: «{0 => 0}\n    #          {0 => 0, 1 => 1}\n    #          {0 => 0, 1 => 1, 2 => 2}␤»\n\nAs with the other anonymous state variables, each mention of C<%> within a\ngiven scope will effectively introduce a separate variable.\n\n=head2 The C<constant> declarator\n\nThe C<constant> declarator declares that the value it tags is not going to\nchange during its lifetime.\n\n=begin code\nconstant $pi2 = pi * 2;\n$pi2 = 6; # OUTPUT: «(exit code 1) Cannot assign to an immutable value␤\n=end code\n\nThe value is assigned at compile time. Since Raku modules are L<precompiled\nautomatically|/language/compilation>, constants defined in modules are not\nre-evaluated when the program is run. Please check\nL<the section on constants in the Terms page|/language/terms#Constants> for\nadditional information.\n\n=head2 The C<augment> declarator\n\nWith C<augment>, you can add methods, but not attributes, to existing classes and\ngrammars, provided you activated the C<MONKEY-TYPING> pragma first.\n\nSince classes are usually C<our> scoped, and thus global, this means modifying\nglobal state, which is strongly discouraged. For almost all situations, there\nare better solutions.\n\n    # don't do this\n    use MONKEY-TYPING;\n    augment class Int {\n        method is-answer { self == 42 }\n    }\n    say 42.is-answer;       # OUTPUT: «True␤»\n\n(In this case, the better solution would be to use a\nL<function|/language/functions>).\n\nFor a better, and safer example, this is a practical\nway to create a class module to extend L<C<IO::Path>|/type/IO::Path> by\nadding a currently missing method to yield the part of the C<basename>\nleft after the C<extension> is removed. (Note there\nis no clear developer consensus about what to call that\npart or even how it should be constructed.)\n\n=begin code :solo\nunit class IO::Barename is IO::Path;\n\nmethod new(|c) {\n    return self.IO::Path::new(|c);\n}\n\nuse MONKEY-TYPING;\naugment class IO::Path {\n    method barename {\n        self.extension(\"\").basename;\n    }\n}\n=end code\n\n=head2 The C<temp> keyword\n\nLike C<my>, C<temp> restores the old value of a variable at the end of its\nscope. However, C<temp> does not create a new variable.\n\n    my $in = 0; # temp will \"entangle\" the global variable with the call stack\n                # that keeps the calls at the bottom in order.\n    sub f(*@c) {\n        (temp $in)++;\n         \"<f>\\n\"\n         ~ @c».indent($in).join(\"\\n\")\n         ~ (+@c ?? \"\\n\" !! \"\")\n         ~ '</f>'\n    };\n    sub g(*@c) {\n        (temp $in)++;\n        \"<g>\\n\"\n        ~ @c».indent($in).join(\"\\n\")\n        ~ (+@c ?? \"\\n\" !! \"\")\n        ~ \"</g>\"\n    };\n    print g(g(f(g()), g(), f()));\n\n    # OUTPUT: «<g>\n    #           <g>\n    #            <f>\n    #             <g>\n    #             </g>\n    #            </f>\n    #            <g>\n    #            </g>\n    #            <f>\n    #            </f>\n    #           </g>\n    #          </g>␤»\n\n=head2 The C<let> keyword\n\nRestores the previous value if the block exits unsuccessfully. A\nsuccessful exit means the block returned a defined value or a list.\n\n    my $answer = 42;\n\n    {\n        let $answer = 84;\n        die if not Bool.pick;\n        CATCH {\n            default { say \"it's been reset :(\" }\n        }\n        say \"we made it 84 sticks!\";\n    }\n\n    say $answer;\n\nIn the above case, if the C<Bool.pick> returns true, the answer will\nstay as 84 because the block returns a defined value (C<say> returns\nC<True>). Otherwise the C<die> statement will cause the block to exit\nunsuccessfully, resetting the answer to 42.\n\n=head1 Type constraints and initialization\n\nVariables have a type constraint via the L<container|/language/containers> they\nare bound to, which goes between the declarator and the variable name. The\ndefault type constraint is L<C<Mu>|/type/Mu>. You can also use the trait\nL<of|/type/Variable#trait_of> to set a type constraint.\n\n=for code :skip-test<compilation error>\n    my Int $x = 42;\n    $x = 'a string';\n    CATCH { default { put .^name, ': ', .Str } }\n    # OUTPUT: «X::TypeCheck::Assignment: Type check failed in assignment to $x; expected Int but got Str (\"a string\")␤»\n\nIf a scalar variable has a type constraint but no initial value, it's\ninitialized with the type object of the default value of the container it's\nbound to.\n\n    my Int $x;\n    say $x.^name;       # OUTPUT: «Int␤»\n    say $x.defined;     # OUTPUT: «False␤»\n\nScalar variables without an explicit type constraint are typed as\nL<C<Mu>|/type/Mu> but default to the L<C<Any>|/type/Any> type object.\n\nVariables with the C<@> sigil are initialized with an empty\nL<C<Array>|/type/Array>; variables with the C<%> sigil are initialized with an\nempty L<C<Hash>|/type/Hash>.\n\nThe default value of a variable can be set with the C<is default> trait, and\nre-applied by assigning L<C<Nil>|/type/Nil> to it:\n\n    my Real $product is default(1);\n    say $product;                       # OUTPUT: «1␤»\n    $product *= 5;\n    say $product;                       # OUTPUT: «5␤»\n    $product = Nil;\n    say $product;                       # OUTPUT: «1␤»\n\n=head2 Default defined variables pragma\n\nTo force all variables to have a\nL<definiteness|/language/mop#DEFINITE> constraint,\nuse the pragma C<use variables :D>. The pragma is lexically scoped and can be\nswitched off with C<use variables :_>.\n\n=begin code :skip-test<compile-time error>\nuse variables :D;\nmy Int $i;\n# OUTPUT: «===SORRY!=== Error while compiling <tmp>␤Variable definition of type Int:D (implicit :D by pragma) requires an initializer ...\nmy Int $i = 1; # that works\n{ use variables :_; my Int $i; } # switch it off in this block\n=end code\n\nNote that assigning L<C<Nil>|/type/Nil> will revert the variable to its\ndefault value, which is often not a definite value and as such would\nfail the constraint:\n\n=begin code\nuse variables :D;\nmy Int $x = 42;\n$x = Nil;\n# OUTPUT: «Type check failed in assignment to $x; expected type Int:D cannot be itself…»\n=end code\n\nAs the name suggests, this pragma applies B<only> to variables.\n\n=head1 Special variables\n\nRaku attempts to use long, descriptive names for special\nvariables. There are only three special variables that are extra\nshort.\n\n=head2 Pre-defined lexical variables\n\nThere are four special variables that are always available:\n\n=begin table\n\n    Variable    Meaning            Scope\n\n    $_          topic variable               every block\n    $/          regex match                  every sub / method\n    $!          exceptions                   every sub / method\n    $¢          last match (similar to $/)   inside current regex\n\n=end table\n\nI<Note that while you can access C<$¢> without error anywhere, it will\ncontain L<C<Nil>|/type/Nil> if accessed outside of a regex>.\n\nX<|Language,topic variable>\n=head3 The C<$_> variable\n\nC<$_> is the topic variable.  A fresh one is created in every B<block>.\nIt's also the default parameter for blocks that do not have an explicit\nsignature, so constructs like C<for @array { ... }> and C<given $var\n{ ... }> bind the value or values of the variable to C<$_> by invoking\nthe block.\n\n    for <a b c> { say $_ }  # binds $_ to 'a', 'b' and 'c' in turn\n    say $_ for <a b c>;     # same, even though it's not a block\n    given 'a'   { say $_ }  # binds $_ to 'a'\n    say $_ given 'a';       # same, even though it's not a block\n\nBecause C<$_> is bound to the value of the iteration, you can also\nassign to C<$_> if it is bound to something assignable.\n\n    my @numbers = ^5;   # 0 through 4\n    $_++ for @numbers;  # increment all elements of @numbers\n    say @numbers;\n\n    # OUTPUT: «1 2 3 4 5␤»\n\nC<CATCH> blocks bind C<$_> to the exception that was caught. The C<~~>\nsmartmatch operator binds C<$_> on the right-hand side expression to the\nvalue of the left-hand side.\n\nCalling a method on C<$_> can be shortened by leaving off the variable name:\n\n    .say;                   # same as $_.say\n\nC<m/regex/> and C</regex/> regex matches and C<s/regex/subst/> substitutions\nwork on C<$_>:\n\n    say \"Looking for strings with non-alphabetic characters...\";\n    for <ab:c d$e fgh ij*> {\n        .say if m/<-alpha>/;\n    }\n\n    # OUTPUT: «Looking for strings with non-alphabetic characters...\n    #          ab:c\n    #          d$e\n    #          ij*␤»\n\nX<|Language,match variable>\n=head3 The C<$/> variable\n\nC<$/> is the match variable.  A fresh one is created in every B<routine>.\nIt is set to the result of the last L<regex|/language/regexes>\nmatch and so usually contains objects of type L<C<Match>|/type/Match>.\n\n    'abc 12' ~~ /\\w+/;  # sets $/ to a Match object\n    say $/.Str;         # OUTPUT: «abc␤»\n\nThe C<Grammar.parse> method also sets the caller's C<$/> to the resulting\nL<C<Match>|/type/Match> object.  For the following code:\n\n=begin code :skip-test<needs XML::Grammar>\nuse XML::Grammar; # zef install XML\nXML::Grammar.parse(\"<p>some text</p>\");\nsay $/;\n\n# OUTPUT: «｢<p>some text</p>｣\n#           root => ｢<p>some text</p>｣\n#            name => ｢p｣\n#            child => ｢some text｣\n#             text => ｢some text｣\n#             textnode => ｢some text｣\n#           element => ｢<p>some text</p>｣\n#            name => ｢p｣\n#            child => ｢some text｣\n#             text => ｢some text｣\n#             textnode => ｢some text｣␤»\n=end code\n\nPrior to the 6.d version, you could use C<$()> shortcut to get the\nL<ast|/routine/ast> value from C<$/> L<C<Match>|/type/Match> if that value is\ntruthy, or the stringification of the L<C<Match>|/type/Match> object otherwise.\n\n    'test' ~~ /.../;\n    # 6.c language only:\n    say $(); # OUTPUT: «tes␤»;\n    $/.make: 'McTesty';\n    say $(); # OUTPUT: «McTesty␤»;\n\nThis (non-)feature has been deprecated as of version 6.d.\n\n=head4 X«Positional attributes|Variables,$0»\n\nX«|Variables,$1»\nC<$/> can have positional attributes if the L<regex|/language/regexes> had\ncapture-groups in it, which are just formed with parentheses.\n\n    'abbbbbcdddddeffg' ~~ / a (b+) c (d+ef+) g /;\n    say $/[0]; # OUTPUT: «｢bbbbb｣␤»\n    say $/[1]; # OUTPUT: «｢dddddeff｣␤»\n\nThese can also be accessed by the shortcuts C<$0>, C<$1>, C<$2>, etc.\n\n    say $0; # OUTPUT: «｢bbbbb｣␤»\n    say $1; # OUTPUT: «｢dddddeff｣␤»\n\nTo get all of the positional attributes, you can use C<$/.list> or C<@$/>.\nBefore 6.d, you can also use the C<@()> shortcut (no spaces inside the\nparentheses).\n\n    say @$/.join; # OUTPUT: «bbbbbdddddeff␤»\n\n    # 6.c language only:\n    say @().join; # OUTPUT: «bbbbbdddddeff␤»\n\nThis I<magic> behavior of C<@()> has been deprecated as of 6.d\n\n=head4 X«Named attributes|Variables,$<named>»\n\nC<$/> can have named attributes if the L<regex|/language/regexes> had named\ncapture-groups in it, or if the Regex called out to another Regex.\n\n=for code\n'I... see?' ~~ / \\w+ $<punctuation>=[ <-[\\w\\s]>+ ] \\s* $<final-word> = [ \\w+ . ] /;\nsay $/<punctuation>; # OUTPUT: «｢....｣␤»\nsay $/<final-word>;  # OUTPUT: «｢see?｣␤»\n\nThese can also be accessed by the shortcut C«$<named>».\n\n    say $<punctuation>; # OUTPUT: «｢....｣␤»\n    say $<final-word>;  # OUTPUT: «｢see?｣␤»\n\nTo get all of the named attributes, you can use C<$/.hash> or C<%$/>.  Before\n6.d language, you could also use the C<%()> shortcut (no spaces inside the\nparentheses).\n\n    say %$/.join;       # OUTPUT: «\"punctuation     ....final-word  see?\"␤»\n\n    # 6.c language only\n    say %().join;       # OUTPUT: «\"punctuation     ....final-word  see?\"␤»\n\nThis behavior has been deprecated as of the 6.d version.\n\n=head4 Thread-safety issues\n\nBecause C<$/> is only defined per B<routine>, you are in fact\nre-using the same C<$/> when you do matching in a loop.  In a single\nthreaded program, this is not an issue.  However, if you're going to\nuse C<hyper> or C<race> to have multiple threads do matching in\nparallel, the sharing of the \"outer\" C<$/> becomes an issue, because\nthen it is being shared B<between> threads!  Fortunately, the solution\nis very simple: define your own C<$/> inside the scope where you are\ndoing the matching.  For example, taking a source of text, running\na regex on it, and map that to a hash using parallel execution:\n\n=begin code :preamble<my @source>\nmy %mapped = @source.race.map: {\n    my $/;  # need one in this block to prevent racing issues\n    m/foo (.*?) bar (.*)/;  # matches on $_, stores in $/\n    $0 => $1   # short for $/[0] / $/[1]\n}\n=end code\n\nX<|Language,error variable>\n=head3 The C<$!> variable\n\nC<$!> is the error variable.  A fresh one is created in every B<routine>.\nIf a C<try> block or statement prefix catches an exception, that exception\nis stored in C<$!>. If no exception was caught, C<$!> is set to L<C<Nil>|/type/Nil>.\n\nNote that C<CATCH> blocks I<do not> set C<$!>. Rather, they set C<$_> inside\nthe block to the caught exception.\n\nAlso note that the same thread-safety issues apply to the use of C<$!> as\nthey do to C<$/>.\n\nX<|Language,cursor variable>\n=head3 The C<$¢> variable\n\nSee the description in L<C<Match>|/type/Match>.\n\nX<|Variables,$?FILE>X<|Variables,$?LINE>X<|Variables,::?CLASS>\n\n=head2 Compile-time variables\n\nAll compile time variables have a question mark as part of the twigil. Being\nI<compile time> they cannot be changed at runtime, however they are valuable in\norder to introspect the program. The most common compile time variables are the\nfollowing:\n\n=for table\n    $?FILE         Which file am I in?\n    $?LINE         Which line am I at? [indexed from 1]\n    ::?CLASS       Which class am I in?\n    %?RESOURCES    The files associated with the \"Distribution\" of the current compilation unit.\n\nC<$?FILE> and C<$?LINE> are also available from L<C<CallFrame>|/type/CallFrame> as\nthe L<C<file>|/type/CallFrame#method_file> and\nL<C<line>|/type/CallFrame#method_line> methods, respectively.\n\n=head3 X<C<%?RESOURCES>|Variables,%?RESOURCES>\n\nC<%?RESOURCES> is a B<compile-time> variable available to the code of a\nL<C<Distribution>|/type/Distribution>.\n\nIt contains a hash that provides compile and runtime access to files\nassociated with the Distribution of the current compilation unit. This hash\nis used to access a special storage for L<C<Distribution>|/type/Distribution>-wide static files\n(such as examples of configuration files, templates or data files).\n\nFiles available via this variable need to be placed under the Distribution's C<resources>\ndirectory:\n\n=begin code :lang<text>\nModule-Foo/\n├── lib\n│   └── Module\n│       └── Foo.rakumod\n├── META6.json\n├── README.md\n└── resources\n    └── images\n        └── foo.jpg\n=end code\n\nAdditionally, a relative path (starting from the root resources directory of a\ndistribution) to a file I<may> be specified under the C<\"resources\"> field in the\nC<META6.json> file:\n\n=begin code :lang<json>\n\"resources\": [\n    \"images/foo.jpg\"\n]\n=end code\n\nEvery resource file is added to an B<installed> Distribution and is\naccessible using a L<C<Hash>|/type/Hash>-like access to C<%?RESOURCES>, returning a\nL<C<Distribution::Resource>|/type/Distribution::Resource> object:\n\n=begin code\nmy $foo-IO = %?RESOURCES<images/foo.jpg>;          # gets an object you can slurp\nmy $foo-IO = %?RESOURCES<images/foo.jpg>.open;     # gets an opened IO::Handle to work with\n=end code\n\nNote that paths and names of resource files can be mangled in an\ninstalled distribution, so do not rely on their values in any other\ncase besides using them as keys for the C<%?RESOURCES> variable.\n\nThe C<%?RESOURCES> variable is not implemented as a plain L<C<Hash>|/type/Hash>, but as an\ninstance of the L<C<Distribution::Resource>|/type/Distribution::Resource> type, so do not expect to see\nall available resource files in a distribution by printing or by using other\nways to inspect its value. Instead, use the API described above to\naccess particular files.\n\nThe C<%?RESOURCES> variable is only accessible inside of modules.\nIf you want to access C<%?RESOURCES> outside of a module, you'll need\nto expose that API yourself.  One way to do that is to create a\nroutine in the C<lib> directory to return its value:\n\n=begin code :solo\nunit module MyLib;\nsub my-resources is export {\n    %?RESOURCES\n}\n=end code\n\nThen create a test file, say, C<t/resources.t>, with contents:\n\n=begin code :skip-test<needs dummy lib>\nuse Test;\nuse MyLib;\n\nmy $resources = my-resources;\nisa-ok $resources, Distribution::Resource;\n=end code\n\nThe contents of the compile-time hash are thus exposed to the runtime code.\n\n=head3 Introspection compile-time variables\n\nX<|Variables,$?PACKAGE>X<|Variables,$?MODULE>X<|Variables,$?CLASS>X<|Variables,$?ROLE>\nX<|Variables,$?TABSTOP>X<|Variables,$?NL>\n\nThe following compile time variables allow for a deeper introspection:\n\n=for table\n    $?PACKAGE            Which package am I in?\n    $?MODULE, ::?MODULE  Which module am I in? It contains the type of the module.\n    $?CLASS              Which class am I in? (as variable)\n    $?ROLE               Which role am I in? (as variable)\n    $?TABSTOP            How many spaces is a tab in a heredoc or virtual margin?\n    $?NL                 What a vertical newline \"\\n\" means: LF, CR or CRLF\n    $?DISTRIBUTION       The Distribution of the current compilation unit.\n\nWith particular regard to the C<$?NL>, see the L<newline\npragma|/language/pragmas>.\n\n=head3 Rakudo-specific compile-time variables\n\nThese variables are Rakudo specific, with all the corresponding caveats:\n=for table\n$?BITS           Number of data-path bits of the platform the program is being compiled upon.\n\n=head3 X<&?ROUTINE|Variables,&?ROUTINE>\n\nThe compile time variable C<&?ROUTINE> provides introspection about which\nroutine the program is actually within. It returns an instance of\nL<C<Routine>|/type/Routine> attached to the current routine. It does support the method\nC<.name> to obtain the name of the called routine, as well as C<.signature> and\nothers method related to L<C<Routine>|/type/Routine>:\n\n    sub awesome-sub { say &?ROUTINE.name }\n    awesome-sub; # OUTPUT: «awesome-sub␤»\n\nIt also allows also for recursion:\n\n=begin code\nmy $counter = 10;\nsub do-work {\n    say 'Calling myself other ' ~ $counter-- ~ ' times';\n    &?ROUTINE() if ( $counter > 0 );\n}\ndo-work;\n=end code\n\nNote that, in a L<C«multi»|/language/functions#Multi-dispatch>,\nC<&?ROUTINE> refers to the current candidate, I<not> the C<multi>\nas a whole.\n\nThus, the following recursive definition does B<not> work:\n\n=begin code\nmulti broken-fibonacci($n where * ≤ 1) { $n }\nmulti broken-fibonacci($n where * > 0) {\n    &?ROUTINE($n - 1) + &?ROUTINE($n - 2)\n}\n=end code\n\nIf called, C<&?ROUTINE> would always refer to the second\nmulti candidate and would never dispatch to the first.  If\nyou want to use self-recursion for the whole C<proto>, either\nuse the function name or L<C«samewith»|/language/functions#sub_samewith>.\n\n=head3 X<&?BLOCK|Variables,&?BLOCK>\n\nThe special compile variable C<&?BLOCK> behaves similarly to\nC<&?ROUTINE> but it allows to introspect a single block of code.\nIt holds a L<C<Block>|/type/Block> and allows for recursion within the\nsame block:\n\n=begin code\nfor '.' {\n    .Str.say when !.IO.d;\n    .IO.dir()».&?BLOCK when .IO.d # lets recurse a little!\n}\n=end code\n\n=head3 X<$?DISTRIBUTION|Variables,$?DISTRIBUTION>\n\nC<$?DISTRIBUTION> provides access to the L<C<Distribution>|/type/Distribution> of\nthe current compilation unit. This gives module authors a way to reference other\nfiles in the distribution by their original relative path names, or to view the\nmetadata (via the C<.meta> method), without needing to know the underlying file\nstructure (such as how L<C<CompUnit::Repository::Installation>|/type/CompUnit::Repository::Installation> changes the file\nlayout on installation).\n\n=begin code :solo\nunit module MyFoo;\n\nsub module-version {\n    say \"MyFoo is version:\";\n    say $?DISTRIBUTION.meta<ver>; # OUTPUT: «0.0.1␤»\n}\n=end code\n\nThe C<.meta> method provides access to the values in your C<META6.json>, especially C<version>, C<auth>, and C<api>.\n\nThe C<.content> method provides access to files in the distribution\nwhen provided with the relative path from the distribution's top-level\ndirectory.\n\nC<$?DISTRIBUTION> only returns information when used inside a module. In scripts\nit contains L<C<Nil>|/type/Nil>.\n\n=begin code\nsub module-source {\n    say \"MyFoo source code:\";\n    say $?DISTRIBUTION.content('lib/MyFoo.rakumod');\n    # OUTPUT: «IO::Handle<\"lib/MyFoo.rakumod\".IO>(closed)␤»\n}\n=end code\n\nNote the output for the C<content> example is a B<closed> filehandle.\nTo actually use the file's content, the user can extract it as a string\nin another routine in the same module:\n\n=begin code\nsub get-file-content {\n    say $?DISTRIBUTION.content('lib/MyFoo.rakumod').open.slurp;\n    # OUTPUT: «unit module MyFoo;␤»\n}\n=end code\n\n=head2 Dynamic variables\n\nThe pre-defined dynamically scoped variables all have the L<C<*> twigil|#The_*_twigil>,\nand their name is (conventionally) written in uppercase.\n\nX<|Variables,$*ARGFILES>X<|Variables,@*ARGS>\n=head3 Argument related variables\n\nThese variables are related to the arguments passed to a script.\n\n=head4 C<$*ARGFILES>\n\nAn L<C<IO::ArgFiles>|/type/IO::ArgFiles> (an empty subclass of L<C<IO::CatHandle>|/type/IO::CatHandle>) that uses C<@*ARGS>\nas source files, if it contains any files, or C<$*IN> otherwise. When C<$*IN> is\nused, its C<:nl-in>, C<:chomp>, C<:encoding>, and C<:bin> will be set on the\nL<C<IO::ArgFiles>|/type/IO::ArgFiles> object.\n\nAs of the 6.d version, C<$*ARGFILES> I<inside>\nL<C«sub MAIN»|/language/functions#sub_MAIN> is always set to C<$*IN>, even when\nC<@*ARGS> is not empty. See\nL<the class documentation|/type/IO::ArgFiles#$*ARGFILES>\nfor examples and more context.\n\n=head4 C<@*ARGS>\n\nC<@*ARGS> is an array of L<C<Str>|/type/Str> containing the arguments from the command line.\n\n=head4 C<&*ARGS-TO-CAPTURE>\n\nA dynamic variable available inside any custom\nL<C<ARGS-TO-CAPTURE>|/language/create-cli#sub_ARGS-TO-CAPTURE> subroutine\nthat can be used to perform the default argument parsing. Takes the same\nparameters as are expected of the custom C<ARGS-TO-CAPTURE> subroutine.\n\n=head4 C<&*GENERATE-USAGE>\n\nA dynamic variable available inside any custom\nL<C<GENERATE-USAGE>|/language/create-cli#sub_GENERATE-USAGE> subroutine\nthat can be used to perform the default usage message creation. Takes the\nsame parameters as are expected of the custom C<GENERATE-USAGE> subroutine.\n\nX<|Variables,$*IN>X<|Variables,$*OUT>X<|Variables,$*ERR>\n=head3 Special filehandles: C<STDIN>, C<STDOUT> and C<STDERR>\n\nFor more information about special filehandles please see also the L<Input and\nOutput|/language/io> page and the L<C<IO::Special>|/type/IO::Special> class. L<C<IO::Handle>|/type/IO::Handle> contains\nseveral examples of using C<$*IN> for reading standard input.\n\n=item C<$*IN>\nStandard input filehandle, AKA I<STDIN>.\n\n=item C<$*OUT>\nStandard output filehandle, AKA I<STDOUT>.\n\n=item C<$*ERR>\nStandard error filehandle, AKA I<STDERR>.\n\n=head3 Runtime environment\n\nThese dynamic variables contain information related to the environment the\nscript or program is running in.\n\n=head4  C<%*ENV>\n\nOperating system environment variables. Numeric values are provided\nas L<allomorphs|/language/glossary#Allomorph>.\n\n=head4 C<$*REPO>\n\nThis variable holds information about modules installed/loaded.\n\n=head4 C<$*INIT-INSTANT>\n\nC<$*INIT-INSTANT> is an L<C<Instant>|/type/Instant> object representing program\nstartup time. In particular, this is when the core code starts up, so the value\nof C<$*INIT-INSTANT> may be a few milliseconds earlier than C<INIT now> or even\nC<BEGIN now> executed in your program.\n\n=head4 C<$*TZ>\n\nC<$*TZ> is a dynamic variable intended to contain an object with information\nabout the system's local timezone.  It should numify to the number of\nB<seconds> from GMT.\n\nIf not set explicitly, it contains just an integer value without any\nfurther information, set the first time C<$*TZ> is accessed.  Any\ndaylight saving time changes occurring during the duration of the\nprocess will B<not> be seen in that case.\n\n=head4 C<$*CWD>\n\nIt contains the C<C>urrent C<W>orking C<D>irectory.\n\n=head4 C<$*KERNEL>\n\nC<$*KERNEL> contains a L<C<Kernel> instance|/type/Kernel>, the C<.gist> of it\nbeing the current running kernel.\n\n    say $*KERNEL; # OUTPUT: «linux (4.4.92.31.default)␤»\n\n=head4 C<$*DISTRO>\n\nThis object (of type L<C<Distro>|/type/Distro>) contains information about the current operating\nsystem distribution. For instance:\n\n    say \"Some sort of Windows\" if $*DISTRO.is-win;\n\nC<$*DISTRO.name> takes a set of values that depend on the operating system.\nThese names will vary with version and implementation, so you should\ndouble-check and test before using them in your programs; since these names are\nimplementation defined and not in the specification, they could vary and change\nat any moment.\n\nThe C<$*DISTRO> gist is displayed by using C<say>:\n\n    say $*DISTRO; # OUTPUT: «debian (9.stretch)␤»\n\nThis shows additional information on the operating system and version it's\nusing, but as a matter of fact, this variable contains information which is\nuseful to create portable programs, such as the path separator:\n\n    say $*DISTRO.raku;\n    # OUTPUT: «Distro.new(release => \"42.3\", is-win => Bool::False,\n    #          path-sep => \":\", name => \"opensuse\",\n    #          auth => \"https://www.opensuse.org/\", version => v42.3,\n    #          signature => Blob, desc => \"2018-12-13T08:50:59.213619+01:00\")␤»\n\n\n=head4 C<$*VM>\n\nThis variable contains the current virtual machine running the code, as well as\nadditional information on the inner workings of aforementioned VM.\n\n    say $*VM.precomp-ext, \" \", $*VM.precomp-target; # OUTPUT: «moarvm mbc␤»\n\nThese two methods, for instance, will show the extension used in the precompiled\nbytecode scripts and the target used. This is what is found in the Moar Virtual\nMachine, but it could also vary with version and implementation. Other VM, such\nas Java, will show different values for them. C<$*VM.config> includes all\nconfiguration values used to create the virtual machine, e.g.\n\n    say $*VM.config<versionmajor>, \".\", $*VM.config<versionminor>;\n    # OUTPUT: «2018.11␤»\n\nwhich are the version of the virtual machine, generally the same one as the one\nused in the interpreter and the overall Raku environment.\n\n=head4 C<$*RAKU>\n\nThis object of the L<C<Raku>|/type/Raku> class contains information on the\ncurrent implementation of the Raku language:\n\n    say $*RAKU.compiler.version; # OUTPUT: «v2020.01␤»\n\nbut its gist includes the name of the language, followed by the major\nversion of the compiler:\n\n    say $*RAKU; # OUTPUT: «Raku (6.d)␤»\n\nIt stringifies to C<Raku>:\n\n    $*RAKU.put; # OUTPUT: «Raku␤»\n\nB<Note:> Before Rakudo release 2020.1, this information was only\navailable through the C<$*PERL> variable. Since Rakudo release 2020.1,\nit is available through both the C<$*RAKU> and the C<$*PERL> variables.\n\n=head4 C<$*PERL>\n\nFor the foreseeable future, the same as C<$*RAKU>.  Will be deprecated at\nsome point.\n\n=head4 C<$*PID>\n\nObject containing an integer describing the current Process IDentifier\n(operating system dependent).\n\n=head4 C<$*PROGRAM-NAME>\n\nThis contains the path to the current executable as it was entered on the\ncommand line, or C<-e> if raku was invoked with the -e flag.\n\n=head4 C<$*PROGRAM>\n\nContains the location (in the form of an L<C<IO::Path>|/type/IO::Path> object) of the Raku\nprogram being executed.\n\n=head4 C<&*EXIT>\n\nThis is a L<C<Callable>|/type/Callable> that contains the code that will be\nexecuted when doing an C<exit()> call.  Intended to be used in situations where\nRaku is embedded in another language runtime (such as Inline::Perl6 in Perl).\n\n=head4 C<$*EXIT>\n\nUsing C<$*EXIT> usually only makes sense in an L<END|/language/phasers#END>\nblock.  It contains the currently known L<exit()|/routine/exit> value: B<1>\nif an exception occurred, B<0> if no exception occurred, B<N> when an\nC<exit(N)> was executed.\n\nSupport for C<$*EXIT> was added in Rakudo compiler release 2023.02.\n\n=head4 C<$*EXCEPTION>\n\nUsing C<$*EXCEPTION> usually only makes sense in an L<END|/language/phasers#END>\nblock.  It contains an instantiated L<C<Exception>|/type/Exception> object if the program is\nending because of an exception having been thrown.  Will contain the Exception\ntype object otherwise.\n\nSupport for C<$*EXCEPTION> was added in Rakudo compiler release 2023.02.\n\n=head4 C<$*EXECUTABLE>\n\nContains an L<C<IO::Path>|/type/IO::Path> absolute path of the raku executable that is currently\nrunning.\n\n=head4 C<$*EXECUTABLE-NAME>\n\nContains the name of the Raku executable that is currently running. (e.g.\nraku-p, raku-m). Favor C<$*EXECUTABLE> over this one, since it's not\nguaranteed that the raku executable is in C<PATH>.\n\n=head4 C<$*USAGE>\n\nThis is an object of type L<C<Str>|/type/Str> containing the default usage message\ngenerated from the signatures of C<MAIN> subs available from inside\nC<sub MAIN> and C<sub USAGE>. The variable is I<read-only>.\n\n=for code\nsub MAIN($a, :$b, UInt :$ehehe) {\n    say $*USAGE; # OUTPUT: «Usage:␤  my-script.raku [-a=<Int>] [-b=<Str>] [--<opts>=...]»\n}\n\nIt is accessible only inside of MAIN sub.\n\n=head4 C<$*USER>\n\nAn L<C<Allomorph>|/type/Allomorph> with information about the user that is running the program. It\nwill evaluate to the username if treated as a string and the numeric user id if\ntreated as a number.\n\n=head4 C<$*GROUP>\n\nAn L<C<Allomorph>|/type/Allomorph> with the primary group of the user who is running the program.\nIt will evaluate to the groupname only if treated as a string and the numeric\ngroup id if treated as a number.\n\n=head4 C<$*HOMEDRIVE>\n\nContains information about the \"home drive\" of the user that is running the\nprogram on Windows. It's not defined in other operating systems.\n\n=head4 C<$*HOMEPATH>\n\nContains information about the path to the user directory that is running the\nprogram on Windows. It's not defined in other operating systems.\n\n=head4 C<$*HOME>\n\nContains an L<C<IO::Path>|/type/IO::Path> object representing the \"home directory\" of the user\nthat is running the program. Uses V«%*ENV<HOME>» if set.\n\nOn Windows, uses V«%*ENV<HOMEDRIVE> ~ %*ENV<HOMEPATH>». If the home directory\ncannot be determined, it will be L<C<Any>|/type/Any>.\n\n=head4 C<$*SPEC>\n\nContains the appropriate L<C<IO::Spec>|/type/IO::Spec> sub-class for the platform that the program\nis running on. This is a higher-level class for the operating system; it will\nreturn C<Unix>, for instance, in the case of Linux (in the form of the\nL<C<IO::Spec>|/type/IO::Spec> class used for the current implementation).\n\n=head4 C<$*TMPDIR>\n\nThis is an L<C<IO::Path>|/type/IO::Path> object representing the \"system temporary directory\" as\ndetermined by L«C<.tmpdir IO::Spec::* method>|/routine/tmpdir».\n\n=head4 C<$*THREAD>\n\nContains a L<C<Thread>|/type/Thread> object representing the currently executing\nthread.\n\n=head4 C<$*SCHEDULER>\n\nThis is a L<C<ThreadPoolScheduler>|/type/ThreadPoolScheduler> object representing\nthe current default scheduler.\n\nBy default this imposes a maximum of 64 threads on the methods C<.hyper>,\nC<.race> and other thread-pool classes that use that scheduler such as\nL<C<Promise>|/type/Promise>s or L<C<Supply>|/type/Supply>s. This is, however, implementation, dependent and might\nbe subject to change. To change the maximum number of threads, you can either\nset the environment variable C<RAKUDO_MAX_THREADS> before running raku or\ncreate a scoped copy with the default changed before using them:\n\n    my $*SCHEDULER = ThreadPoolScheduler.new( max_threads => 128 );\n\nThis behavior is not tested in the spec tests and is subject to change.\n\n=head4 C<$*SAMPLER>\n\nThe current L<C<Telemetry::Sampler>|/type/Telemetry::Sampler> used for making snapshots of system state.\nOnly available if L<C<Telemetry>|/type/Telemetry> has been loaded.\n\n=head3 Runtime variables\n\nThese variables affect the behavior of certain functions, and in some cases its\nvalue can be changed during runtime.\n\n=head4 C<$*DEFAULT-READ-ELEMS>\n\nAffects the number of bytes read by default by\nL<C<IO::Handle.read>|/type/IO::Handle#method_read>. Its default value is 65536.\n\n=head4 C<$*COLLATION>\n\nThis is a L<C<Collation>|/type/Collation> object that can be used to\nconfigure Unicode collation levels.\n\n=head4 C<$*RAT-OVERFLOW>\n\nAvailable as of release 2022.02 of the Rakudo compiler.\n\nUsing Rats by itself is fine, until you run out of precision.  The\n$*RAT-OVERFLOW dynamic variable specifies the behavior that should be\nexecuted when a L<C<Rat>|/type/Rat> overflows its precision. By default, it is set to\nL<C<Num>|/type/Num>, meaning it will revert to using (lossy) floating point.\n\nYou can also set it to L<C<FatRat>|/type/FatRat>, which will cause automatic upgrade\nto L<C<FatRat>|/type/FatRat> as soon as a L<C<Rat>|/type/Rat> runs out of precision. You can also\nspecify L<C<Failure>|/type/Failure> (to have it fail), L<C<Exception>|/type/Exception> (to have it throw\nan exception) or L<C<CX::Warn>|/type/CX::Warn> (to have it warn on downgrading to L<C<Num>|/type/Num>).\n\nTo activate this globally to upgrade to L<C<FatRat>|/type/FatRat>:\n\n=begin code\nINIT $*RAT-OVERFLOW = FatRat;\n=end code\n\nTo activate this only for a lexical scope:\n\n=begin code\nmy $*RAT-OVERFLOW = FatRat;\n=end code\n\nHow does that work? The C<$*RAT-OVERFLOW> variable is supposed to contain\na class or instance on which the C<UPGRADE-RAT> method will be called\nwhen a Rat overflows. So you can introduce your own behavior by\ncreating a class with an C<UPGRADE-RAT> method in it.\n\nSuch a method should accept two integer values: one for the numerator\nand one for the denominator.  For example (not entirely serious) would\nbe to convert the resulting value to C<Inf> if really great, or C<0>\nif really small:\n\n=begin code\nclass ZeroOrInf {\n    method UPGRADE-RAT(Int $nu, Int $de) {\n        $nu > $de ?? Inf !! 0\n    }\n}\n=end code\n\n=head4 C<$*TOLERANCE>\n\nVariable used by the L<C<=~=>|/routine/=~=> operator, and any operations that\ndepend on it, to decide if two values are approximately equal. Defaults to\nC<1e-15>.\n\n=head1 Naming conventions\n\nIt is helpful to know our naming conventions in order to understand what codes\ndo directly. However, there is not yet (and might never be) an official list of;\nstill, we list several conventions that are widely held.\n\n=item1 Subs and methods from the built-ins library try to have single-word names\nwhen a good one could be found. In cases where there are two or more words\nmaking up a name, they are separated by a \"-\".\n\n=item1 Compounds are treated as a single word, thus C<substr>, C<subbuf>, and\nC<deepmap> (just like we write \"starfish\", not \"star fish\" in English).\n\n=item1 Subs and methods that are automatically called for you at special times\nare written in uppercase. This includes the C<MAIN> sub, the C<AT-POS> and\nrelated methods for implementing container types, along with C<BUILD> and\nC<DESTROY>.\n\n=item1 Type names are camel case, except for native types, which are lowercase.\nFor the exception, you can remember it by: they are stored in a more compact\nway, so they names look smaller too.\n\n=item1 Built-in dynamic variables and compile-time variables are always\nuppercase, such like C<$*OUT>, C<$?FILE>.\n\n=item1 Methods from the MOP and other internals use \"_\" to separate multiple\nwords, such like C<add_method>.\n\n=end pod\n"
  },
  {
    "path": "doc/Native/int.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class int\n\n=SUBTITLE Native integer\n\n  class int is Int { }\n\nThis class is used to represent integers that are native to the compiler,\noperating system and architecture the interpreter is compiled in.\n\nMore information in L<the native types page|/language/nativetypes> as well as in\nthe section on L<native numerics|/language/numerics#Native_numerics>.\n\n\n=end pod\n"
  },
  {
    "path": "doc/Programs/01-debugging.rakudoc",
    "content": "=begin pod :kind(\"Programs\") :subkind(\"programs\") :category(\"programs\")\n\n=TITLE Debugging\n\n=SUBTITLE Modules and applications used to debug Raku programs\n\n=head1 Core debugging features\n\n=head2 The C<trace> pragma\n\nThe C<trace> pragma causes the program to print out step-by-step which\nlines get executed:\n\n    use trace;\n    sub foo { say \"hi\" }\n    foo;\n    # OUTPUT:\n    # 2 (/tmp/script.raku line 2)\n    # sub foo { say \"hi\" }\n    # 5 (/tmp/script.raku line 3)\n    # foo\n    # 3 (/tmp/script.raku line 2)\n    # say \"hi\"\n    # hi\n\nX<|Subroutines,dd> X<|Language,dumper>\n=head1 Dumper function (C<dd>)\n\nN<This routine is a Rakudo-specific debugging feature and not\nstandard Raku.>\n\nThe I<Tiny Data Dumper>: This function takes the input list of variables\nand C<note>s them (on C<$*ERR>) in an easy to read format, along with\nthe C<name> of the variable.  For example, this prints to the standard\nerror stream the variables passed as arguments:\n\n=begin code :ok-test<dd>\nmy $a = 42;\nmy %hash = \"a\" => 1, \"b\" => 2, \"c\" => 3;\n\ndd %hash, $a;\n#`( OUTPUT:\n    Hash %hash = {:a(1), :b(2), :c(3)}\n    Int $a = 42\n)\n=end code\n\nPlease note that C<dd> will ignore named parameters. You can use a\nL<C<Capture>|/type/Capture> or L<C<Array>|/type/Array> to force it to dump everything passed to it.\n\n=begin code :ok-test<dd>\ndd \\((:a(1), :b(2)), :c(3));\ndd [(:a(1), :b(2)), :c(3)];\n=end code\n\nIf you don't specify any parameters at all, it will just print the type\nand name of the current subroutine / method to the standard error\nstream:\n\n=begin code :ok-test<dd>\nsub a { dd }; a   # OUTPUT: «sub a()␤»\n=end code\n\nThis can be handy as a cheap trace function.\n\n=head2 Using backtraces\n\nThe L<C<Backtrace>|/type/Backtrace> class gets the current call stack, and can return it as\na string:\n\n    my $trace = Backtrace.new;\n    sub inner { say ~Backtrace.new; }\n    sub outer { inner; }\n    outer;\n\n    # OUTPUT:\n    # raku /tmp/script.raku\n    #   in sub inner at /tmp/script.raku line 2\n    #   in sub outer at /tmp/script.raku line 3\n    #   in block <unit> at /tmp/script.raku line 4\n\n=head2 Environment variables\n\nSee L<Raku Environment\nVariables|https://github.com/rakudo/rakudo/wiki/dev-env-vars>\nfor more information.\n\n=head1 Ecosystem debugging modules\n\nThere are at least two useful debuggers and two tracers available for Rakudo\n(the Raku compiler).  For more information on these modules, please refer to\ntheir documentation.\n\nHistorically other modules have existed and others are likely to be\nwritten in the future. Please check the L<Raku\nModules|https://raku.land/> website for more modules like these.\n\n=head2 L<C<Grammar::Debugger>|https://raku.land/zef:raku-community-modules/Grammar::Debugger> (and C<Grammar::Tracer> in the same distribution)\n\nSimple tracing and debugging support for Raku grammars.\n\n=head2 L<C<Trait::Traced>|https://raku.land/cpan:KAIEPI/Trait::Traced>\n\nThis provides the C<is traced> trait, which automatically traces usage of\nfeatures of whatever the trait is applied to. What features of whatever the\ntrace is applied to get traced and how traces are handled are customizable.\nRefer to its documentation for more information on how this works.\n\n=end pod\n"
  },
  {
    "path": "doc/Programs/02-reading-docs.rakudoc",
    "content": "=begin pod :kind(\"Programs\") :subkind(\"programs\") :category(\"programs\")\n\n=TITLE Reading the docs\n\n=SUBTITLE rakudoc - the Raku pod reader\n\n=head1 X<INTRODUCTION|Programs,rakudoc>\n\nProgram C<rakudoc> is a command-line-interface (CLI) program that reads\nRaku pod from B<installed> modules' source code, in contrast to\nrunning C<raku --doc=MODULE programfile> which reads Raku pod from\nthe named source file.\n\nNote that C<rakudoc> may not be installed automatically depending upon\nhow you installed Rakudo Raku.  To install it use C<zef>:\n\n=for code :lang<usage>\nzef install 'rakudoc:auth<zef:coke>'\n\n=head1 SYNOPSIS\n\n=for code :lang<usage>\nrakudoc [switches] [arguments]\n\n=head1 DESCRIPTION\n\nWith no switches or arguments, C<rakudoc> lists its help to C<$*OUT> (C<stdout>).\nFor C«rakudoc:ver<0.2.5>», this output is:\n\n=begin code :lang<output>\nUsage:\n  rakudoc [-d|--doc-sources=<Directories>] [-D|--no-default-docs] <query>\n  rakudoc -b|--build-index [-d|--doc-sources=<Directories>] [-D|--no-default-docs]\n  rakudoc -V|--version\n  rakudoc -h|--help <ARGUMENTS>\n\n    <query>                           Example: 'Map', 'IO::Path.add', '.add'\n    -d|--doc-sources=<Directories>    Additional directories to search for documentation\n    -D|--no-default-docs              Use only directories in --doc-sources / $RAKUDOC\n    -b|--build-index                  Index all documents found in doc source directories\n=end code\n\nThe text output can be captured and converted to other forms if desired.\n\nIf you want to use ANSI escape sequences, which will apply boldface\nand other enhancements when the output is printed to a terminal, you\nwill have to set the environment variable POD_TO_TEXT_ANSI, which is\nunset by default\n\n=for code :lang<shell>\nexport POD_TO_TEXT_ANSI=1\n\n\n=head1 LIMITATIONS\n\nCurrently C<rakudoc> can only extract embedded Raku pod from installed\nmodule source files (as listed in a distribution's C<META6.json>\nfile).  It is planned to add a feature for C<rakudoc> (in conjunction\nwith C<META6.json> changes) to extract B<all> Raku pod in files\nincluded with the installed distribution.\n\n=end pod\n"
  },
  {
    "path": "doc/Programs/03-environment-variables.rakudoc",
    "content": "=begin pod :kind(\"Programs\") :subkind(\"programs\") :category(\"programs\")\n\n=TITLE Environment variables used by the C<raku> command line\n\n=SUBTITLE How to run Rakudo, a Raku implementation, and modify its behavior\nwith environment variables.\n\nRakudo's behavior can be tweaked by a (growing) number of environment variables;\nthis section attempts to document all those currently in use. They are\ninterpreter specific in all cases, except where some use conventional names\nsuch as C<PATH>.\n\nThe underlying virtual machine is also sensitive to a series of environment\nvariables; they are listed L<in this wiki\npage|https://github.com/rakudo/rakudo/wiki/dev-env-vars#moarvm>.\n\n=head2 Affecting execution from the command line\n\nX<|Programs,RAKUDO_OPT>\n=item C<RAKUDO_OPT>\n\nAvailable as of the 2022.02 Rakudo compiler release.\n\nThe C<RAKUDO_OPT> environment variable provides a way to specify default\ncompiler command line options, overridable by explicitly specifications\non the command line. For example:\n\n=for code :lang<shell>\n    RAKUDO_OPT=\"-I. --ll-exception\" raku -Ilib test.raku\n\nwould ignore the C<-I.> but would honor the C<--ll-exception> command\nline argument.\n\nA simple space splitter is used to separate arguments, making it impossible\nto use arguments with spaces in them.\n\n=head2 Module loading\n\nX<|Programs,RAKUDOLIB>X<|Programs,RAKULIB>X<|Programs,PERL6LIB>\n=item C<RAKUDOLIB>, C<RAKULIB>\n\nType: L<C<Str>|/type/Str>.\n\nC<RAKUDOLIB> and C<RAKULIB> append a comma-delimited list of paths to the\nsearch list for modules. C<RAKUDOLIB> is evaluated first. B<NOTE:> These env\nvars were added in the Rakudo compiler in release 2020.05. The deprecated older\nenv var C<PERL6LIB> is still available.\n\nX<|Programs,RAKUDO_MODULE_DEBUG>\n=item C<RAKUDO_MODULE_DEBUG>\n\nType: L<C<Bool>|/type/Bool>.\n\nIf true, causes the module loader to print debugging information to standard\nerror.\n\nX<|Programs,RAKUDO_PRECOMPILATION_PROGRESS>\n=item C<RAKUDO_PRECOMPILATION_PROGRESS>\n\nType: L<C<Bool>|/type/Bool>.\n\nAvailable as of the 2021.12 release of the Rakudo compiler.\n\nIf true, causes the module loader to print the names of modules that are being\nre-precompiled on standard error.  As such it is a simplified version of the\nfunctionality offered by C<RAKUDO_MODULE_DEBUG>.\n\n=head2 Error message verbosity and strictness\n\nX<|Programs,RAKU_EXCEPTIONS_HANDLER>\n=item C<RAKU_EXCEPTIONS_HANDLER>\n\nIf present, the C<print_exception> routine will use a class of that name to\nprocess the exception for output. Rakudo currently ships with\nC<Exceptions::JSON> (invoked by setting this variable to C<JSON>), to\noverride the default output.\n\nAvailable as of the 2020.01 release of the Rakudo compiler.  Before that it\nwas available as C<PERL6_EXCEPTIONS_HANDLER> (which was removed in the\n2023.04 release of the Rakudo compiler).\n\nIntended to be used by environments that embed the Raku Programming Language,\nsuch as IDEs.\n\n=for code :lang<shell>\n    RAKU_EXCEPTIONS_HANDLER=JSON raku -e 'die \"foo\"'\n    # {\"X::AdHoc\":{\"payload\":\"foo\",\"message\":\"foo\"}}\n\nX<|Programs,RAKUDO_NO_DEPRECATIONS>\n=item C<RAKUDO_NO_DEPRECATIONS>\n\nType: L<C<Bool>|/type/Bool>.\n\nIf true, suppresses deprecation warnings triggered by the C<is DEPRECATED>\ntrait.\n\nX<|Programs,RAKUDO_DEPRECATIONS_FATAL>\n=item C<RAKUDO_DEPRECATIONS_FATAL>\n\nType: L<C<Bool>|/type/Bool>.\n\nIf true, deprecation warnings become thrown exceptions.\n\nX<|Programs,RAKUDO_VERBOSE_STACKFRAME>\n=item C<RAKUDO_VERBOSE_STACKFRAME>\n\nType: L<C<UInt>|/type/UInt>.\n\nDisplays source code in stack frames surrounded by the specified number of\nlines of context; for instance C<RAKUDO_VERBOSE_STACKFRAME = 1> will use one\ncontext line.\n\nX<|Programs,RAKUDO_BACKTRACE_SETTING>\n=item C<RAKUDO_BACKTRACE_SETTING>\n\nType: L<C<Bool>|/type/Bool>.\n\nControls whether C<.setting> files are included in backtraces.\n\n=head2 Affecting precompilation\n\nX<|Programs,RAKUDO_PREFIX>\n=item C<RAKUDO_PREFIX>\n\nType: L<C<Str>|/type/Str>.\n\nWhen this is set, Rakudo will look for the standard repositories (perl, vendor,\nsite) in the specified directory. This is intended as an escape hatch for\nbuild-time bootstrapping issues, where Rakudo may be built as an unprivileged\nuser without write access to the runtime paths in NQP's config.\n\nX<|Programs,RAKUDO_PRECOMP_DIST>\n=item C<RAKUDO_PRECOMP_DIST>\nX<|Programs,RAKUDO_PRECOMP_LOADING>\n=item C<RAKUDO_PRECOMP_LOADING>\nX<|Programs,RAKUDO_PRECOMP_WITH>\n=item C<RAKUDO_PRECOMP_WITH>\n\nThese are internal variables for passing serialized state to precompilation jobs\nin child processes. Please do not set them manually.\n\nX<|Programs,RAKUDO_LOG_PRECOMP>\n=item C<RAKUDO_LOG_PRECOMP>\n\nIf set to 1, diagnostic information about the precompilation process is\nemitted.\n\nX<|Programs,RAKUDO_NO_PRECOMPILATION>\n=item C<RAKUDO_NO_PRECOMPILATION>\n\nIf set to 1, precompilation will be disabled. Available as of the 2023.08\nrelease of the Rakudo compiler.\n\n=head2 REPL (Read-eval-print loop)\n\nX<|Programs,RAKU_REPL_OUTPUT_METHOD>\n=item C<RAKU_REPL_OUTPUT_METHOD>\n\nThis specifies the name of the method that should be called on the result\nvalue of a statement in the L<REPL|/language/REPL> if the statement did B<not> cause any\noutput of its own.  If absent, C<gist> will be assumed.  One can use\nC<raku> to force a more literal, parsable representation.  Or L<C<Str>|/type/Str> to force a\ncomplete string representation.  Available as of the 2020.06 release of\nthe Rakudo compiler.\n\nX<|Programs,RAKUDO_LINE_EDITOR>\n=item C<RAKUDO_LINE_EDITOR>\n\nThis specifies the preferred line editor to use; valid values are C<LineEditor>,\nC<Readline>, C<Linenoise>, and none. A value of none is useful if you want to avoid the\nrecommendation message upon REPL startup.\n\nX<|Programs,RAKUDO_DISABLE_MULTILINE>\n=item C<RAKUDO_DISABLE_MULTILINE>\n\nIf set to 1, will disable multiline input for the REPL.\n\nX<|Programs,RAKUDO_HIST>\n=item C<RAKUDO_HIST>\n\nThis specifies the location of the history file used by the\nline editor; the default is C<~/.raku/rakudo-history>.\nBefore Rakudo release 2020.02 the default was\nC<~/.perl6/rakudo-history>.\n\n=head2 Other\n\nX<|Programs,RAKUDO_DEFAULT_READ_ELEMS>\n=item C<RAKUDO_DEFAULT_READ_ELEMS>\n\nThis specifies the default number of characters to read on an\nL«C<IO::Handle>|/type/IO::Handle» by setting the\nL«C<$*DEFAULT-READ-ELEMS>|/language/variables#$*DEFAULT-READ-ELEMS» dynamic\nvariable.\n\nX<|Programs,RAKUDO_ERROR_COLOR>\n=item C<RAKUDO_ERROR_COLOR>\n\nType: L<C<Bool>|/type/Bool>.\n\nControls whether to emit ANSI codes for error highlighting. Defaults to true\nif unset, except on Windows.\n\nX<|Programs,INSIDE_EMACS>\n=item C<INSIDE_EMACS>\n\nSupported as of release 2022.04 of the Rakudo compiler.  If specified with\na true value, will B<not> try to load any of the line editing modules in\nthe C<REPL>.  This allows the C<REPL> to be better integrated in the Emacs\nenvironment (which sets this environment variable).\n\nX<|Programs,RAKUDO_MAX_THREADS>\n=item C<RAKUDO_MAX_THREADS>\n\nType: L<C<UInt>|/type/UInt>.\n\nIndicates the maximum number of threads used by default when creating a\nL<C<ThreadPoolScheduler>|/type/ThreadPoolScheduler>. Defaults to 64 unless there appear to be more than\n8 CPU cores available: in which case it defaults to 8 * number of cores.\n\nAs of release 2022.06 of the Rakudo compiler, it is also possible to\nspecify \"B<unlimited>\" or \"B<Inf>\" to indicate that the number of threads\navailable by the operating system, will be the limiting factor.\n\nX<|Programs,TMPDIR>X<|Programs,TEMP>X<|Programs,TMP>\n=item C<TMPDIR>, C<TEMP>, C<TMP>\n\nType: L<C<Str>|/type/Str>.\n\nThe C<IO::Spec::Unix.tmpdir> method will return C<$TMPDIR> if it points to a\ndirectory with full access permissions for the current user, with a fallback\ndefault of C<'/tmp'>.\n\nL<C<IO::Spec::Cygwin>|/type/IO::Spec::Cygwin> and L<C<IO::Spec::Win32>|/type/IO::Spec::Win32> use more Windows-appropriate lists\nwhich also include the C<%TEMP%> and C<%TMP%> environment variables.\n\nX<|Programs,PATH>\n=item C<PATH>, C<Path>\n\nType: L<C<Str>|/type/Str>.\n\nThe C<IO::Spec::Unix.path> method splits C<$PATH> as a\nshell would; i.e. as a colon-separated list. L<C<IO::Spec::Cygwin>|/type/IO::Spec::Cygwin> inherits this\nfrom L<C<IO::Spec::Unix>|/type/IO::Spec::Unix>. C<IO::Spec::Win32.path> will read the first defined of\neither C<%PATH%> or C<%Path%> as a semicolon-delimited list.\n\nX<|Programs,RAKUDO_SNAPPER>\n=item C<RAKUDO_SNAPPER>\n\nIndicates the period in which the telemetry snapper will take a snapshot.\nDefaults to .1 for 10 snapshots per second.\n\nX<|Programs,RAKUDO_HOME>\n=item C<RAKUDO_HOME>\n\nAllows to override the Raku installation path. Defaults to\nC<[rakudo_executable_dir]/../share/perl6> in relocatable builds and the\nabsolute path to that folder in non-relocatable builds.\n\nX<|Programs,NQP_HOME>\n=item C<NQP_HOME>\n\nAllows to override the NQP installation path. Defaults to\nC<[rakudo_executable_dir]/../share/nqp> in relocatable builds and the absolute\npath to that folder in non-relocatable builds.\n\n=head1 WINDOWS PECULIARITIES\n\nX<|Programs,rakuw.exe>X<|Programs,rakudow.exe>\n=head2 Non-console applications\n\nOn Windows programs are compiled to either be I<console> applications or\nI<non-console> applications. I<Console> applications always open a console\nwindow. There is no straightforward way to suppress this window.\n\nRakudo provides a separate set of executables suffixed with a C<'w'>\n(C<rakuw.exe>, C<rakudow.exe>, ...) that are compiled as I<non-console>\napplications. These do not spawn this console window.\n\nB<WARNING> By default these I<non-console> applications will silently swallow\neverything that is printed to C<STDOUT> and C<STDERR>.\n\nTo receive the output of the program it suffices to redirect it externally:\n\n=for code :lang<batch>\nrakuw.exe script.raku >stdout.txt 2>stderr.txt\n\n=end pod\n"
  },
  {
    "path": "doc/Programs/04-running-raku.rakudoc",
    "content": "=begin pod :kind(\"Programs\") :subkind(\"programs\") :category(\"programs\")\n\n=TITLE Running Raku\n\n=SUBTITLE How to run Rakudo, a Raku implementation, and the command line\noptions you can use with it.\n\n=head1 NAME\n\nraku - Rakudo Raku Compiler\n\n=head1 SYNOPSIS\n\n=for code :lang<usage>\nraku [switches] [--] [programfile] [arguments]\n\n=head1 DESCRIPTION\n\nWith no arguments, it enters a L<REPL|/language/REPL>. With a C<[programfile]> or the C<-e>\noption, compiles the given program and by default also executes the\ncompiled code.\n\n=begin code :lang<usage>\n  -                    read program source from STDIN or start REPL if a TTY\n  -c                   check syntax only (runs BEGIN and CHECK blocks)\n  --doc                extract documentation and print it as text\n  -e program           one line of program, strict is enabled by default\n  -h, --help           display this help text\n  -n                   run program once for each line of input\n  -p                   same as -n, but also print $_ at the end of lines\n  -I path              adds the path to the module search path\n  -M module            loads the module prior to running the program\n  --target=stage       specify compilation stage to emit\n  --optimize=level     use the given level of optimization (0..3)\n  --rakudo-home=path   Override the path of the Rakudo runtime files\n  -o, --output=name    specify name of output file\n  -v, --version        display version information\n  -V                   print configuration summary\n  --stagestats         display time spent in the compilation stages\n  --ll-exception       display a low level backtrace on errors\n  --doc=module         use Pod::To::[module] to render inline documentation\n  --repl-mode=interactive|non-interactive\n                       when running without \"-e\" or filename arguments,\n                       a REPL is started. By default, if STDIN is a TTY,\n                       \"interactive\" REPL is started that shows extra messages and\n                       prompts, otherwise a \"non-interactive\" mode is used where\n                       STDIN is read entirely and evaluated as if it were a program,\n                       without any extra output (in fact, no REPL machinery is even\n                       loaded). This option allows to bypass TTY detection and\n                       force one of the REPL modes.\n  --profile[=name]     write profile information to a file\n                       Extension controls format:\n                           .json outputs in JSON\n                           .sql  outputs in SQL\n                           any other extension outputs in HTML\n  --profile-compile[=name]\n                       write compile-time profile information to a file\n                       Extension controls format:\n                         .json outputs in JSON\n                         .sql  outputs in SQL\n                         any other extension outputs in HTML\n  --profile-kind[=name]\n                       choose the type of profile to generate\n                         instrumented - performance measurements (default)\n                         heap - record heap snapshots after every garbage\n                         collector run\n  --profile-filename=name\n                       provide a different filename for profile.\n                       Extension controls format:\n                         .json outputs in JSON\n                         .sql  outputs in SQL\n                         any other extension outputs in HTML\n                       This option will go away in a future Rakudo release\n  --profile-stage=stage\n                       write profile information for the given compilation\n                       stage to a file. Use --profile-compile to set name\n                       and format\n  --full-cleanup       try to free all memory and exit cleanly\n  --debug-port=port    listen for incoming debugger connections\n  --debug-suspend      pause execution at the entry point\n  --tracing            output a line to stderr on every interpreter instr (only if\n                       enabled in MoarVM)\n=end code\n\nNote that only Boolean single-letter options may be bundled.\n\nThe supported values (stages) for C<--target> are:\n\n=begin code :lang<text>\nTarget     Backend  Description\n======     =======  ===========\nparse      all      a representation of the parse tree\nast        all      an abstract syntax tree (before optimizations)\noptimize   all      an abstract syntax tree (after optimizations)\n\nmbc        MoarVM   MoarVM byte code\njar        JVM      JVM archive\n=end code\n\nFor C<--profile-filename>, specifying a name ending in C<.json> will write a raw\nJSON profile dump. The default if this is omitted is C<profile-[timestamp].html>.\n\nPlease check out the L<document on environment\nvariables|/programs/03-environment-variables> to check for different ways to change the\nbehavior of the different layers of Raku.\n\n=end pod\n"
  },
  {
    "path": "doc/Programs/README.md",
    "content": "Attention contributors\n======================\n\nFiles in this directory are sorted by file name to generate the index\nfor the \"Programs\" tab (in contrast to the other tabs which are\nindexed in order by each file's \"=TITLE\" entry).\n"
  },
  {
    "path": "doc/Type/AST.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class AST\n\n=SUBTITLE Abstract representation of a piece of source code\n\n    class AST { }\n\nAn C<AST> or I<Abstract Syntax Tree> is a partially processed representation\nof a program.  ASTs are return values of the C<quasi> quoting construct,\nand are typically used within macros to generate code that is inserted\nin the calling location of the macro.\n\nThere is no API defined for ASTs yet.  Hopefully that will emerge as\npart of the work on macros.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Allomorph.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Allomorph\n\n=SUBTITLE Dual value number and string\n\n    class Allomorph is Str { }\n\nThe C<Allomorph> class is a common parent class for Raku's\ndual value types: L«C<ComplexStr>|/type/ComplexStr»,\nL«C<IntStr>|/type/IntStr», L«C<NumStr>|/type/NumStr»,\nL«C<RatStr>|/type/RatStr».\n\nThe dual value types (often referred to as\nL<allomorphs|/language/glossary#Allomorph>) allow for the representation\nof a value as both a string and a numeric type. Typically they will be\ncreated for you when the context is \"stringy\" but they can be determined\nto be numbers, such as in some L<quoting constructs|/language/quoting>:\n\n    my $c = <42+0i>;  say $c.^name; # OUTPUT: «ComplexStr␤»\n    my $i = <42>;     say $i.^name; # OUTPUT: «IntStr␤»\n    my $n = <42.1e0>; say $n.^name; # OUTPUT: «NumStr␤»\n    my $r = <42.1>;   say $r.^name; # OUTPUT: «RatStr␤»\n\nAs a subclass of both a L«C<Numeric>|/type/Numeric» class and\nL«C<Str>|/type/Str», via the C<Allomorph> class, an allomorph will be\naccepted where either is expected. However, an allomorph does not share\nobject identity with its L<C<Numeric>|/type/Numeric> parent class- or L<C<Str>|/type/Str>-only variants:\n\n=begin code\nmy ($complex-str, $int-str, $num-str, $rat-str)\n           = < 42+0i 42 42e10 42.1 >;\n\nmy (Complex $complex, Int $int, Num $num, Rat $rat)\n           =  $complex-str, $int-str, $num-str, $rat-str;  # OK!\n\nmy Str @strings\n           =  $complex-str, $int-str, $num-str, $rat-str;  # OK!\n\n# ∈ operator cares about object identity\nsay 42+0i ∈ < 42+0i 42 42e10 42.1 >;  # OUTPUT: «False␤»\nsay 42    ∈ < 42+0i 42 42e10 42.1 >;  # OUTPUT: «False␤»\nsay 42e10 ∈ < 42+0i 42 42e10 42.1 >;  # OUTPUT: «False␤»\nsay 42.1  ∈ < 42+0i 42 42e10 42.1 >;  # OUTPUT: «False␤»\n=end code\n\nPlease see L<the Numerics page|/language/numerics#Allomorphs> for a more\ncomplete description on how to work with these allomorphs.\n\n=head1 Methods\n\n=head2 method ACCEPTS\n\n    multi method ACCEPTS(Allomorph:D: Any:D \\a)\n\nIf the C<a> parameter is L<C<Numeric>|/type/Numeric> (including\nanother L<allomorph|/language/glossary#Allomorph>),\nchecks if invocant's L<C<Numeric>|/type/Numeric> value\nL<ACCEPTS|/type/Numeric#method_ACCEPTS> C<a>.\nIf the C<a> parameter is L<C<Str>|/type/Str>, checks if invocant's\nL<C<Str>|/type/Str> value L<ACCEPTS|/type/Str#method_ACCEPTS> C<a>.\nIf the C<a> parameter is anything else, checks if both\nL<C<Numeric>|/type/Numeric> and L<C<Str>|/type/Str> values of the invocant\nC<ACCEPTS> C<a>.\n\n    say \"5.0\" ~~ <5>; # OUTPUT: «False␤»\n    say 5.0   ~~ <5>; # OUTPUT: «True␤»\n    say <5.0> ~~ <5>; # OUTPUT: «True␤»\n\n=head2 method Bool\n\n    multi method Bool(::?CLASS:D:)\n\nReturns C<False> if the invocant is numerically C<0>, otherwise returns\nC<True>. The L<C<Str>|/type/Str> value of the invocant is not considered.\n\nB<Note>: For the C<Allomorph> subclass L«C<RatStr>|/type/RatStr» also\nsee L«C<Rational.Bool>|/type/Rational#method_Bool».\n\n=head2 method chomp\n\n    method chomp(Allomorph:D:)\n\nCalls L«C<Str.chomp>|/type/Str#routine_chomp» on the invocant's\nL<C<Str>|/type/Str> value.\n\n=head2 method chop\n\n    method chop(Allomorph:D: |c)\n\nCalls L«C<Str.chop>|/type/Str#routine_chop» on the invocant's\nL<C<Str>|/type/Str> value.\n\n=head2 method comb\n\n    method comb(Allomorph:D: |c)\n\nCalls L«C<Str.comb>|/type/Str#routine_comb» on the invocant's\nL<C<Str>|/type/Str> value.\n\n=head2 method fc\n\n    method fc(Allomorph:D:)\n\nCalls L«C<Str.fc>|/type/Str#routine_fc» on the invocant's\nL<C<Str>|/type/Str> value.\n\n=head2 method flip\n\n    method flip(Allomorph:D:)\n\nCalls L«C<Str.flip>|/type/Str#routine_flip» on the invocant's\nL<C<Str>|/type/Str> value.\n\n=head2 method lc\n\n    method lc(Allomorph:D:)\n\nCalls L«C<Str.lc>|/type/Str#routine_lc» on the invocant's\nL<C<Str>|/type/Str> value.\n\n=head2 method pred\n\n    method pred(Allomorph:D:)\n\nCalls L«C<Numeric.pred>|/type/Numeric#method_pred» on the invocant's\nnumeric value.\n\n=head2 method raku\n\n    multi method raku(Allomorph:D:)\n\nReturn a representation of the object that can be used via\nL«C<EVAL>|/routine/EVAL» to reconstruct the value of the object.\n\n=head2 method samecase\n\n    method samecase(Allomorph:D: |c)\n\nCalls L«C<Str.samecase>|/type/Str#method_samecase» on the invocant's\nL<C<Str>|/type/Str> value.\n\n=head2 method samemark\n\n    method samemark(Allomorph:D: |c)\n\nCalls L«C<Str.samemark>|/type/Str#routine_samemark» on the invocant's\nL<C<Str>|/type/Str> value.\n\n=begin comment\n=head2 method samespace\n\n    method samespace(Allomorph:D: |c)\n\nSee L<Is Str.samespace an implementation detail or not? · Issue #4318 · rakudo/rakudo · GitHub|https://github.com/rakudo/rakudo/issues/4318>\n=end comment\n\n=head2 method split\n\n    method split(Allomorph:D: |c)\n\nCalls L«C<Str.split>|/type/Str#routine_split» on the invocant's\nL<C<Str>|/type/Str> value.\n\n=head2 method Str\n\n    method Str(Allomorph:D:)\n\nReturns the L<C<Str>|/type/Str> value of the invocant.\n\n=head2 method subst\n\n    method subst(Allomorph:D: |c)\n\nCalls L«C<Str.subst>|/type/Str#method_subst» on the invocant's\nL<C<Str>|/type/Str> value.\n\n=head2 method subst-mutate\n\n    method subst-mutate(Allomorph:D \\SELF: |c)\n\nCalls L«C<Str.subst-mutate>|/type/Str#method_subst-mutate» on the\ninvocant's L<C<Str>|/type/Str> value.\n\n=head2 method substr\n\n    method substr(Allomorph:D: |c)\n\nCalls L«C<Str.substr>|/type/Str#routine_substr» on the\ninvocant's L<C<Str>|/type/Str> value.\n\n=head2 method substr-rw\n\n    method substr-rw(Allomorph:D \\SELF: $start = 0, $want = Whatever)\n\nCalls L«C<Str.substr-rw>|/type/Str#method_substr-rw» on the\ninvocant's L<C<Str>|/type/Str> value.\n\n=head2 method succ\n\n    method succ(Allomorph:D:)\n\nCalls L«C<Numeric.succ>|/type/Numeric#method_succ» on the invocant's\nnumeric value.\n\n=head2 method tc\n\n    method tc(Allomorph:D:)\n\nCalls L«C<Str.tc>|/type/Str#routine_tc» on the invocant's L<C<Str>|/type/Str> value.\n\n=head2 method tclc\n\n    method tclc(Allomorph:D:)\n\nCalls L«C<Str.tclc>|/type/Str#routine_tclc» on the invocant's L<C<Str>|/type/Str>\nvalue.\n\n=head2 method trim\n\n    method trim(Allomorph:D:)\n\nCalls L«C<Str.trim>|/type/Str#method_trim» on the invocant's L<C<Str>|/type/Str>\nvalue.\n\n=head2 method trim-leading\n\n    method trim-leading(Allomorph:D:)\n\nCalls L«C<Str.trim-leading>|/type/Str#method_trim-leading» on the\ninvocant's L<C<Str>|/type/Str> value.\n\n=head2 method trim-trailing\n\n    method trim-trailing(Allomorph:D:)\n\nCalls L«C<Str.trim-trailing>|/type/Str#method_trim-trailing» on the\ninvocant's L<C<Str>|/type/Str> value.\n\n=head2 method uc\n\n    method uc(Allomorph:D:)\n\nCalls L«C<Str.uc>|/type/Str#routine_uc» on the invocant's L<C<Str>|/type/Str> value.\n\n=head2 method WHICH\n\n    multi method WHICH(Allomorph:D:)\n\nReturns an object of type L«C<ValueObjAt>|/type/ValueObjAt» which\nuniquely identifies the object.\n\n    my $f = <42.1e0>;\n    say $f.WHICH;     # OUTPUT: «NumStr|Num|42.1|Str|42.1e0␤»\n\n=head1 Operators\n\n=head2 infix cmp\n\n    multi infix:<cmp>(Allomorph:D $a, Allomorph:D $b)\n\nCompare two C<Allomorph> objects.  The comparison is done on the\nL<C<Numeric>|/type/Numeric> value first and then on the L<C<Str>|/type/Str> value. If you want to\ncompare in a different order then you would coerce to a L<C<Numeric>|/type/Numeric>\nor L<C<Str>|/type/Str> value first:\n\n    my $f = IntStr.new(42, \"smaller\");\n    my $g = IntStr.new(43, \"larger\");\n    say $f cmp $g;          # OUTPUT: «Less␤»\n    say $f.Str cmp $g.Str;  # OUTPUT: «More␤»\n\n=head2 infix eqv\n\n    multi infix:<eqv>(Allomorph:D $a, Allomorph:D $b --> Bool:D)\n\nReturns C<True> if the two C<Allomorph> C<$a> and C<$b> are of the same\ntype, their L<C<Numeric>|/type/Numeric> values are L<equivalent|/routine/eqv> and their\nL<C<Str>|/type/Str> values are also L<equivalent|/routine/eqv>. Returns C<False>\notherwise.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Any.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Any\n\n=SUBTITLE Thing/object\n\n    class Any is Mu {}\n\nWhile L<C<Mu>|/type/Mu> is the root of the Raku class hierarchy, C<Any>\nis the class that serves as a default base class for new classes, and as the\nbase class for most built-in classes.\n\nSince Raku intentionally confuses items and single-element lists, most methods\nin C<Any> are also present on class L<C<List>|/type/List>, and coerce to\nList or a list-like type.\n\n=head1 Methods\n\n=head2 method ACCEPTS\n\n    multi method ACCEPTS(Any:D: Mu $other)\n\nUsage:\n\n=begin code :lang<pseudo>\nEXPR.ACCEPTS(EXPR);\n=end code\n\nReturns C<True> if C<$other === self> (i.e. it checks object identity).\n\nMany built-in types override this for more specific comparisons.\n\n=head2 routine any\n\n    method any(        --> Junction:D)\n    multi  any(+values --> Junction:D)\n    multi  any(@values --> Junction:D)\n\nInterprets the invocant or arguments as a list and creates an\nL<any|/routine/any>-L<C<Junction>|/type/Junction> from it.\n\n    say so 2 == <1 2 3>.any;        # OUTPUT: «True␤»\n    say so 5 == any(<1 2 3>);       # OUTPUT: «False␤»\n\n=head2 routine all\n\n    method all(        --> Junction:D)\n    multi  all(+values --> Junction:D)\n    multi  all(@values --> Junction:D)\n\nInterprets the invocant or arguments as a list and creates an\nL<all|/routine/all>-L<C<Junction>|/type/Junction> from it.\n\n    say so 3 < <2 3 4>.all;         # OUTPUT: «False␤»\n    say so 1 < all(<2 3 4>);        # OUTPUT: «True␤»\n\n=head2 routine one\n\n    method one(        --> Junction:D)\n    multi  one(+values --> Junction:D)\n    multi  one(@values --> Junction:D)\n\nInterprets the invocant or arguments as a list and creates a\nL<one|/routine/one>-L<C<Junction>|/type/Junction> from it.\n\n    say so 1 == (1, 2, 3).one;      # OUTPUT: «True␤»\n    say so 1 == one(1, 2, 1);       # OUTPUT: «False␤»\n\n=head2 routine none\n\n    method none(        --> Junction:D)\n    multi  none(+values --> Junction:D)\n    multi  none(@values --> Junction:D)\n\nInterprets the invocant or arguments as a list and creates a\nL<none|/routine/none>-L<C<Junction>|/type/Junction> from it.\n\n    say so 1 == (1, 2, 3).none;     # OUTPUT: «False␤»\n    say so 4 == none(1, 2, 3);      # OUTPUT: «True␤»\n\n=head2 method list\n\n    multi method list(Any:U:)\n    multi method list(Any:D \\SELF:)\n\nApplies the infix L«C<,>|/routine/,» operator to the invocant and returns\nthe resulting L<C<List>|/type/List>:\n\n    say 42.list.^name;           # OUTPUT: «List␤»\n    say 42.list.elems;           # OUTPUT: «1␤»\n\nSubclasses of C<Any> may choose to return any I<core> type that\ndoes the L<C<Positional>|/type/Positional> role\nfrom L«C<.list>|/routine/list». Use L«C<.List>|/routine/List» to\ncoerce specifically to L<C<List>|/type/List>.\n\nX<|Syntax,@ list contextualizer>\nC<@> can also be used as a list or L<C<Positional>|/type/Positional> contextualizer:\n\n=for code\nmy $not-a-list-yet = $[1,2,3];\nsay $not-a-list-yet.raku;             # OUTPUT: «$[1, 2, 3]␤»\nmy @maybe-a-list = @$not-a-list-yet;\nsay @maybe-a-list.^name;              # OUTPUT: «Array␤»\n\nIn the first case, the list is I<itemized>. C<@> as a prefix puts the initial\nscalar in a list context by calling C<.list> and turning it into an L<C<Array>|/type/Array>.\n\n=head2 method push\n\n    multi method push(Any:U \\SELF: |values --> Positional:D)\n\nThe method push is defined for undefined invocants and allows for autovivifying\nundefined to an empty L<C<Array>|/type/Array>, unless the undefined value\nimplements L<C<Positional>|/type/Positional> already. The argument provided will\nthen be pushed into the newly created Array.\n\n    my %h;\n    say %h<a>;     # OUTPUT: «(Any)␤»      <-- Undefined\n    %h<a>.push(1); # .push on Any\n    say %h;        # OUTPUT: «{a => [1]}␤» <-- Note the Array\n\n=head2 routine reverse\n\n    multi        reverse(*@list  --> Seq:D)\n    multi method reverse(List:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> with the same elements in reverse order.\n\nNote that C<reverse> always refers to reversing elements of a list;\nto reverse the characters in a string, use L<flip|/routine/flip>.\n\nExamples:\n\n    say <hello world!>.reverse;     # OUTPUT: «(world! hello)␤»\n    say reverse ^10;                # OUTPUT: «(9 8 7 6 5 4 3 2 1 0)␤»\n\n=head2 method sort\n\n    multi method sort()\n    multi method sort(&custom-routine-to-use)\n\nSorts iterables with L<cmp|/routine/cmp> or given code object and returns a new\nL<C<Seq>|/type/Seq>. Optionally, takes a L<C<Callable>|/type/Callable> as a positional\nparameter, specifying how to sort.\n\nExamples:\n\n    say <b c a>.sort;                           # OUTPUT: «(a b c)␤»\n    say 'bca'.comb.sort.join;                   # OUTPUT: «abc␤»\n    say 'bca'.comb.sort({$^b cmp $^a}).join;    # OUTPUT: «cba␤»\n    say '231'.comb.sort(&infix:«<=>»).join;     # OUTPUT: «123␤»\n\n    sub by-character-count { $^a.chars <=> $^b.chars }\n    say <Let us impart what we have seen tonight unto young Hamlet>.sort(&by-character-count);\n    # OUTPUT: «(us we Let what have seen unto young impart Hamlet tonight)␤»\n\n=head2 routine map\n\n    multi method map(\\SELF: &code)\n    multi        map(&code, +values)\n\nC<map> will iterate over the invocant and apply the number of positional\nparameters of the code object from the invocant per call.  The returned values\nof the code object will become elements of the returned L<C<Seq>|/type/Seq>.\n\nThe additional parameters C<:$label> and C<:$item>,\navailable in the C<method> form, are useful only internally, since C<for> loops get\nconverted to C<map>s. The C<:$label> takes an existing L<C<Label>|/type/Label> to\nlabel the C<.map>'s loop with and C<:$item> controls whether the iteration will\noccur over C<(SELF,)> (if C<:$item> is set) or C<SELF>.\n\nIn C<sub> form, it will apply the C<code> block to the C<values>, which will be\nused as invocant.\n\nThe forms with C<|c>, C<Iterable:D \\iterable> and C<Hash:D \\hash> as signatures\nwill fail with C<X::Cannot::Map>, and are mainly meant to catch common traps.\n\nInside a C<for> statement that has been sunk, a L<C<Seq>|/type/Seq> created by a map will\nalso sink:\n\n=for code\nsay gather for 1 {\n    ^3 .map: *.take;\n} # OUTPUT: «(0 1 2)␤»\n\nIn this case, C<gather> sinks the C<for> statement, and the result of sinking\nthe L<C<Seq>|/type/Seq> will be iterating over its elements, calling C<.take> on them.\n\n=head2 routine deepmap\n\n    method deepmap(&block --> Iterable) is nodal\n    sub    deepmap(&op, \\obj --> Iterable)\n\nC<deepmap> will apply its argument (or first argument for the sub form) to\neach element and return a new L<C<Iterable>|/type/Iterable> with the return\nvalues of the argument, unless the element does the\nL<C<Iterable>|/type/Iterable> role. For those elements\nL<deepmap|/routine/deepmap> will descend recursively into the sublist.\n\n    say [[1,2,3],[[4,5],6,7]].deepmap(* + 1);\n    # OUTPUT: «[[2 3 4] [[5 6] 7 8]]␤»\n    say deepmap * + 1, [[1,2,3],[[4,5],6,7]];\n    # OUTPUT: «[[2 3 4] [[5 6] 7 8]]␤»\n\nIn the case of L<C<Associative>|/type/Associative>s, it will be applied to its values:\n\n=for code\n{ what => \"is\", this => \"thing\", a => <real list> }.deepmap( *.flip ).say;\n# OUTPUT: «{a => (laer tsil), this => gniht, what => si}␤»\nsay deepmap *.flip, {what=>'is', this=>'thing', a=><real list>};\n# OUTPUT: «{a => (laer tsil), this => gniht, what => si}␤»\n\n=head2 routine duckmap\n\n    method duckmap(&block --> Iterable) is rw is nodal\n    sub    duckmap(&op, \\obj --> Iterable)\n\nC<duckmap> will apply its argument (or first argument for the sub form) to each\nelement that behaves in such a way that the argument can be applied. If it\nfails, it will descend recursively if possible, or otherwise return the item\nwithout any transformation. It will act on values if the object is\nL<C<Associative>|/type/Associative>.\n\n=for code\n<a b c d e f g>.duckmap(-> $_ where <c d e>.any { .uc }).say;\n# OUTPUT: «(a b C D E f g)␤»\n(('d', 'e'), 'f').duckmap(-> $_ where <e f>.any { .uc }).say;\n# OUTPUT: «((d E) F)␤»\n{ first => ('d', 'e'), second => 'f'}.duckmap(-> $_ where <e f>.any { .uc }).say;\n# OUTPUT: «{first => (d E), second => F}␤»\n\nIn the first case, it is applied to C<c>, C<d> and C<e> which are the ones that\nmeet the conditions for the block (C<{ .uc }>) to be applied; the rest are\nreturned as is.\n\nIn the second case, the first item is a list that does not meet the condition,\nso it's visited; that flat list will behave in the same way as the first one.\nSimilarly in the third case; here it's only the values in each pair that are\nvisited.\n\n    say duckmap *², [[1,2,3],[[4,5],6,7]];   # OUTPUT: «[9 9]␤»\n\nYou can square anything as long as it behaves like a number. In this case, there\nare two arrays with 3 elements each; these arrays will be converted into the\nnumber 3 and squared. In the next case, however\n\n    say duckmap -> Rat $_ { $_²}, [[1,2,3],[[4,5],6.1,7.2]];\n    # OUTPUT: «[[1 2 3] [[4 5] 37.21 51.84]]␤»\n\n3-item lists are not L<C<Rat>|/type/Rat>, so it descends recursively, but eventually only\napplies the operation to those that match L<C<Rat>|/type/Rat>.\n\nAlthough on the surface (and name), C<duckmap> might look similar to\nL<C<deepmap>|/routine/deepmap>, the latter is applied recursively regardless of\nthe type of the item.\n\n=head2 routine nodemap\n\n    method nodemap(&block --> Iterable) is nodal\n    sub    nodemap(&op, \\obj --> Iterable)\n\nC<nodemap> will apply its argument (or first argument for the sub form) to each\nelement and return a new L<C<Iterable>|/type/Iterable> with the return values\nof its L<C<Callable>|/type/Callable> argument. In contrast to\nL<deepmap|/routine/deepmap> it will B<not> descend recursively into sublists if\nit finds elements which L<do|/routine/does> the L<C<Iterable>|/type/Iterable>\nrole.\n\n    say nodemap *+1, [[1,2,3], [[4,5],6,7], 7];\n    # OUTPUT: «(4, 4, 8)␤»\n\n    say [[2, 3], [4, [5, 6]]]».nodemap(*+1)\n    # OUTPUT: «((3 4) (5 3))␤»\n\nThe examples above would have produced the exact same results if we had used\nL<map|/routine/map> instead of C<nodemap>. The difference between the two lies\nin the fact that L<map|/routine/map> flattens out L<C<Slip>|/type/Slip>s while\nC<nodemap> doesn't.\n\n    say [[2,3], [[4,5],6,7], 7].nodemap({.elems == 1 ?? $_ !! slip});\n    # OUTPUT: «(() () 7)␤»\n    say [[2,3], [[4,5],6,7], 7].map({.elems == 1 ?? $_ !! slip});\n    # OUTPUT: «(7)␤»\n\nWhen applied to L<C<Associative>|/type/Associative>s, it will act on the values:\n\n    say nodemap *.flip, { what => \"is\", this => \"thing\" };\n    # OUTPUT: «{this => gniht, what => si}␤»\n\n=head2 method flat\n\n    method flat() is nodal\n\nInterprets the invocant as a list, flattens\nL<non-containerized|/language/containers> L<C<Iterable>|/type/Iterable>s into a\nflat list, and returns that list. Keep in mind L<C<Map>|/type/Map> and\nL<C<Hash>|/type/Hash> types are L<C<Iterable>|/type/Iterable> and so will be flattened\ninto lists of pairs.\n\n    say ((1, 2), (3), %(:42a));      # OUTPUT: «((1 2) 3 {a => 42})␤»\n    say ((1, 2), (3), %(:42a)).flat; # OUTPUT: «(1 2 3 a => 42)␤»\n\nNote that L<C<Array>|/type/Array>s containerize their elements by default, and so\nC<flat> will not flatten them. You can use the\n\nL<hyper method call|/language/operators#methodop_%C2%BB._/_methodop_%3E%3E.> to call the\nL«C<.List>|/routine/List» method on all the inner L<C<Iterable>|/type/Iterable>s\nand so de-containerize them, so that C<flat> can flatten them:\n\n    say [[1, 2, 3], [(4, 5), 6, 7]]      .flat; # OUTPUT: «([1 2 3] [(4 5) 6 7])␤»\n    say [[1, 2, 3], [(4, 5), 6, 7]]».List.flat; # OUTPUT: «(1 2 3 4 5 6 7)␤»\n\nFor more fine-tuned options, see L<deepmap|/routine/deepmap>,\nL<duckmap|/routine/duckmap>, and\nL<signature destructuring|/language/signatures#Destructuring_arguments>\n\n=head2 method eager\n\n    method eager() is nodal\n\nInterprets the invocant as a L<C<List>|/type/List>, evaluates it eagerly, and\nreturns that L<C<List>|/type/List>.\n\n    my  $range = 1..5;\n    say $range;         # OUTPUT: «1..5␤»\n    say $range.eager;   # OUTPUT: «(1 2 3 4 5)␤»\n\n=head2 routine elems\n\n    multi method elems(Any:U: --> 1)\n    multi method elems(Any:D:)\n    multi        elems($a)\n    multi        elems(array:D \\a)\n\nInterprets the invocant or argument as a list, and returns the number of\nelements in the list.\n\n    say elems 42;                   # OUTPUT: «1␤»\n    say <a b c>.elems;              # OUTPUT: «3␤»\n    say Whatever.elems ;            # OUTPUT: «1␤»\n\nIt will also return 1 for classes.\n\n=head2 routine end\n\n    multi method end(Any:U: --> 0)\n    multi method end(Any:D:)\n    multi        end($a)\n    multi        end(array:D \\a)\n    multi        end($, *%)\n\nInterprets the invocant or argument as a list, and returns the last index of\nthat list.\n\n    say 6.end;                      # OUTPUT: «0␤»\n    say <a b c>.end;                # OUTPUT: «2␤»\n    say end ^9;                     # OUTPUT: «8␤»\n\n=head2 method pairup\n\n    multi method pairup(Any:U:)\n    multi method pairup(Any:D:)\n\nReturns an\nempty L<C<Seq>|/type/Seq> if the invocant is a type object\n\n    Range.pairup.say; # OUTPUT: «()␤»\n\nInterprets the invocant as a list, and constructs a list of\nL<C<Pair>|/type/Pair>s from it, in the same way that assignment to a\nL<C<Hash>|/type/Hash> does.  That is, it takes two consecutive elements and\nconstructs a pair from them, unless the item in the key position already is a\npair (in which case the pair is passed through, and the next list item, if any,\nis considered to be a key again). It returns a L<C<Seq>|/type/Seq> of L<C<Pair>|/type/Pair>s.\n\n    say (a => 1, 'b', 'c').pairup.raku;     # OUTPUT: «(:a(1), :b(\"c\")).Seq␤»\n\nX<|Syntax,$ (item contextualizer)>\n\n=head2 method Array\n\n    method Array(--> Array:D) is nodal\n\nCoerces the invocant to an L<C<Array>|/type/Array>.\n\n=head2 method List\n\n    method List(--> List:D) is nodal\n\nCoerces the invocant to L<C<List>|/type/List>, using the L<list|/routine/list>\nmethod.\n\n=head2 method serial\n\n    multi method serial()\n\nThis method is Rakudo specific, and is not included in the Raku spec.\n\nThe method returns the self-reference to the instance itself:\n\n=begin code\nmy $b;                 # defaults to Any\nsay $b.serial.^name;   # OUTPUT: «Any␤»\nsay $b.^name;          # OUTPUT: «Any␤»\nmy $breakfast = 'food';\n$breakfast.serial.say; # OUTPUT: «food␤»\n=end code\n\nThis is apparently a no-op, as exemplified by the third example above. However,\nin L<C<HyperSeq>|/type/HyperSeq>s and L<C<RaceSeq>|/type/RaceSeq>s it returns a\nserialized L<C<Seq>|/type/Seq>, so it can be considered the opposite of the C<hyper/race>\nmethods. As such, it ensures that we are in serial list-processing mode, as\nopposed to the autothreading mode of those methods.\n\n=head2 method Hash\n\n    multi method Hash( --> Hash:D)\n\nCoerces the invocant to L<C<Hash>|/type/Hash>.\n\n=head2 method hash\n\n    multi method hash(Any:U:)\n    multi method hash(Any:D:)\n\nWhen called on a type object, returns an empty L<C<Hash>|/type/Hash>. On instances,\nit is equivalent to assigning the invocant to a C<%->sigiled variable and\nreturning that.\n\nSubclasses of C<Any> may choose to return any I<core> type that does the\nL<C<Associative>|/type/Associative> role from L«C<.hash>|/routine/hash». Use\nL«C<.Hash>|/routine/Hash» to coerce specifically to L<C<Hash>|/type/Hash>.\n\n=begin code\nmy $d; # $d is Any\nsay $d.hash; # OUTPUT: {}\n\nmy %m is Map = a => 42, b => 666;\nsay %m.hash;  # OUTPUT: «Map.new((a => 42, b => 666))␤»\nsay %m.Hash;  # OUTPUT: «{a => 42, b => 666}␤»\n=end code\n\n=head2 method Slip\n\n    method Slip(--> Slip:D) is nodal\n\nCoerces the invocant to L<C<Slip>|/type/Slip>.\n\n=head2 method Map\n\n    method Map(--> Map:D) is nodal\n\nCoerces the invocant to L<C<Map>|/type/Map>.\n\n=head2 method Seq\n\n    method Seq() is nodal\n\nCoerces the invocant to L<C<Seq>|/type/Seq>.\n\n=head2 method Bag\n\n    method Bag(--> Bag:D) is nodal\n\nCoerces the invocant to L<C<Bag>|/type/Bag>, whereby\nL<C<Positional>|/type/Positional>s are treated as lists of values.\n\n=head2 method BagHash\n\n    method BagHash(--> BagHash:D) is nodal\n\nCoerces the invocant to L<C<BagHash>|/type/BagHash>, whereby\nL<C<Positional>|/type/Positional>s are treated as lists of values.\n\n=head2 method Set\n\n    method Set(--> Set:D) is nodal\n\nCoerces the invocant to L<C<Set>|/type/Set>, whereby L<C<Positional>|/type/Positional>s\nare treated as lists of values.\n\n=head2 method SetHash\n\n    method SetHash(--> SetHash:D) is nodal\n\nCoerces the invocant to L<C<SetHash>|/type/SetHash>, whereby\nL<C<Positional>|/type/Positional>s are treated as lists of values.\n\n=head2 method Mix\n\n    method Mix(--> Mix:D) is nodal\n\nCoerces the invocant to L<C<Mix>|/type/Mix>, whereby L<C<Positional>|/type/Positional>s\nare treated as lists of values.\n\n=head2 method MixHash\n\n    method MixHash(--> MixHash:D) is nodal\n\nCoerces the invocant to L<C<MixHash>|/type/MixHash>, whereby\nL<C<Positional>|/type/Positional>s are treated as lists of values.\n\n=head2 method Supply\n\n    method Supply(--> Supply:D) is nodal\n\nFirst, it coerces the invocant to a C<list> by applying its\nL«C<.list>|/routine/list» method, and then to a L<C<Supply>|/type/Supply>.\n\n=head2 routine min\n\n    multi method min(&by?, :$k, :$v, :$kv, :$p )\n    multi        min(+args, :&by, :$k, :$v, :$kv, :$p)\n\nCoerces the invocant to L<C<Iterable>|/type/Iterable> and returns the smallest\nelement using L<cmp|/routine/cmp> semantics; in the case of L<C<Map>|/type/Map>s and\nL<C<Hash>|/type/Hash>es, it returns the L<C<Pair>|/type/Pair> with the B<lowest> value.\n\nA L<C<Callable>|/type/Callable> positional argument can be given to the\nC<method> form.  If that L<C<Callable>|/type/Callable> accepts a single argument, then it\nwill be used to convert the values to be sorted B<before> doing comparisons.\nThe original value is still the one returned from C<min>.\n\nIf that L<C<Callable>|/type/Callable> accepts two arguments, it will be used as the\ncomparator instead of C<cmp>.\n\nIn C<sub> form, the invocant is passed as an argument and any L<C<Callable>|/type/Callable>\nmust be specified with the named argument C<:by>.\n\n    say (1,7,3).min();              # OUTPUT: «1␤»\n    say (1,7,3).min({1/$_});        # OUTPUT: «7␤»\n    say min(1,7,3);                 # OUTPUT: «1␤»\n    say min(1,7,3,:by( { 1/$_ } )); # OUTPUT: «7␤»\n    min( %(a => 3, b=> 7 ) ).say ;  # OUTPUT: «a => 3␤»\n\nAs of the 2023.08 Rakudo compiler release, B<additional> named arguments\ncan be specified to get B<all> possible information related to the lowest\nvalue.  Whenever any of these named arguments is specified, the returned\nvalue will B<always> be a L<C<List>|/type/List>.\n\n=item :k\n\nReturns a L<C<List>|/type/List> with the indices of the lowest values found.\n\n=item :v\n\nReturns a L<C<List>|/type/List> with the actual values of the lowest values found.  In\nthe case of a L<C<Map>|/type/Map> or L<C<Hash>|/type/Hash>, these would the L<C<Pair>|/type/Pair>s.\n\n=item :kv\n\nReturns a L<C<List>|/type/List> with the index and the value alternating.\n\n=item :p\n\nReturns a L<C<List>|/type/List> of L<C<Pair>|/type/Pair>s in which the key is the index value, and\nthe value is the actual lowest value (which in the case of a L<C<Map>|/type/Map> or a\nL<C<Hash>|/type/Hash> would be a L<C<Pair>|/type/Pair>).\n\n    say <a b c a>.min(:k);  # OUTPUT:«(0 3)␤»\n    say <a b c a>.min(:v);  # OUTPUT:«(a a)␤»\n    say <a b c a>.min(:kv); # OUTPUT:«(0 a 3 a)␤»\n    say <a b c a>.min(:p);  # OUTPUT:«(0 => a 3 => a)␤»\n\n=head2 routine max\n\n    multi method max(&by?, :$k, :$v, :$kv, :$p )\n    multi        max(+args, :&by, :$k, :$v, :$kv, :$p)\n\nThe interface of the C<max> method / routine is the same as the one of\nL<min|#routine min>.  But instead of the lowest value, it will return the\nB<highest> value.\n\n    say (1,7,3).max();                # OUTPUT: «7␤»\n    say (1,7,3).max({1/$_});          # OUTPUT: «1␤»\n    say max(1,7,3,:by( { 1/$_ } ));   # OUTPUT: «1␤»\n    say max(1,7,3);                   # OUTPUT: «7␤»\n    max( %(a => 'B', b=> 'C' ) ).say; # OUTPUT: «b => C␤»\n\nAs of the 2023.08 Rakudo compiler release:\n\n    say <a b c c>.max(:k);  # OUTPUT:«(2 3)␤»\n    say <a b c c>.max(:v);  # OUTPUT:«(c c)␤»\n    say <a b c c>.max(:kv); # OUTPUT:«(2 c 3 c)␤»\n    say <a b c c>.max(:p);  # OUTPUT:«(2 => c 3 => c)␤»\n\n=head2 routine minmax\n\n    multi method minmax()\n    multi method minmax(&by)\n    multi        minmax(+args, :&by!)\n    multi        minmax(+args)\n\nReturns a L<C<Range>|/type/Range> from the smallest to the largest element.\n\nIf a L<C<Callable>|/type/Callable> positional argument is provided, each value is\npassed into the filter, and its return value is compared instead of the original\nvalue. The original values are still used in the returned L<C<Range>|/type/Range>.\n\nIn C<sub> form, the invocant is passed as an argument and a comparison L<C<Callable>|/type/Callable>\ncan be specified with the named argument C<:by>.\n\n    say (1,7,3).minmax();        # OUTPUT:«1..7␤»\n    say (1,7,3).minmax({-$_});   # OUTPUT:«7..1␤»\n    say minmax(1,7,3);           # OUTPUT: «1..7␤»\n    say minmax(1,7,3,:by( -* )); # OUTPUT: «7..1␤»\n\n=head2 method minpairs\n\n    multi method minpairs(Any:D:)\n\nCalls L«C<.pairs>|/routine/pairs» and returns a L<C<Seq>|/type/Seq> with\nall of the Pairs with minimum values, as judged by the\nL«C<cmp> operator|/routine/cmp»:\n\n    <a b c a b c>.minpairs.raku.put; # OUTPUT: «(0 => \"a\", 3 => \"a\").Seq␤»\n    %(:42a, :75b).minpairs.raku.put; # OUTPUT: «(:a(42),).Seq␤»\n\n=head2 method maxpairs\n\n    multi method maxpairs(Any:D:)\n\nCalls L«C<.pairs>|/routine/pairs» and returns a L<C<Seq>|/type/Seq> with all of the\nPairs with maximum values, as judged by the L«C<cmp>\noperator|/routine/cmp»:\n\n    <a b c a b c>.maxpairs.raku.put; # OUTPUT: «(2 => \"c\", 5 => \"c\").Seq␤»\n    %(:42a, :75b).maxpairs.raku.put; # OUTPUT: «(:b(75),).Seq␤»\n\n=head2 method keys\n\n    multi method keys(Any:U: --> List)\n    multi method keys(Any:D: --> List)\n\nFor defined C<Any> returns its L<keys|/routine/keys> after calling C<list> on it,\notherwise calls C<list> and returns it.\n\n    my $setty = Set(<Þor Oðin Freija>);\n    say $setty.keys; # OUTPUT: «(Þor Oðin Freija)␤»\n\nSee also L<C<List.keys>|/type/List#routine_keys>.\n\nTrying the same on a class will return an empty list, since most of them\ndon't really have keys.\n\n=head2 method flatmap\n\n    method flatmap(&block, :$label)\n\nConvenience method, analogous to L<C<.map(&block)>|#routine_map>L<C<.flat>|#method_flat>.\n\n=head2 method roll\n\n    multi method roll(--> Any)\n    multi method roll($n --> Seq)\n\nCoerces the invocant to a C<list> by applying its\nL«C<.list>|/routine/list» method and uses\nL«C<List.roll>|/type/List#routine_roll» on it.\n\n    my Mix $m = (\"þ\" xx 3, \"ð\" xx 4, \"ß\" xx 5).Mix;\n    say $m.roll;    # OUTPUT: «ð␤»\n    say $m.roll(5); # OUTPUT: «(ß ß þ ß þ)␤»\n\nC<$m>, in this case, is converted into a list and then a (weighted in this case)\ndice is rolled on it. See also L<C<List.roll>|/type/List#routine_roll> for more\ninformation.\n\n=head2 method iterator\n\n    multi method iterator(Any:)\n\nReturns the object as an iterator after converting it to a list. This is the\nfunction called from the C<for> statement.\n\n    .say for 3; # OUTPUT: «3␤»\n\nAn iterable subclass of C<Any> should provide its own implementation of this\nmethod, but other classes can inherit this as-is to provide a\nsingle-item-list iterator in contexts that require one.\n\n=head2 method pick\n\n    multi method pick(--> Any)\n    multi method pick($n --> Seq)\n\nCoerces the invocant to a L<C<List>|/type/List> by applying\nits L«C<.list>|/routine/list» method and uses\nL«C<List.pick>|/type/List#routine_pick» on it.\n\n    my Range $rg = 'α'..'ω';\n    say $rg.pick(3); # OUTPUT: «(β α σ)␤»\n\n\n=head2 routine skip\n\n    multi method skip()\n    multi method skip(Whatever)\n    multi method skip(Callable:D $w)\n    multi method skip(Int() $n)\n    multi method skip($skip, $produce)\n\nCreates a L<C<Seq>|/type/Seq> from 1-item list's iterator and uses\nL«C<Seq.skip>|/type/Seq#method_skip» on it, please check that document for real\nuse cases; calling C<skip> without argument is equivalent to C<skip(1)>.\n\n    multi skip(\\skipper, +values)\n\nAs of release 2022.07 of the Rakudo compiler, there is also a \"sub\" version\nof C<skip>.  It B<must> have the skip specifier as the first argument.  The\nrest of the arguments are turned into a L<C<Seq>|/type/Seq> and then have the C<skip>\nmethod called on it.\n\n=head2 method are\n\n    multi method are(Any:)\n    multi method are(Any: Any $type)\n\nThe argumentless version available as of release 2022.02 of the Rakudo\ncompiler.  The version with the type argument is in the 6.e language version\n(early implementation exists in Rakudo compiler 2024.05+).\n\nIf called without arguments, returns the strictest type (or role) to which\nB<all> elements of the list will smartmatch.  Returns L<C<Nil>|/type/Nil>\non an empty list.\n\n    say (1,2,3).are;        # OUTPUT: «(Int)␤»\n    say <a b c>.are;        # OUTPUT: «(Str)␤»\n    say <42 666>.are;       # OUTPUT: «(IntStr)␤»\n    say (42,666e0).are;     # OUTPUT: «(Real)␤»\n    say (42,i).are;         # OUTPUT: «(Numeric)␤»\n    say (\"a\",42,3.14).are;  # OUTPUT: «(Cool)␤»\n    say ().are;             # OUTPUT: «Nil␤»\n\nScalar values are interpreted as a single element list.\n\n    say 42.are;             # OUTPUT: «(Int)␤»\n    say Int.are;            # OUTPUT: «(Int)␤»\n\nHashes will be interpreted as a list of pairs, and as such will always\nproduce the L<C<Pair>|/type/Pair> type object.  Use the C<.keys> or\nC<.values> method to get the strictest type of the keys or the values of\na hash.\n\n    my %h = a => 42, b => \"bar\";\n    say %h.keys.are;        # OUTPUT: «(Str)␤»\n    say %h.values.are;      # OUTPUT: «(Cool)␤»\n\nIf called with a type argument, will check if all types in the invocant\nsmartmatch with the given type.  If so, returns C<True>.  If any of the\nsmartmatches fails, returns a L<C<Failure>|/type/Failure>.\n\n    say (1,2,3).are(Int);         # OUTPUT: «True␤»\n    say <a b c>.are(Str);         # OUTPUT: «True␤»\n    say <42 666>.are(Int);        # OUTPUT: «True␤»\n    say <42 666>.are(Str);        # OUTPUT: «True␤»\n    say (42,666e0).are(Real);     # OUTPUT: «True␤»\n    say (42,i).are(Numeric);      # OUTPUT: «True␤»\n    say (\"a\",42,3.14).are(Cool);  # OUTPUT: «True␤»\n    say ().are(Int);              # OUTPUT: «True␤»\n\n    Int.are(Str);      # OUTPUT: «Expected 'Str' but got 'Int'␤»\n    (1,2,3).are(Str);  # OUTPUT: «Expected 'Str' but got 'Int' in element 0␤»\n\n=head2 method prepend\n\n    multi method prepend(Any:U: --> Array)\n    multi method prepend(Any:U: @values --> Array)\n\nCalled with no arguments on an empty variable, it initializes it as an\nempty L<C<Array>|/type/Array>; if called with arguments, it creates an array and then\napplies L«C<Array.prepend>|/type/Array#routine_prepend» on it.\n\n    my $a;\n    say $a.prepend; # OUTPUT: «[]␤»\n    say $a;         # OUTPUT: «[]␤»\n    my $b;\n    say $b.prepend(1,2,3); # OUTPUT: «[1 2 3]␤»\n\n=head2 method unshift\n\n    multi method unshift(Any:U: --> Array)\n    multi method unshift(Any:U: @values --> Array)\n\nInitializes C<Any> variable as empty L<C<Array>|/type/Array> and calls\nL«C<Array.unshift>|/type/Array#routine_unshift» on it.\n\n    my $a;\n    say $a.unshift; # OUTPUT: «[]␤»\n    say $a;         # OUTPUT: «[]␤»\n    my $b;\n    say $b.unshift([1,2,3]); # OUTPUT: «[[1 2 3]]␤»\n\n=head2 routine first\n\n    multi method first(Bool:D $t)\n    multi method first(Regex:D $test, :$end, *%a)\n    multi method first(Callable:D $test, :$end, *%a is copy)\n    multi method first(Mu $test, :$end, *%a)\n    multi method first(:$end, *%a)\n    multi        first(Bool:D $t, |)\n    multi        first(Mu $test, +values, *%a)\n\nIn general, coerces the invocant to a C<list> by applying its\nL«C<.list>|/routine/list» method and uses\nL«C<List.first>|/type/List#routine_first» on it.\n\nHowever, this is a multi with different signatures, which are implemented with\n(slightly) different behavior, although using it as a subroutine is equivalent\nto using it as a method with the second argument as the object.\n\nFor starters, using a L<C<Bool>|/type/Bool> as the argument will always return a L<C<Failure>|/type/Failure>.\nThe form that uses a C<$test> will return the first element that smartmatches\nit, starting from the end if C<:end> is used.\n\n    say (3..33).first;           # OUTPUT: «3␤»\n    say (3..33).first(:end);     # OUTPUT: «33␤»\n    say (⅓,⅔…30).first( 0xF );   # OUTPUT: «15␤»\n    say first 0xF, (⅓,⅔…30);     # OUTPUT: «15␤»\n    say (3..33).first( /\\d\\d/ ); # OUTPUT: «10␤»\n\nThe third and fourth examples use the C<Mu $test> forms which smartmatches and\nreturns the first element that does. The last example uses as a test a regex for\nnumbers with two figures, and thus the first that meets that criterion is number\n10. This last form uses the L<C<Callable>|/type/Callable> multi:\n\n    say (⅓,⅔…30).first( * %% 11, :end, :kv ); # OUTPUT: «(65 22)␤»\n\nBesides, the search for first will start from the C<:end> and returns the set of\nkey/values in a list; the I<key> in this case is simply the position it occupies\nin the L<C<Seq>|/type/Seq>. The C<:kv> argument, which is part of the C<%a> argument in the\ndefinitions above, modifies what C<first> returns, providing it as a flattened\nlist of keys and values; for a listy object, the key will always be the index.\n\nFrom version 6.d, the test can also be a L<C<Junction>|/type/Junction>:\n\n    say (⅓,⅔…30).first( 3 | 33, :kv ); # OUTPUT: «(8 3)␤»\n\n=head2 method unique\n\n    multi method unique()\n    multi method unique( :&as!, :&with! )\n    multi method unique( :&as! )\n    multi method unique( :&with! )\n\nCreates a sequence of unique elements either of the object or of C<values> in\nthe case it's called as a C<sub>.\n\n    <1 2 2 3 3 3>.unique.say; # OUTPUT: «(1 2 3)␤»\n    say unique <1 2 2 3 3 3>; # OUTPUT: «(1 2 3)␤»\n\nThe C<:as> and C<:with> parameters receive functions that are used for\ntransforming the item before checking equality, and for checking equality, since\nby default the L<C<===>|/routine/===> operator is used:\n\n    (\"1\", 1, \"1 \", 2).unique( as => Int, with => &[==] ).say; # OUTPUT: «(1 2)␤»\n\nPlease see L<C<unique>|/type/independent-routines#routine_unique> for\nadditional examples that use its sub form.\n\n=head2 method repeated\n\n    multi method repeated()\n    multi method repeated( :&as!, :&with! )\n    multi method repeated( :&as! )\n    multi method repeated( :&with! )\n\nSimilarly to L<C<unique>|/type/Any#method_unique>, finds repeated elements in\nC<values> (as a routine) or in the object, using the C<:as> associative argument\nas a normalizing function and C<:with> as equality function.\n\n    <1 -1 2 -2 3>.repeated(:as(&abs),:with(&[==])).say; # OUTPUT: «(-1 -2)␤»\n    (3+3i, 3+2i, 2+1i).repeated(as => *.re).say;        # OUTPUT: «(3+2i)␤»\n\nIt returns the last repeated element before normalization, as shown in the\nexample above. See\nL<C<repeated>|/type/independent-routines#routine_repeated> for more\nexamples that use its sub form.\n\n=head2 method squish\n\n    multi method squish( :&as!, :&with = &[===] )\n    multi method squish( :&with = &[===] )\n\nSimilar to L<C<.repeated>|/type/Any#method_repeated>, returns the sequence of\nfirst elements of contiguous sequences of equal elements, after normalization by\nthe function C<:as>, if present, and using as an equality operator the C<:with>\nargument or C<===> by default.\n\n=for code\n\"aabbccddaa\".comb.squish.say;             # OUTPUT: «(a b c d a)␤»\n\"aABbccdDaa\".comb.squish( :as(&lc) ).say; # OUTPUT: «(a B c d a)␤»\n(3+2i,3+3i,4+0i).squish( as => *.re, with => &[==]).put; # OUTPUT: «3+2i 4+0i␤»\n\nAs shown in the last example, a sequence can contain a single element. See\nL<C<squish>|/type/independent-routines#routine_squish> for additional C<sub>\nexamples.\n\n=head2 method permutations\n\n    method permutations(|c)\n\nCoerces the invocant to a C<list> by applying its\nL«C<.list>|/routine/list» method and uses\nL«C<List.permutations>|/type/List#routine_permutations» on it.\n\n    say <a b c>.permutations;\n    # OUTPUT: «((a b c) (a c b) (b a c) (b c a) (c a b) (c b a))␤»\n    say set(1,2).permutations;\n    # OUTPUT: «((2 => True 1 => True) (1 => True 2 => True))␤»\n\nPermutations of data structures with a single or no element will return a\nlist containing an empty list or a list with a single element.\n\n    say 1.permutations; # OUTPUT: «((1))␤»\n\n=head2 method join\n\n    method join($separator = '') is nodal\n\nConverts the object to a list by calling\nL<C<self.list>|/type/Any#method_list>,\nand calls L<C<.join>|/type/List#routine_join> on the list.\nCan take a separator, which is an empty string by default.\n\n    (1..3).join.say;       # OUTPUT: «123␤»\n    <a b c>.join(\"❧\").put; # OUTPUT: «a❧b❧c␤»\n\n=head2 routine categorize\n\n    multi method categorize()\n    multi method categorize(Whatever)\n    multi method categorize($test, :$into!, :&as)\n    multi method categorize($test, :&as)\n    multi        categorize($test, +items, :$into!, *%named )\n    multi        categorize($test, +items, *%named )\n\nThe first form will always fail. The second form classifies on the\nidentity of the given object, which usually only makes sense in\ncombination with the C<:&as> argument.\n\nIn its simplest form, it uses a C<$test> whose result will be used as a key; the\nvalues of the key will be an array of the elements that produced that key as a\nresult of the test.\n\n=for code\nsay (1..13).categorize( * %% 3);\nsay categorize( * %% 3, 1..13)\n# OUTPUT: «{False => [1 2 4 5 7 8 10 11 13], True => [3 6 9 12]}␤»\n\nThe C<:as> argument will normalize before categorizing\n\n=for code\nsay categorize( * %% 3, -5..5, as => &abs )\n# OUTPUT: «{False => [5 4 2 1 1 2 4 5], True => [3 0 3]}␤»\n\nThe C<$into> associative argument can be used to put the result instead of\nreturning a new L<C<Hash>|/type/Hash>.\n\n=for code\nmy %leap-years;\nmy @years = (2002..2009).map( { Date.new( $_~\"-01-01\" ) } );\n@years.categorize( *.is-leap-year , into => %leap-years );\nsay %leap-years\n# OUTPUT:\n# «{ False\n# => [2002-01-01 2003-01-01 2005-01-01 2006-01-01 2007-01-01 2009-01-01],\n#    True => [2004-01-01 2008-01-01]}␤»\n\nThe function used to categorize can return an array indicating all possible bins\ntheir argument can be put into:\n\n=begin code\nsub divisible-by( Int $n --> Array(Seq) ) {\n    gather {\n        for <2 3 5 7> {\n            take $_ if $n %% $_;\n        }\n    }\n}\n\nsay (3..13).categorize( &divisible-by );\n# OUTPUT:\n# «{2 => [4 6 8 10 12], 3 => [3 6 9 12], 5 => [5 10], 7 => [7]}␤»\n=end code\n\nIn this case, every number in the range is classified in as many bins as it can\nbe divided by.\n\nSupport for using L<C<Whatever>|/type/Whatever> as the test was added in Rakudo compiler\nrelease 2023.02.\n\n=head2 routine classify\n\n    multi method classify()\n    multi method classify(Whatever)\n    multi method classify($test, :$into!, :&as)\n    multi method classify($test, :&as)\n    multi        classify($test, +items, :$into!, *%named )\n    multi        classify($test, +items, *%named )\n\nThe first form will always fail. The second form classifies on the\nidentity of the given object, which usually only makes sense in\ncombination with the C<:&as> argument.\n\nThe rest include a C<$test> argument, which is a function that will\nreturn a scalar for every input; these will be used as keys of a hash\nwhose values will be arrays with the elements that output that key for\nthe test function.\n\n=for code\nmy @years = (2003..2008).map( { Date.new( $_~\"-01-01\" ) } );\n@years.classify( *.is-leap-year , into => my %leap-years );\nsay %leap-years;\n# OUTPUT: «{False => [2003-01-01 2005-01-01 2006-01-01 2007-01-01],\n#           True => [2004-01-01 2008-01-01]}␤»\n\n\nSimilarly to L<C<.categorize>|/type/Any#routine_categorize>, elements can be\nnormalized by the L<C<Callable>|/type/Callable> passed with the C<:as> argument, and it can use\nthe C<:into> named argument to pass a L<C<Hash>|/type/Hash> the results will be classified\ninto; in the example above, it's defined on the fly.\n\nFrom version 6.d, C<.classify> will also work with L<C<Junction>|/type/Junction>s.\n\nSupport for using L<C<Whatever>|/type/Whatever> as the test was added in Rakudo compiler\nrelease 2023.02.\n\n=head2 routine reduce\n\n    multi method reduce(Any:U: & --> Nil)\n    multi method reduce(Any:D: &with)\n    multi        reduce (&with, +list)\n\nThis routine combines the elements in a list-y object, and produces a single\nresult, by applying a binary subroutine. It applies its argument (or first\nargument for the sub form) as an operator to all the elements in the object (or\nsecond argument for the sub form), producing a single result. The subroutine\nmust be either an\nL<infix operator|/language/operators#index-entry-infix_operator>\nor take two positional arguments. When using an infix operator, we must provide\nthe code object of its subroutine version, i.e., the operator category, followed\nby a colon, then a list quote construct with the symbol(s) that make up the\noperator (e.g., C«infix:<+>»). See L<Operators|/language/operators>.\n\n    say (1..4).reduce(&infix:<+>);   # OUTPUT: «10␤»\n    say reduce &infix:<+>, 1..4;     # OUTPUT: «10␤»\n    say reduce &min, 1..4;           # OUTPUT: «1␤»\n\n    sub hyphenate(Str \\a, Str \\b) { a ~ '-' ~ b }\n    say reduce &hyphenate, 'a'..'c'; # OUTPUT: «a-b-c␤»\n\nApplied to a class, the routine will always return L<C<Nil>|/type/Nil>.\n\n    say Range.reduce(&infix:<+>);    # OUTPUT: «Nil␤»\n    say Str.reduce(&infix:<~>);      # OUTPUT: «Nil␤»\n\nSee L<List.reduce|/type/List#routine_reduce> for a more thorough discussion.\n\n=head2 routine produce\n\n    multi method produce(Any:U: & --> Nil)\n    multi method produce(Any:D: &with)\n    multi        produce (&with, +list)\n\nThis is similar to L<C<reduce>|/routine/reduce#(List)_routine_reduce>, but\nreturns a list with the accumulated values instead of a single result.\n\n=for code\n<10 5 3>.reduce( &[*] ).say ; # OUTPUT: «150␤»\n<10 5 3>.produce( &[*] ).say; # OUTPUT: «(10 50 150)␤»\n\nThe last element of the produced list would be the output produced by the\nC<.reduce> method.\n\nIf it's a class, it will simply return Nil.\n\n=head2 method pairs\n\n    multi method pairs(Any:U:)\n    multi method pairs(Any:D:)\n\nReturns an empty\nL<C<List>|/type/List> if the invocant is a type object:\n\n    say Num.pairs; # OUTPUT: «()␤»\n\nFor a value object, it converts the invocant to a L<C<List>|/type/List> via the\nC<list> method and returns the result of L<List.pairs|/type/List#routine_pairs>\non it.\n\n    <1 2 2 3 3 3>.Bag.pairs.say;# OUTPUT: «(1 => 1 3 => 3 2 => 2)␤»\n\nIn this case, every element (with weight) in a bag is converted to a pair.\n\n=head2 method antipairs\n\n    multi method antipairs(Any:U:)\n    multi method antipairs(Any:D:)\n\nReturns an\nempty L<C<List>|/type/List> if the invocant is a type object\n\n    Range.antipairs.say; # OUTPUT: «()␤»\n\nIf it's a value object, it returns the inverted list of pairs after converting\nit to a list of pairs; the values will become keys and the other way round.\n\n    %(s => 1, t=> 2, u => 3).antipairs.say ;# OUTPUT: «(2 => t 1 => s 3 => u)␤»\n\n=head2 method invert\n\n    multi method invert(Any:U:)\n    multi method invert(Any:D:)\n\nApplied to a type object will return an empty list; applied to an object will\nconvert it to a list and apply L<C<List.invert>|/type/List#routine_invert> to\nit, that is, interchange key with value in every Pair. The resulting list needs\nto be a list of L<C<Pair>|/type/Pair>s.\n\n    \"aaabbcccc\".comb.Bag.invert.say; # OUTPUT: «(4 => c 3 => a 2 => b)␤»\n\nIn this case, a L<C<Bag>|/type/Bag> can be converted to a list of L<C<Pair>|/type/Pair>s. If the result of\nconverting the object to a list is not a list of pairs, the method will fail.\n\n\n=head2 routine kv\n\n    multi method kv(Any:U:)\n    multi method kv(Any:D:)\n    multi        kv($x)\n\n\nReturns an empty L<C<List>|/type/List> if the invocant is a type object:\n\n    Sub.kv.say ;# OUTPUT: «()␤»\n\nIt calls C<list> on the invocant for value objects and returns the result of\nL<List.kv|/type/List#routine_kv> on it as a list where keys and values will be\nordered and contiguous\n\n    <1 2 3>.kv.say; # OUTPUT: «(0 1 1 2 2 3)␤»\n\nIn the case of L<C<Positional>|/type/Positional>s, the indices will be considered I<keys>.\n\n=head2 method toggle\n\n    method toggle(Any:D: *@conditions where .all ~~ Callable:D, Bool :$off  --> Seq:D)\n\nL<Iterates|/routine/iterator> over the invocant, producing a L<C<Seq>|/type/Seq>,\ntoggling whether the received values are propagated to the result on and off,\ndepending on the results of calling L<C<Callables>|/type/Callable> in\nC<@conditions>:\n\n=for code\nsay (1..15).toggle(* < 5, * > 10, * < 15); # OUTPUT: «(1 2 3 4 11 12 13 14)␤»\nsay (1..15).toggle(:off, * > 2, * < 5, * > 10, * < 15); # OUTPUT: «(3 4 11 12 13 14)␤»\n\nImagine a switch that's either on or off (C<True> or C<False>), and values are\nproduced if it's on. By default, the initial state of that switch is in \"on\"\nposition, unless C<:$off> is set to a true value, in which case the initial\nstate will be \"off\".\n\nA L<C<Callable>|/type/Callable> from the L<head|/routine/head> of C<@conditions> is\ntaken (if any are available) and it becomes the current tester. Each value from\nthe original sequence is tested by calling the tester L<C<Callable>|/type/Callable>\nwith that value. The state of our imaginary switch is set to the return value\nfrom the tester: if it's truthy, set switch to \"on\",  otherwise set it to \"off\".\n\nWhenever the switch is I<toggled> (i.e. switched from \"off\" to \"on\" or from\n\"on\" to \"off\"), the current tester L<C<Callable>|/type/Callable> is replaced by the\nnext L<C<Callable>|/type/Callable> in C<@conditions>, if available, which will be\nused to test any further values. If no more tester L<C<Callable>|/type/Callable>s are available, the\nswitch will remain in its current state until the end of iteration.\n\n=begin code\n# our original sequence of elements:\nsay list ^10; # OUTPUT: «(0 1 2 3 4 5 6 7 8 9)␤»\n# toggled result:\nsay ^10 .toggle: * < 4, * %% 2, &is-prime; # OUTPUT: «(0 1 2 3 6 7)␤»\n\n# First tester Callable is `* < 4` and initial state of switch is \"on\".\n# As we iterate over our original sequence:\n# 0 => 0 < 4 === True  switch is on, value gets into result, switch is\n#                      toggled, so we keep using the same Callable:\n# 1 => 1 < 4 === True  same\n# 2 => 2 < 4 === True  same\n# 3 => 3 < 4 === True  same\n# 4 => 4 < 4 === False switch is now off, \"4\" does not make it into the\n#                      result. In addition, our switch got toggled, so\n#                      we're switching to the next tester Callable\n# 5 => 5 %% 2 === False  switch is still off, keep trying to find a value\n# 6 => 6 %% 2 === True   switch is now on, take \"6\" into result. The switch\n#                        toggled, so we'll use the next tester Callable\n# 7 => is-prime(7) === True  switch is still on, take value and keep going\n# 8 => is-prime(8) === False switch is now off, \"8\" does not make it into\n#                            the result. The switch got toggled, but we\n#                            don't have any more tester Callables, so it\n#                            will remain off for the rest of the sequence.\n=end code\n\nSince the toggle of the switch's state loads the next tester\nL<C<Callable>|/type/Callable>, setting C<:$off> to a C<True> value affects when\nfirst tester is discarded:\n\n=begin code\n# our original sequence of elements:\nsay <0 1 2>; # OUTPUT: «(0 1 2)␤»\n# toggled result:\nsay <0 1 2>.toggle: * > 1; # OUTPUT: «()␤»\n\n# First tester Callable is `* > 1` and initial state of switch is \"on\".\n# As we iterate over our original sequence:\n# 0 => 0 > 1 === False  switch is off, \"0\" does not make it into result.\n#                      In addition, switch got toggled, so we change the\n#                      tester Callable, and since we don't have any more\n#                      of them, the switch will remain \"off\" until the end\n=end code\n\nThe behavior changes when C<:off> is used:\n\n=begin code\n# our original sequence of elements:\nsay <0 1 2>; # OUTPUT: «(0 1 2)␤»\n# toggled result:\nsay <0 1 2>.toggle: :off, * > 1; # OUTPUT: «(2)␤»\n\n# First tester Callable is `* > 1` and initial state of switch is \"off\".\n# As we iterate over our original sequence:\n# 0 => 0 > 1 === False  switch is off, \"0\" does not make it into result.\n#                       The switch did NOT get toggled this time, so we\n#                       keep using our current tester Callable\n# 1 => 1 > 1 === False  same\n# 2 => 2 > 1 === True   switch is on, \"2\" makes it into the result\n=end code\n\n=head2 routine head\n\n    multi method head(Any:D:) is raw\n    multi method head(Any:D: Callable:D $w)\n    multi method head(Any:D: $n)\n\nReturns either the first element in the object, or the first C<$n> if that's\nused.\n\n    \"aaabbc\".comb.head.put; # OUTPUT: «a␤»\n    say ^10 .head(5);           # OUTPUT: «(0 1 2 3 4)␤»\n    say ^∞ .head(5);            # OUTPUT: «(0 1 2 3 4)␤»\n    say ^10 .head;              # OUTPUT: «0␤»\n    say ^∞ .head;               # OUTPUT: «0␤»\n\nIn the first two cases, the results are different since there's no defined order\nin L<C<Mix>|/type/Mix>es. In the other cases, it returns a L<C<Seq>|/type/Seq>. A L<C<Callable>|/type/Callable> can be used\nto return all but the last elements:\n\n    say (^10).head( * - 3 );# OUTPUT: «(0 1 2 3 4 5 6)␤»\n\nAs of release 2022.07 of the Rakudo compiler, there is also a \"sub\" version\nof C<head>.\n\n    multi head(\\specifier, +values)\n\nIt B<must> have the head specifier as the first argument.  The rest of\nthe arguments are turned into a L<C<Seq>|/type/Seq> and then have the C<head>\nmethod called on it.\n\n=head2 routine tail\n\n    multi method tail() is raw\n    multi method tail($n)\n\nReturns the last or the list of the C<$n> last elements of an object. C<$n> can\nbe a L<C<Callable>|/type/Callable>, usually a L<C<WhateverCode>|/type/WhateverCode>, which will be used to get all but\nthe first C<n> elements of the object.\n\n=for code\nsay (^12).reverse.tail ;     # OUTPUT: «0␤»\nsay (^12).reverse.tail(3);   # OUTPUT: «(2 1 0)␤»\nsay (^12).reverse.tail(*-7); # OUTPUT: «(4 3 2 1 0)␤»\n\nAs of release 2022.07 of the Rakudo compiler, there is also a \"sub\" version\nof C<tail>.\n\n    multi tail(\\specifier, +values)\n\nIt B<must> have the tail specifier as the first argument.  The rest of\nthe arguments are turned into a L<C<Seq>|/type/Seq> and then have the C<tail>\nmethod called on it.\n\n=head2 method tree\n\n    multi method tree(Any:U:)\n    multi method tree(Any:D:)\n    multi method tree(Any:D: Whatever )\n    multi method tree(Any:D: Int(Cool) $count)\n    multi method tree(Any:D: @ [&first, *@rest])\n    multi method tree(Any:D: &first, *@rest)\n\nReturns the class if it's undefined or if it's not L<C<Iterable>|/type/Iterable>,\nreturns the result of applying the C<tree> method to its invocant otherwise.\n\n    say Any.tree; # OUTPUT: «Any␤»\n\nC<.tree> has different prototypes for L<C<Iterable>|/type/Iterable> elements.\n\n=for code\nmy @floors = ( 'A', ('B','C', ('E','F','G')));\nsay @floors.tree(1).flat.elems; # OUTPUT: «6␤»\nsay @floors.tree(2).flat.elems; # OUTPUT: «2␤»\nsay @floors.tree( *.join(\"-\"),*.join(\"—\"),*.join(\"|\"));# OUTPUT: «A-B—C—E|F|G␤»\n\nWith a number, it iteratively applies C<tree> to every element in the\nlower level; the first instance will apply C<.tree(0)> to every\nelement in the array, and likewise for the next example.\n\nThe second prototype applies the L<C<WhateverCode>|/type/WhateverCode> passed as arguments\nto every level in turn; the first argument will go to level 1 and so\non. C<tree> can, thus, be a great way to process complex all levels of\ncomplex, multi-level, data structures.\n\n=head2 method nl-out\n\n    method nl-out(--> Str)\n\nReturns L<C<Str>|/type/Str> with the value of \"\\n\". See\nL«C<IO::Handle.nl-out>|/type/IO::Handle#method_nl-out» for the\ndetails.\n\n    Num.nl-out.print;     # OUTPUT: «␤»\n    Whatever.nl-out.print;# OUTPUT: «␤»\n    33.nl-out.print;      # OUTPUT: «␤»\n\n=head2 method combinations\n\n    method combinations(|c)\n\nCoerces the invocant to a C<list> by applying its L«C<.list>|/routine/list»\nmethod and uses L«C<List.combinations>|/type/List#routine_combinations» on it.\n\n=for code\nsay (^3).combinations; # OUTPUT: «(() (0) (1) (2) (0 1) (0 2) (1 2) (0 1 2))␤»\n\nCombinations on an empty data structure will return a list with a single\nelement, an empty list; on a data structure with a single element it will\nreturn a list with two lists, one of them empty and the other with a single\nelement.\n\n    say set().combinations; # OUTPUT: «(())␤»\n\n=head2 method grep\n\n    method grep(Mu $matcher, :$k, :$kv, :$p, :$v --> Seq)\n\nCoerces the invocant to a C<list> by applying\nits L«C<.list>|/routine/list» method and uses\nL«C<List.grep>|/type/List#routine_grep» on it.\n\nFor undefined invocants, based on C<$matcher> the return value can\nbe either C<((Any))> or the empty List.\n\n    my $a;\n    say $a.grep({ True }); # OUTPUT: «((Any))␤»\n    say $a.grep({ $_ });   # OUTPUT: «()␤»\n\n=head2 method append\n\n    multi method append(Any:U \\SELF: |values)\n\nIn the case the instance is not a positional-thing, it instantiates it as a new\nL<C<Array>|/type/Array>, otherwise clone the current instance. After that, it\nappends the values passed as arguments to the array obtained calling\nL«C<Array.append>|/type/Array#method_append» on it.\n\n    my $a;\n    say $a.append; # OUTPUT: «[]␤»\n    my $b;\n    say $b.append((1,2,3)); # OUTPUT: «[1 2 3]␤»\n\n=head2 method values\n\n    multi method values(Any:U:)\n    multi method values(Any:D:)\n\nWill return an empty list for undefined or class arguments, and the object\nconverted to a list otherwise.\n\n    say (1..3).values; # OUTPUT: «(1 2 3)␤»\n    say List.values;   # OUTPUT: «()␤»\n\n=head2 method collate\n\n    method collate()\n\nThe C<collate> method sorts taking into account Unicode grapheme\ncharacteristics; that is, sorting more or less as one would expect instead of\nusing the order in which their codepoints appear. C<collate> will behave this\nway if the object it is applied to is L<C<Iterable>|/type/Iterable>.\n\n=begin code\nsay ('a', 'Z').sort; # (Z a)\nsay ('a', 'Z').collate; # (a Z)\nsay <ä a o ö>.collate; # (a ä o ö)\nmy %hash = 'aa' => 'value', 'Za' => 'second';\nsay %hash.collate; # (aa => value Za => second);\n=end code\n\nThis method is affected by the\nL<C<$*COLLATION>|/language/variables#index-entry-$*COLLATION> variable, which\nconfigures the four X<collation levels|Language,collation levels>. While Primary, Secondary and\nTertiary mean different things for different scripts, for the Latin script used\nin English they mostly correspond with Primary being Alphabetic, Secondary being\nDiacritics and Tertiary being Case.\n\nIn the example below you can see how when we disable tertiary collation which in\nLatin script generally is for case, and also disable quaternary which breaks\nany ties by checking the codepoint values of the strings, we get B<Same> back\nfor B<A> and B<a>:\n\n    $*COLLATION.set(:quaternary(False), :tertiary(False));\n    say 'a' coll 'A'; # OUTPUT: «Same␤»\n    say ('a','A').collate == ('A','a').collate; # OUTPUT: «True␤»\n\nThe variable affects the L<C<coll>|/routine/coll> operator as shown as well as\nthis method.\n\n=head2 method cache\n\n    method cache()\n\nProvides a L<C<List>|/type/List> representation of the object itself, calling\nthe method C<list> on the instance.\n\n=head2 method batch\n\n    multi method batch(Int:D $batch)\n    multi method batch(Int:D :$elems!)\n\nCoerces the invocant to a C<list> by applying\nits L«C<.list>|/routine/list» method and uses\nL«C<List.batch>|/type/List#method_batch» on it.\n\n=head2 method rotor\n\n    multi method rotor(Any:D: Int:D $batch, :$partial)\n    multi method rotor(Any:D: *@cycle, :$partial)\n\nCreates a L<C<Seq>|/type/Seq> that groups the elements of the object in lists of C<$batch>\nelements.\n\n    say (3..9).rotor(3); # OUTPUT: «((3 4 5) (6 7 8))␤»\n\nWith the C<:partial> named argument, it will also include lists that do not get\nto be the C<$batch> size:\n\n    say (3..10).rotor(3, :partial); # OUTPUT: «((3 4 5) (6 7 8) (9 10))␤»\n\nC<.rotor> can be called with an array of integers and pairs, which will be\napplied in turn. While integers will establish the batch size, as above,\nL<C<Pair>|/type/Pair>s will use the key as batch size and the value as number of elements to\nskip if it's positive, or overlap if it's negative.\n\n    say (3..11).rotor(3, 2 => 1, 3 => -2, :partial);\n    # OUTPUT: «((3 4 5) (6 7) (9 10 11) (10 11))␤»\n\nIn this case, the first batch (ruled by an integer) has 3 elements; the second\none has 2 elements (key of the pair), but skips one (the number 8); the third\none has size 2 (because partials are allowed), and an overlap of 2 also.\n\nThe overlap cannot be larger than the sublist size; in that case, it will\nthrow an L<C<Exception>|/type/Exception>:\n\n=for code :skip-test<Throws>\nsay (3..11).rotor(3, 2 => 1, 3 => -4, :partial);\n# OUTPUT: «(exit code 1) Rotorizing gap is out of range. Is: -4, should be in\n# -3..^Inf; ␤Ensure a negative gap is not larger than the length of the\n# sublist␤ ␤␤»\n\nNon-L<C<Int>|/type/Int> values of C<$batch> will be coerced to Int:\n\n    say (3..9).rotor(3+⅓); # OUTPUT: «((3 4 5) (6 7 8))␤»\n\nPlease see also L<C<list.rotor>|/type/List#routine_rotor> for examples applied to\nlists.\n\n=head2 method sum\n\n    method sum() is nodal\n\nIf the content is iterable, it returns the sum of the values after pulling them\none by one, or 0 if the list is empty.\n\n=for code\n(3,2,1).sum; # OUTPUT: «6␤»\nsay 3.sum;   # OUTPUT: «3␤»\n\nIt will fail if any of the elements cannot be converted to a number.\n\n=head2 multi method slice\n\n    method slice(Any:D: *@indices --> Seq:D)\n\nAvailable as of the 2021.02 release of the Rakudo compiler.\n\nConverts the invocant to a L<C<Seq>|/type/Seq> and then calls the\nL<slice method|/type/Seq#multi_method_slice> on it.\n\n    say (1..10).slice(0, 3..6, 8);  # OUTPUT: «(1 4 5 6 7 9)␤»\n\n=head2 routine snip\n\n    multi        snip(\\matcher, +values)\n    multi method snip(\\values: \\matcher)\n\nAvailable as of 6.e language version (early implementation exists in Rakudo\ncompiler 2022.07+).\n\nThe C<snip> method / subroutine provides a way to cut a given L<C<Iterable>|/type/Iterable>\ninto two or more L<C<List>|/type/List>s.  A \"snip\" will be made as soon as the smartmatch\nof a value in the given L<C<Iterable>|/type/Iterable> returns False.  The matcher may also\nbe a list of matchers: as soon as a \"snip\" was made, will it start checking\nusing the next matcher.  The rest of the L<C<Iterable>|/type/Iterable> will be produced if\nthere are no matchers left.\n\n=for code :solo :preamble<use v6.e.PREVIEW;>\n.say for snip * < 10, 2, 5, 13, 9, 6;      # OUTPUT: «(2 5)␤(13 9 6)␤»\n.say for snip (* < 10, * < 20), 5, 13, 29; # OUTPUT: «(5)␤(13)␤(29)␤»\n.say for snip Int, 2, 5, 5, \"a\", \"b\";      # OUTPUT: «(2 5 5)␤(a b)␤»\n.say for (2, 5, 13, 9, 6).snip(* < 10);    # OUTPUT: «(2 5)␤(13 9 6)␤»\n.say for (5, 13,29).snip(* < 10, * < 20);  # OUTPUT: «(5)␤(13)␤(29)␤»\n.say for (2, 5, 5, \"a\", \"b\").snip: Int;    # OUTPUT: «(2 5 5)␤(a b)␤»\n\n=head2 routine snitch\n\n    multi  snitch(\\snitchee)\n    multi  snitch(&snitcher, \\snitchee)\n    method snitch(\\snitchee: &snitcher = &note)\n\nAvailable as of 6.e language version (early implementation exists in Rakudo\ncompiler 2022.12+).\n\nThe C<snitch> method / subroutine is a debugging / logging tool that will\nalways return any invocant / argument given unchanged.\n\nBy default, it will L<note|/routine/note> the invocant / argument, but\nthis can be overridden by specifying a L<C<Callable>|/type/Callable> that is expected to\ntake the invocant / argument as its only argument.\n\n=for code :solo :preamble<use v6.e.PREVIEW;> :ok-test<dd>\n(my $a = 42).snitch = 666; say $a;  # OUTPUT: «42␤666␤»\n(1..5).snitch;                      # OUTPUT: «1..5␤»\n(1..5).Seq.snitch;                  # OUTPUT: «(1 2 3 4 5)␤»\n(1..5).Seq.snitch(&dd);             # OUTPUT: «(1, 2, 3, 4, 5).Seq␤»\n(1..5).map(*+1).snitch;             # OUTPUT: «(2 3 4 5 6)␤»\nsay (1..3).Seq.snitch.map(*+2);     # OUTPUT: «(1 2 3)␤(3 4 5)␤»\n\nThe same, using the feed operator:\n\n=for code :solo :preamble<use v6.e.PREVIEW;>\n(1..3).Seq ==> snitch() ==> map(*+2) ==> say();  # OUTPUT: «(1 2 3)␤(3 4 5)␤»\n\nUsing a custom logger:\n\n=begin code\nmy @snitched;\nmy @result = (1..3).Seq.snitch({ @snitched.push($_) }).map(*+2);\nsay @snitched;  # OUTPUT: «[(1 2 3)]␤»\nsay @result;    # OUTPUT: «[3 4 5]␤»\n=end code\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Array.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class Array\n\n=SUBTITLE Sequence of itemized values\n\n    class Array is List {}\n\nAn C<Array> is a L<C<List>|/type/List> which forces all its elements to be\nscalar containers, which means you can assign to array elements.\n\nC<Array> implements L<C<Positional>|/type/Positional> and as such provides support for\nL<subscripts|/language/subscripts>.\n\nB<Note> from version 6.d, C<.raku> (C<.perl> before release 2019.11) can be\ncalled on multi-dimensional arrays.\n\nIf you want to declare an C<Array> of a specific type, you can do so using\nseveral different ways:\n\n=for code\nmy @foo of Int = 33,44;        # [33 44]\nmy @bar is Array[Int] = 33,44; # [33 44]\n\nThe second example, which parameterizes a type, is only available from Rakudo\n2019.03.\n\n=head1 Methods\n\n=head2 method gist\n\nExactly the same as L«C<List.gist>|/type/List#method_gist»,\nexcept using square brackets for surrounding delimiters.\n\n=head2 method pop\n\n    method pop(Array:D:) is nodal\n\nRemoves and returns the last item from the array.  Fails if the array is empty.\n\nLike many C<Array> methods, method C<pop> may be called via the corresponding\nL<subroutine|/type/independent-routines#sub_pop>. For example:\n\n    my @foo = <a b>; # a b\n    @foo.pop;        # b\n    pop @foo;        # a\n    pop @foo;\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Cannot::Empty: Cannot pop from an empty Array␤»\n\n=head2 method push\n\n    multi method push(Array:D: **@values is raw --> Array:D)\n    multi method push(Array:D: \\value --> Array:D)\n    multi method push(Array:D: Slip \\values --> Array:D)\n\nAdds the provided value or values to the end of the array, and returns the\nmodified array. If any argument is a L<C<Slip>|/type/Slip>, method C<push> will add the values\nproduced by the argument's L<iterator|/routine/iterator>. It throws if the\ninvocant array or a L<C<Slip>|/type/Slip> L<is lazy|/routine/is-lazy>.\n\nExample:\n\n    my @foo = <a b c>;\n    @foo.push: 'd';\n    say @foo;                   # OUTPUT: «[a b c d]␤»\n\nNote that C<push> does not attempt to flatten its argument list.  If you pass\nan array or list as the thing to push, it becomes one additional element:\n\n    my @a = <a b c>;\n    my @b = <d e f>;\n    @a.push: @b;\n    say @a.elems;               # OUTPUT: «4␤»\n    say @a[3].join;             # OUTPUT: «def␤»\n\nMultiple values are added to the array only if you supply them as separate\narguments or in a L<C<Slip>|/type/Slip>:\n\n   my @a = '1';\n   say @a.push: 'a', 'b';       # OUTPUT: «[1 a b]␤»\n   my @c = <E F>;\n   say @a.push: @c.Slip;        # OUTPUT: «[1 a b E F]␤»\n\nSee L<method append|/type/Array#method_append> if you want to append multiple\nvalues that are produced by a single non-slipping L<C<Iterable>|/type/Iterable>.\n\n=head2 method append\n\n    multi method append(Array:D: **@values is raw --> Array:D)\n    multi method append(Array:D: \\arg --> Array:D)\n\nAdds the provided values to the end of the array and returns the modified array,\nor throws if the invocant array or an argument that requires flattening L<is\nlazy|/routine/is-lazy>.\n\nIn contrast with L<method push|/type/Array#method_push>, method C<append>\nadheres to the L<single argument rule|/language/functions#Slurpy_conventions>\nand is probably best thought of as:\n\n    multi method append(Array:D: +values --> Array:D)\n\nThis means that if you pass a B<single> argument that is a\nnon-L<itemized|/language/mop#VAR> L<C<Iterable>|/type/Iterable>, C<append> will try to flatten it.\n\nFor example:\n\n    my @a = <a b c>;\n    my @b = <d e f>;\n    @a.append: @b;\n    say @a.elems;               # OUTPUT: «6␤»\n    say @a;                     # OUTPUT: «[a b c d e f]␤»\n\n=head2 method elems\n\n    method elems(Array:D: --> Int:D)\n\nReturns the number of elements in the invocant. Throws L<C<X::Cannot::Lazy>|/type/X::Cannot::Lazy>\nexception if the invocant L<is lazy|/routine/is-lazy>. For shaped arrays,\nreturns the outer dimension; see L<shape|/routine/shape> if you need information for\nall dimensions.\n\n    say [<foo bar ber>] .elems; # OUTPUT: «3␤»\n    say (my @a[42;3;70]).elems; # OUTPUT: «42␤»\n\n    try [-∞...∞].elems;\n    say $!.^name;               # OUTPUT: «X::Cannot::Lazy␤»\n\n=head2 method clone\n\n    method clone(Array:D: --> Array:D)\n\nClones the original C<Array>. Modifications of elements in the clone\nare not propagated to the original and vice-versa:\n\n    my @a = <a b c>; my @b = @a.clone;\n    @b[1] = 42; @a.push: 72;\n    say @b; # OUTPUT: «[a 42 c]␤»\n    say @a; # OUTPUT: «[a b c 72]␤»\n\nHowever, note that the reifier I<is> shared between the two Arrays,\nso both Arrays will have the same elements even when each is randomly-generated\non reification and each element will be reified just once, regardless of\nwhether the reification was done by the clone or the original Array.\nB<Note:> just as reifying an Array from multiple threads is not safe,\nso is, for example, reifying the clone from one thread while reifying\nthe original from another thread is not safe.\n\n    my @a = 1, {rand} … ∞; my @b = @a.clone;\n    say @b[^3]; # OUTPUT: «(1 0.0216426755282736 0.567660896142156)␤»\n    say @a[^3]; # OUTPUT: «(1 0.0216426755282736 0.567660896142156)␤»\n\n=head2 method flat\n\n    multi method flat(Array:U:)\n    multi method flat(Array:D:)\n\nThis method will return the type object itself if it's applied to a type\nobject; when applied to an object, it will return a L<C<Seq>|/type/Seq> created from the\nC<Array> underlying iterator.\n\n=for code\nmy @a = <a 2 c>;\nsay @a.flat.^name; # OUTPUT: «Seq␤»\n\n\n=head2 method shift\n\n    method shift(Array:D:) is nodal\n\nRemoves and returns the first item from the array.  Fails if the array is empty.\n\nExample:\n\n    my @foo = <a b>;\n    say @foo.shift;             # OUTPUT: «a␤»\n    say @foo.shift;             # OUTPUT: «b␤»\n    say @foo.shift;\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Cannot::Empty: Cannot shift from an empty Array␤»\n\n=head2 routine unshift\n\n    multi        unshift(Array:D, **@values --> Array:D)\n    multi method unshift(Array:D: **@values --> Array:D)\n\nAdds the C<@values> to the start of the array, and returns the modified array.\nFails if C<@values> is a lazy list.\n\nExample:\n\n    my @foo = <a b c>;\n    @foo.unshift: 1, 3 ... 11;\n    say @foo;                   # OUTPUT: «[(1 3 5 7 9 11) a b c]␤»\n\nThe notes in L<the documentation for method push|/type/Array#method_push> apply,\nregarding how many elements are added to the array.\n\nThe L<routine prepend|/type/Array#routine_prepend> is the equivalent for adding multiple elements from one\nlist or array.\n\n=head2 routine prepend\n\n    sub prepend(\\array, |values)\n    multi method prepend(Array:D: \\values)\n    multi method prepend(Array:D: **@values is raw)\n\nAdds the elements from C<values> to the front of the array, modifying it\nin-place.\n\nExample:\n\n    my @foo = <a b c>;\n    @foo.prepend: 1, 3 ... 11;\n    say @foo;                   # OUTPUT: «[1 3 5 7 9 11 a b c]␤»\n\nThe difference from method C<unshift> is that if you prepend a B<single> array\nor list argument, C<prepend> will flatten that array / list, whereas C<unshift>\nprepends the list / array as just a single element.\n\n=head2 routine splice\n\n    multi        splice(@list,   $start = 0, $elems?, *@replacement --> Array)\n    multi method splice(Array:D: $start = 0, $elems?, *@replacement --> Array)\n\nDeletes C<$elems> elements starting from index C<$start> from the C<Array>,\nreturns them and replaces them by C<@replacement>. If C<$elems> is omitted or\nis larger than the number of elements starting from C<$start>,\nall the elements starting from index C<$start> are deleted. If both C<$start>\nand C<$elems> are omitted, all elements are deleted from the C<Array> and\nreturned.\n\nEach of C<$start> and C<$elems> can be specified as a\nL<C<Whatever>|/type/Whatever> or as a L<C<Callable>|/type/Callable> that returns an\nL<C<Int>|/type/Int>-compatible value: this returned value is then used as the\ncorresponding argument to the C<splice> routine.\n\nA L<C<Whatever>|/type/Whatever> C<$start> uses the number of elements of C<@list> (or invocant). A\nL<C<Callable>|/type/Callable> C<$start> is called with one argument—the number of elements in\nC<@list> (or C<self>).\n\nA L<C<Whatever>|/type/Whatever> C<$elems> deletes from C<$start> to end of C<@list> (or C<self>)\n(same as no C<$elems>). A L<C<Callable>|/type/Callable> C<$elems> is called with one\nargument—the number of elements in C<@list> (or C<self>) minus the value\nof C<$start>.\n\nExample:\n\n    my @foo = <a b c d e f g>;\n    say @foo.splice(2, 3, <M N O P>);        # OUTPUT: «[c d e]␤»\n    say @foo;                                # OUTPUT: «[a b M N O P f g]␤»\n\nIt can be used to extend an array by simply splicing in more elements than\nthe current size (since version 6.d)\n\n=for code\nmy @foo = <a b c d e f g>;\nsay @foo.splice(6, 4, <M N O P>);       # OUTPUT: «[g]␤»\nsay @foo;                               # OUTPUT: «[a b c d e f M N O P]␤»\n\nThe following equivalences hold (assuming that C«@a.elems ≥ $i»):\n\n=begin code :lang<text>\n@a.push($x, $y)      @a.splice: *  , *, $x, $y\n@a.pop               @a.splice: *-1,\n@a.shift             @a.splice: 0  , 1,\n@a.unshift($x, $y)   @a.splice: 0  , 0, $x, $y\n@a[$i] = $y          @a.splice: $i , 1, $y,\n=end code\n\nAs mentioned above, a L<C«Whatever»|/type/Whatever> or L<C«Callable»|/type/Callable> object can be provided\nfor both the C«$start» and C«$elems» parameters. For example, we could use\neither of them to remove the second to last element from an array provided\nit's large enough to have one:\n\n    my @foo = <a b c d e f g>;\n    say @foo.splice: *-2, *-1;           # OUTPUT: «[f]␤»\n    say @foo;                            # OUTPUT: «[a b c d e g]␤»\n\n    my &start     = -> $n { $n - 2 };\n    my &elems-num = -> $m { $m - 1 };\n    say @foo.splice: &start, &elems-num; # OUTPUT: «[e]␤»\n    say @foo;                            # OUTPUT: «[a b c d g]␤»\n\n=head2 method shape\n\n    method shape() { (*,) }\n\nReturns the shape of the array as a list.\n\nExample:\n\n    my @foo[2;3] = ( < 1 2 3 >, < 4 5 6 > ); # Array with fixed dimensions\n    say @foo.shape;                          # OUTPUT: «(2 3)␤»\n    my @bar = ( < 1 2 3 >, < 4 5 6 > );      # Normal array (of arrays)\n    say @bar.shape;                          # OUTPUT: «(*)␤»\n\n=head2 method default\n\n    method default\n\nReturns the default value of the invocant, i.e. the value which is returned when\ntrying to access an element in the C<Array> which has not been previously\ninitialized or when accessing an element which has explicitly been set to\nL<C<Nil>|/type/Nil>. Unless the C<Array> is declared as having a default value by using the\nL<is default|/type/Variable#trait_is_default> trait the method returns the type object for\nL<C<Any>|/type/Any>.\n\n=begin code\nmy @a1 = 1, \"two\", 2.718;\nsay @a1.default;                               # OUTPUT: «(Any)␤»\nsay @a1[4];                                    # OUTPUT: «(Any)␤»\n\nmy @a2 is default(17) = 1, \"two\", 3;\nsay @a2.default;                               # OUTPUT: «17␤»\nsay @a2[4];                                    # OUTPUT: «17␤»\n@a2[1] = Nil;                                  # (resets element to its default)\nsay @a2[1];                                    # OUTPUT: «17␤»\n=end code\n\n=head2 method of\n\n    method of()\n\nReturns the type constraint for the values of the invocant. By default,\ni.e. if no type constraint is given during declaration, the method\nreturns C<(Mu)>.\n\n    my @a1 = 1, 'two', 3.14159;              # (no type constraint specified)\n    say @a1.of;                              # OUTPUT: «(Mu)␤»\n\n    my Int @a2 = 1, 2, 3;                    # (values must be of type Int)\n    say @a2.of;                              # OUTPUT: «(Int)␤»\n    @a2.push: 'd';\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::TypeCheck::Assignment: Type check failed in assignment to @a2; expected Int but got Str (\"d\")␤»\n\n=head2 method dynamic\n\n    method dynamic(Array:D: --> Bool:D)\n\nReturns C<True> if the invocant has been declared with the L<is dynamic|/routine/is dynamic>\ntrait, that is, if it's a dynamic variable that can be accessed from the\ninner lexical scope without having been declared there.\n\n    my @a;\n    say @a.dynamic;                          # OUTPUT: «False␤»\n\n    my @b is dynamic;\n    say @b.dynamic;                          # OUTPUT: «True␤»\n\nIf you declare a variable with the C<*> twigil C<is dynamic> is implied.\n\n    my @*b;\n    say @*b.dynamic;                         # OUTPUT: «True␤»\n\nPlease note that the C<dynamic> trait is a property of the variable, not the\ncontent. If a L<C<Scalar>|/type/Scalar> dynamic variable contains an array, rules for this\ncontainer will apply (and it will always return C<False>).\n\n=head2 method List\n\n    multi method List(Array:D:)\n\nConverts the array to a L<C<List>|/type/List>.\n\n=for code\nmy @array= [1];\n@array[3]=3;\nsay @array.List;       # OUTPUT: «(1 Nil Nil 3)␤»\n\nThe holes will show up as L<C<Nil>|/type/Nil>.\n\n\n=head2 method Slip\n\n     multi method Slip(Array:D: --> Slip:D)\n\nConverts the array to a L<C<Slip>|/type/Slip>, filling the holes with the type value the\nC<Array> has been defined with.\n\n=for code\nmy Int @array= [0];\n@array[3]=3;\nsay @array.Slip; # OUTPUT: «(0 (Int) (Int) 3)␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Associative.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"composite\")\n\n=TITLE role Associative\n\n=SUBTITLE Object that supports looking up values by key\n\n    role Associative[::TValue = Mu, ::TKey = Str(Any)] { }\n\nA common role for types that support name-based lookup through\nL«postcircumfix:<{ }>|/language/operators#postcircumfix_{_}» such as\nL<C<Hash>|/type/Hash> and L<C<Map>|/type/Map>. It is used for type checks in operators\nthat expect to find specific methods to call. See\nL<Subscripts|/language/subscripts#Methods_to_implement_for_associative_subscripting>\nfor details.\n\nThe C<%> sigil restricts variables to objects that do C<Associative>, so you\nwill have to mix in that role if you want to use it for your classes.\n\n=begin code\nclass Whatever {};\nmy %whatever := Whatever.new;\n# OUTPUT: «Type check failed in binding; expected Associative but got Whatever\n=end code\n\nPlease note that we are using binding C<:=> here, since by default C<%>\nassignments expect a L<C<Hash>|/type/Hash> in the right-hand side, and thus assignment\nwould try and convert it to a hash (also failing). However, with the\nAssociative role:\n\n    class Whatever is Associative {};\n    my %whatever := Whatever.new;\n\nwill be syntactically correct.\n\n=head1 Methods\n\n=head2 method of\n\n    method of()\n\nC<Associative>, as the definition above shows, is actually a\nL<parameterized role|/language/objects#Parameterized_roles>\nwhich can use different classes for keys and values. As seen at the top of the\ndocument, by default it coerces the key to L<C<Str>|/type/Str> and uses a very\ngeneric L<C<Mu>|/type/Mu> for value.\n\n    my %any-hash;\n    say %any-hash.of; # OUTPUT: «(Mu)␤»\n\nThe value is the first parameter you use when instantiating C<Associative> with\nparticular classes:\n\n    class DateHash is Hash does Associative[Cool,DateTime] {};\n    my %date-hash := DateHash.new;\n    say %date-hash.of; # OUTPUT: «(Cool)␤»\n\n=head2 method keyof\n\n    method keyof()\n\nReturns the parameterized key used for the Associative role, which is L<C<Any>|/type/Any>\ncoerced to L<C<Str>|/type/Str> by default. This is the class used as second parameter when\nyou use the parameterized version of Associative.\n\n    my %any-hash;\n    %any-hash.keyof; # OUTPUT: «(Str(Any))␤»\n\n=head1 Methods that classes mixing Associative should provide\n\nYou need to provide these methods if you want your class to implement the\nAssociative role properly and, thus, use the C<{}> operator for accessing the\nvalue given a key. They are not mandatory, however; on the other hand, if you\nsimply want objects of a class to use C<{}>, you can implement them without\nmixing the C<Associative> role.\n\n=head2 method AT-KEY\n\n    method AT-KEY(\\key)\n\nShould return the value / container at the given key.\n\n=for code\nclass What { method AT-KEY(\\key) { 42 }};\nsay What.new{33}; # OUTPUT: «42␤»\n\n=head2 method EXISTS-KEY\n\n    method EXISTS-KEY(\\key)\n\nShould return a L<C<Bool>|/type/Bool> indicating whether the given key actually has a value.\n\n=head2 method STORE\n\n    method STORE(\\values, :$INITIALIZE)\n\nThis method should only be supplied if you want to support the:\n\n=for code :preamble<role Foo {}>\nmy %h is Foo = a => 42, b => 666;\n\nsyntax for binding your implementation of the C<Associative> role.\n\nShould accept the values to (re-)initialize the object with, which either\ncould consist of L<C<Pair>|/type/Pair>s, or separate key/value pairs.  The optional\nnamed parameter will contain a C<True> value when the method is called on\nthe object for the first time.  Should return the invocant.\n\n=head1 See also\n\nSee\nL<Methods to implement for associative subscripting|/language/subscripts#Methods_to_implement_for_associative_subscripting>\nfor information about additional methods that can be implemented for the\nC<Associative> role.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Attribute.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Attribute\n\n=SUBTITLE Member variable\n\n    class Attribute { }\n\nIn Raku lingo, an I<attribute> refers to a per-instance/object storage slot.\nAn C<Attribute> is used to talk about classes' and roles' attributes at the\nmetalevel.\n\nC<Attribute> is typically useful when working with the L<MOP|/language/mop>.\nFor instance, the attributes of any type that supports them can be\nintrospected using the C<attributes> metamethod, which returns a list of\nC<Attribute> instances. Using these, we can inspect various properties of\na type's attributes, such as their names:\n=begin code\nclass WithAttributes {\n    has $.attribute;\n    has $.attribute-two-electric-boogaloo;\n    has $.yet-another-attribute;\n}\n.say for WithAttributes.^attributes(:local).map(*.name);\n# OUTPUT:\n# $!attribute\n# $!attribute-two-electric-boogaloo\n# $!yet-another-attribute\n=end code\n\nBecause of C<Attribute>, a type containing attributes, such as this:\n\n=for code\nclass WithAttribute {\n    has $.attribute;\n}\n\nIs not something only the compiler knows how to generate. This class in\nparticular can be generated manually like so:\n\n=for code :solo\nBEGIN {\n    constant WithAttribute = Metamodel::ClassHOW.new_type: :name<WithAttribute>;\n    WithAttribute.^add_attribute: Attribute.new:\n        :name<$!attribute>, :type(Any), :package(WithAttribute),\n        :1has_accessor;\n    WithAttribute.^compose;\n}\n\n=head1 Traits\n\n=head2 X<trait is default|Traits,is default>\n\nAn attribute that is assigned L<C<Nil>|/type/Nil> will revert to its default value\nset with the trait C<is default>. In the case of arrays or associatives, the\nargument of C<is default> will set the default item value or hash value.\n\n    class C {\n        has $.a is default(42) is rw = 666\n    }\n    my $c = C.new;\n    say $c;\n    $c.a = Nil;\n    say $c;\n    # OUTPUT: «C.new(a => 666)␤C.new(a => 42)␤»\n    class Foo {\n        has @.bar is default(42) is rw\n    };\n    my $foo = Foo.new( bar => <a b c> );\n    $foo.bar =Nil;\n    say $foo; # OUTPUT: «Foo.new(bar => [42])␤»\n\n=head2 X<trait is required|Traits,is required>\n\n    multi trait_mod:<is> (Attribute $attr, :$required!)\n\nThe trait C<is required> will mark the attribute as to be filled with a value\nwhen the object is instantiated. Failing to do so will result in a runtime\nerror.\n\n    class C {\n        has $.a is required\n    }\n    my $c = C.new;\n    CATCH{ default { say .^name, ': ', .Str } }\n    # OUTPUT: «X::Attribute::Required: The attribute '$!a' is required, but you did not provide a value for it.␤»\n\nThis trait also allows attributes to be typed with types that have a\nC<:D> smiley without giving them a default value:\n\n    class Power {\n        has Numeric:D $.base     is required;\n        has Numeric:D $.exponent is required;\n        multi method Numeric(::?CLASS:D: --> Numeric:D) {\n            $!base ** $!exponent\n        }\n    }\n\nB<Available as of 6.d language version> (early implementation exists in Rakudo\ncompiler 2018.08+): You can specify a reason why the attribute is required:\n\n=begin code\nclass D {\n    has $.a is required(\"it is a good idea\");\n}\nmy $d = D.new;\nCATCH{ default { say .^name, ': ', .Str } }\n# OUTPUT: «X::Attribute::Required: The attribute '$!a' is required because it is a good idea,␤but you did not provide a value for it.␤»\n=end code\n\nC<is required> doesn't just affect the default constructor, it checks for the\nattribute at a lower level, so it will work for custom constructors written\nusing L<bless|/routine/bless>.\n\n=head2 X<trait is DEPRECATED|Traits,is DEPRECATED>\n\n    multi trait_mod:<is>(Attribute:D $r, :$DEPRECATED!)\n\nMarks an attribute as deprecated, optionally with a message what to use instead.\n\n    class C {\n        has $.foo is DEPRECATED(\"'bar'\");\n    }\n    my $c = C.new( foo => 42 );  # doesn't trigger with initialization (yet)\n    say $c.foo;                  # does trigger on usage\n\nB<After> the program is finished, this will show something like this on\nSTDERR:\n\n    # Saw 1 occurrence of deprecated code.\n    # =====================================\n    # Method foo (from C) seen at:\n    # script.raku, line 5\n    # Please use 'bar' instead.\n\n=head2 X<trait is rw|Traits,is rw>\n\n    multi trait_mod:<is> (Attribute:D $attr, :$rw!)\n\nMarks an attribute as read/write as opposed to the default C<readonly>.  The\ndefault accessor for the attribute will return a writable value.\n\n   class Boo {\n      has $.bar is rw;\n      has $.baz;\n   };\n\n   my $boo = Boo.new;\n   $boo.bar = 42; # works\n   $boo.baz = 42;\n   CATCH { default { put .^name, ': ', .Str } };\n   # OUTPUT: «X::Assignment::RO: Cannot modify an immutable Any␤»\n\n=head2 X<trait is readonly|Traits,is readonly>\n\n    multi trait_mod:<is> (Attribute:D $attr, :readonly($)!)\n\nMarks as C<readonly> an attribute of a class that has the C<is rw> trait.\n\n    =begin code :skip-test<illustrates error>\n    class Thing is rw {\n        has $.form;\n        has $.matter is readonly;\n    };\n\n    my $t = Thing.new(matter => \"copper\", form => \"cubic\");\n    $t.form = \"round\";   # OK, form is rw\n    $t.matter = \"iron\";  # not OK, matter is readonly\n    # OUTPUT: «Cannot modify an immutable Str (copper)␤...»\n    =end code\n\nThe attributes of classes without the C<is rw> trait are already readonly by default.\nThus, in classes without the C<is rw> trait, the attribute trait C<is readonly> is redundant.\n\n=head2 X<trait is built|Traits,is built>\n\n    multi trait_mod:<is>(Attribute:D $a, :$built!)\n\nBy default, this trait allows setting up a I«private attribute» during\nobject construction via C«.new». The same trait can be used to prevent\nsetting up a I«public attribute» via C«.new» by passing it the Boolean\nvalue C«False». Setting up an attribute with its value is ordinarily\nhandled by assigning the value, but if C<:bind> is passed, then it will\nbe bound instead:\n\n    class Foo {\n        has $!bar is built; # same as `is built(True)`\n        has $.baz is built(False);\n        has $!qux is built(:bind);\n\n        method bar(::?CLASS:D:) { $!bar }\n        method qux(::?CLASS:D:) { $!qux }\n    }\n\n    my Foo:D $foo .= new: :bar[], :baz[], :qux[];\n    say $foo.bar.raku; # OUTPUT: «$[]␤»\n    say $foo.baz.raku; # OUTPUT: «Any␤»\n    say $foo.qux.raku; # OUTPUT: «[]␤»\n\nThe C<built> trait also allows named arguments to be specified.  Currently\nthe C<:bind> named argument can be specified.  In that case, any (default)\nvalue will be B<bound> to the attribute, rather than assigned.  This allows\nfor specifying a L<C<Proxy>|/type/Proxy> to an attribute:\n\n    class Foo {\n        has $!foo is built(:bind) = Proxy.new: :STORE{...}, :FETCH{...}\n    }\n\nAvailable as of the 2020.01 release of the Rakudo compiler.\n\n=head1 Methods\n\n=head2 method new\n\n=begin code :method\nmethod new(\n    Attribute:_:\n    :$name!,\n    :$type!,\n    :$package!,\n    :$inlined = 0,\n    :$has_accessor = 0,\n    :$is_built = $has_accessor,\n    :$is_bound = 0,\n    :$positional_delegate = 0,\n    :$associative_delegate = 0,\n    *%other\n)\n=end code\n\nCreates a new attribute. The following named arguments are required:\n- C<$name> contains the attribute's name, which should always be a\n\n=head2 method name\n\n    method name(Attribute:D: --> Str:D)\n\nReturns the name of the attribute.  Note that this is always the private name,\nso if an attribute is declared as C<has $.a>, the name returned is C<$!a>.\n\n    class Foo {\n        has @!bar;\n    }\n    my $a = Foo.^attributes(:local)[0];\n    say $a.name;            # OUTPUT: «@!bar␤»\n\n=head2 method package\n\n    method package()\n\nReturns the package (class/grammar/role) to which this attribute belongs.\n\n    class Boo {\n        has @!baz;\n    }\n    my $a = Boo.^attributes(:local)[0];\n    say $a.package;         # OUTPUT: «(Boo)␤»\n\n=head2 method has_accessor\n\n    method has_accessor(Attribute:D: --> Bool:D)\n\nReturns C<True> if the attribute has a public accessor method.\n\n    class Container {\n        has $!private;\n        has $.public;\n    }\n    my $private = Container.^attributes(:local)[0];\n    my $public = Container.^attributes(:local)[1];\n    say $private.has_accessor; # OUTPUT: «False␤»\n    say $public.has_accessor;  # OUTPUT: «True␤»\n\n=head2 method rw\n\n    method rw(Attribute:D: --> Bool:D)\n\nReturns C<True> for attributes that have the \"is rw\" trait applied to them.\n\n    class Library {\n        has $.address; # Read-only value\n        has @.new-books is rw;\n    }\n    my $addr = Library.^attributes(:local)[0];\n    my $new-books = Library.^attributes(:local)[1];\n    say $addr.rw;      # OUTPUT: «False␤»\n    say $new-books.rw; # OUTPUT: «True␤»\n\n=head2 method readonly\n\n    method readonly(Attribute:D: --> Bool:D)\n\nReturns C<True> for readonly attributes, which is the default, or C<False> for\nattributes marked as C<is rw>.\n\n    class Library {\n        has $.address; # Read-only value\n        has @.new-books is rw;\n    }\n    my $addr = Library.^attributes(:local)[0];\n    my $new-books = Library.^attributes(:local)[1];\n    say $addr.readonly;      # OUTPUT: «True␤»\n    say $new-books.readonly; # OUTPUT: «False␤»\n\n=head2 method required\n\n    method required(Attribute:D: --> Any:D)\n\nReturns C<1> for attributes that have the \"is required\" trait applied, or L<C<Mu>|/type/Mu>\nif the attribute did not have that trait applied.  If the \"is required\" trait\nis applied with a string, then that string will be returned instead of C<1>.\n\n    class Library {\n        has $.address is required;\n        has @.new-books is required(\"we always need more books\");\n    }\n    my $addr = Library.^attributes(:local)[0];\n    my $new-books = Library.^attributes(:local)[1];\n    say $addr.required;      # OUTPUT: «1␤»\n    say $new-books.readonly; # OUTPUT: «\"we always need more books\"␤»\n\n=head2 method type\n\n    method type(Attribute:D: --> Mu)\n\nReturns the type constraint of the attribute.\n\n    class TypeHouse {\n        has Int @.array;\n        has $!scalar;\n        has @.mystery;\n    }\n    my @types = TypeHouse.^attributes(:local)[0..2];\n    for 0..2 { say @types[$_].type }\n    # OUTPUT: «(Positional[Int])\n    # (Mu)\n    # (Positional)␤»\n\n=head2 method get_value\n\n    method get_value(Mu $obj)\n\nReturns the value stored in this attribute of object C<$obj>.\n\n    class Violated {\n        has $!private-thing = 5;\n    }\n    my $private = Violated.^attributes(:local)[0];\n    say $private.get_value(Violated.new); # OUTPUT: «5␤»\n\nNote that this method violates encapsulation of the object, and should be\nused with care.\n\n=head2 method set_value\n\n    method set_value(Mu $obj, Mu \\new_val)\n\nBinds the value C<new_val> to this attribute of object C<$obj>.\n\n    class A {\n        has $!a = 5;\n        method speak() { say $!a; }\n    }\n    my $attr = A.^attributes(:local)[0];\n    my $a = A.new;\n    $a.speak; # OUTPUT: «5␤»\n    $attr.set_value($a, 42);\n    $a.speak; # OUTPUT: «42␤»\n\nNote that this method violates encapsulation of the object, and should be\nused with care.  Here be dragons.\n\n=head2 method gist\n\n    multi method gist(Attribute:D:)\n\nReturns the name of the type followed by the name of the attribute.\n\n=for code\nclass Hero {\n    has @!inventory;\n    has Str $.name;\n    submethod BUILD( :$name, :@inventory ) {\n        $!name = $name;\n        @!inventory = @inventory\n    }\n}\nsay Hero.^attributes(:local)[0]; # OUTPUT: «Positional @!inventory␤»\n\nSince say implicitly calls C<.gist>, that is what produces the output here.\n\n=head2 method is_built\n\n    method is_built()\n\nReturns C<True> if the attribute had the L<C<is built>|#trait_is_built>\ntrait applied to it, otherwise returns C<False>.\n\n=head2 method is_bound\n\n    method is_bound()\n\nReturns C<True> if the attribute had the L<C<is built>|#trait_is_built>\ntrait applied to it with C<:bind> as an argument, otherwise returns\nC<False>.\n\n=head1 Optional introspection\n\n=head2 DEPRECATED\n\nIf an attribute is marked as C<DEPRECATED>, then calling the C<DEPRECATED>\nmethod is possible and will return C<\"something else\"> (if no specific reason\nwas specified) or the string that was specified with the C<DEPRECATED> trait.\n\nIf an attribute is B<not> marked as DEPRECATED, one B<cannot> call the\nC<DEPRECATED> method.  Therefore, the C<.?method> syntax should be used.\n\n    class Hangout {\n        has $.table;\n        has $.bar is DEPRECATED(\"the patio\");\n    }\n    my $attr-table = Hangout.^attributes(:local)[0];\n    my $attr-bar = Hangout.^attributes(:local)[1];\n    with $attr-table.?DEPRECATED -> $text {     # does not trigger\n        say \"Table is deprecated with '$text'\";\n        # OUTPUT:\n    }\n    with $attr-bar.?DEPRECATED -> $text {\n        say \"Bar is deprecated with '$text'\";\n        # OUTPUT: «Bar is deprecated with 'the patio'\"␤»\n    }\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Backtrace/Frame.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class Backtrace::Frame\n\n=SUBTITLE Single frame of a Backtrace\n\n    class Backtrace::Frame { }\n\nA single backtrace frame. It identifies a location in the source code.\n\n=head1 Methods\n\n=head2 method file\n\n    method file(Backtrace::Frame:D --> Str)\n\nReturns the file name.\n\n    my $bt = Backtrace.new;\n    my $btf = $bt[0];\n    say $btf.file;\n\n=head2 method line\n\n    method line(Backtrace::Frame:D --> Int)\n\nReturns the line number (line numbers start counting from 1).\n\n    my $bt = Backtrace.new;\n    my $btf = $bt[0];\n    say $btf.line;\n\n=head2 method code\n\n    method code(Backtrace::Frame:D)\n\nReturns the code object into which C<.file> and C<.line> point, if available.\n\n    my $bt = Backtrace.new;\n    my $btf = $bt[0];\n    say $btf.code;\n\n=head2 method subname\n\n    method subname(Backtrace::Frame:D --> Str)\n\nReturns the name of the enclosing subroutine.\n\n    my $bt = Backtrace.new;\n    my $btf = $bt[0];\n    say $btf.subname;\n\n=head2 method is-hidden\n\n    method is-hidden(Backtrace::Frame:D: --> Bool:D)\n\nReturns C<True> if the frame is marked as hidden with the\nC<is hidden-from-backtrace> trait.\n\n    my $bt = Backtrace.new;\n    my $btf = $bt[0];\n    say $btf.is-hidden;\n\n=head2 method is-routine\n\n    method is-routine(Backtrace::Frame:D: --> Bool:D)\n\nReturn C<True> if the frame points into a routine (and not\ninto a mere L<C<Block>|/type/Block>).\n\n    my $bt = Backtrace.new;\n    my $btf = $bt[0];\n    say $btf.is-routine;\n\n=head2 method is-setting\n\n    method is-setting(Backtrace::Frame:D: --> Bool:D)\n\nReturns C<True> if the frame is part of a setting.\n\n    my $bt = Backtrace.new;\n    my $btf = $bt[0];\n    say $btf.is-setting; # OUTPUT: «True␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Backtrace.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class Backtrace\n\n=SUBTITLE Snapshot of the dynamic call stack\n\n    class Backtrace {}\n\nA backtrace contains the dynamic call stack, usually leading up to a point where\nan exception was thrown, and is a List of L<C<Backtrace::Frame>|/type/Backtrace::Frame> objects.  Its\ndefault stringification excludes backtrace frames that are deemed unnecessary or\nconfusing; for example routines like C<&die> are hidden by default. Being a\nlist, you can also access individual elements.\n\n=for code\nsub zipi { { { die \"Something bad happened\" }() }() };\ntry {\n    zipi;\n}\nif ($!) {\n    say $!.backtrace[*-1].raku;\n}\n\nThis will print the last frame in the list, pointing at the line where it's\nhappened.\n\n=head1 Methods\n\n=head2 method new\n\n    multi method new()\n    multi method new(Int:D $offset)\n    multi method new(Mu \\ex)\n    multi method new(Mu \\ex, Int:D $offset)\n    multi method new(List:D $bt)\n    multi method new(List:D $bt, Int:D $offset)\n\nCreates a new backtrace, using its calling location as the origin of the\nbacktrace or the C<$offset> that is passed as a parameter. If an object or a\nlist (that will already contain a backtrace in list form) is passed, they will\nbe used instead of the current code.\n\n    my $backtrace = Backtrace.new;\n\n=head2 method gist\n\n    multi method gist(Backtrace:D:)\n\nReturns string C<\"Backtrace(42 frames)\"> where the number indicates the number\nof frames available via L<list|/routine/list> method.\n\n=head2 method Str\n\n    multi method Str(Backtrace:D:)\n\nReturns a concise string representation of the backtrace, omitting\nroutines marked as C<is hidden-from-backtrace>, and at the discretion of\nthe implementation, also some routines from the setting.\n\n    my $backtrace = Backtrace.new;\n    say $backtrace.Str;\n\n=head2 method next-interesting-index\n\n    method next-interesting-index(Backtrace:D: Int $idx = 0, :$named, :$noproto, :$setting)\n\nReturns the index of the next C<interesting> frame, once hidden and other\nsettings are taken into account. C<$named> will decide whether to printed only\nthose with a name, C<$noproto> will hide C<proto>s, and C<$setting> will hide\nthose are considered setting.\n\n=for code\nsub zipi { { { die \"Something bad happened\" }() }() };\ntry zipi;\nsay $!.backtrace.next-interesting-index;           # OUTPUT: «2␤»\nsay $!.backtrace.next-interesting-index( :named ); #  OUTPUT: «4␤»\n\n=head2  method outer-caller-idx\n\n     method outer-caller-idx(Backtrace:D: Int $startidx)\n\nReturns as a list the index of the frames that called the current one.\n\n=for code\nsub zipi { { { die \"Something bad happened\" }() }() };\ntry zipi;\nsay $!.backtrace.outer-caller-idx( 4 ); # OUTPUT: «[6]␤»\n\n=head2 method nice\n\n    method nice(Backtrace:D: :$oneline)\n\nReturns the backtrace as a list of I<interesting> frames. If C<:$oneline> is\nset, will stop after the first frame.\n\n=for code\nsub zipi { { { die \"Something bad happened\" }() }() };\ntry zipi;\nsay $!.backtrace.nice( :oneline ) if $!;\n# OUTPUT: «  in sub zipi at /tmp/... line 1␤␤»\n\n\n=head2 method full\n\n    multi method full(Backtrace:D:)\n\nReturns a full string representation of the backtrace, including hidden\nframes, compiler-specific frames, and those from the setting.\n\n    my $backtrace = Backtrace.new;\n    say $backtrace.full;\n\n=head2 method list\n\n    multi method list(Backtrace:D:)\n\nReturns a list of L<C<Backtrace::Frame>|/type/Backtrace::Frame> objects for this backtrace.\n\n=head2 method summary\n\n    method summary(Backtrace:D: --> Str:D)\n\nReturns a summary string representation of the backtrace, filtered\nby C<!.is-hidden && (.is-routine || !.is-setting)>.\n\nThis program:\n\n    sub inner { say Backtrace.new.summary }\n    sub outer { inner; }\n    outer;\n\nresults in:\n\n=for code :lang<text>\nin method new at SETTING::src/core.c/Backtrace.rakumod line 85\nin sub inner at test.raku line 1\nin sub outer at test.raku line 2\nin block <unit> at test.raku line 3\n\n\n=head2 method concise\n\n    method concise(Backtrace:D:)\n\nReturns a concise string representation of the backtrace, filtered\nby C<!.is-hidden && .is-routine && !.is-setting>.\n\nThis program:\n\n    sub inner { say Backtrace.new.concise }\n    sub outer { inner; }\n    outer;\n\nresults in:\n\n=for code :lang<text>\nin sub inner at test.raku line 1\nin sub outer at test.raku line 2\n\n=head2 method map\n\n    multi method map(Backtrace:D: &block --> Seq:D)\n\nIt invokes C<&block> for each element and gathers the return values in a sequence and returns it.\n\nThis program:\n\n    sub inner { Backtrace.new.map({ say \"{$_.file}: {$_.line}\" }); }\n    sub outer { inner; }\n    outer;\n\nresults in:\n\n=for code :lang<text>\nSETTING::src/core.c/Backtrace.rakumod: 85\nSETTING::src/core.c/Backtrace.rakumod: 85\ntest.raku: 1\ntest.raku: 2\ntest.raku: 3\ntest.raku: 1\n\n=head2 method flat\n\n    multi method flat(Backtrace:D:)\n\nReturns the backtrace same as L<list|#method_list>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Bag.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class Bag\n\n=SUBTITLE Immutable collection of distinct objects with integer weights\n\n    class Bag does Baggy { }\n\nA C<Bag> is an immutable bag/multiset implementing\nL<C<Associative>|/type/Associative>, meaning a collection of distinct\nelements in no particular order that each have an integer weight\nassigned to them signifying how many copies of that element are\nconsidered \"in the bag\".  (For I<mutable> bags, see L<C<BagHash>|/type/BagHash> instead.)\n\nC<Bag>s are often used for performing weighted random selections - see\nL<.pick|/routine/pick> and L<.roll|/routine/roll>.\n\nObjects/values of any type are allowed as bag elements.  Within a\nC<Bag>, items that would compare positively with the L<===|/routine/===> operator are\nconsidered the same element, with the number of how many there are as\nits weight.  But you can also easily get back the expanded\nlist of items (without the order):\n\n=begin code\nmy $breakfast = bag <spam eggs spam spam bacon spam>;\n\nsay $breakfast.elems;      # OUTPUT: «3␤»\nsay $breakfast.keys.sort;  # OUTPUT: «bacon eggs spam␤»\n\nsay $breakfast.total;      # OUTPUT: «6␤»\nsay $breakfast.kxxv.sort;  # OUTPUT: «bacon eggs spam spam spam spam␤»\n=end code\n\nC<Bag>s can be treated as object hashes using the\nL«C<{ }> postcircumfix operator|/language/operators#postcircumfix_{_}»,\nor the\nL«C«< >» postcircumfix operator|/language/operators#postcircumfix_<_>»\nfor literal string keys, which\nreturns the corresponding integer weight for keys that are elements of\nthe bag, and C<0> for keys that aren't:\n\n    my $breakfast = bag <spam eggs spam spam bacon spam>;\n    say $breakfast<bacon>;    # OUTPUT: «1␤»\n    say $breakfast<spam>;     # OUTPUT: «4␤»\n    say $breakfast<sausage>;  # OUTPUT: «0␤»\n\n=head1 Creating C<Bag> objects\n\nC<Bag>s can be composed using the L<bag|#sub bag> subroutine (or\nC<Bag.new>, for which it is a shorthand).  Any positional parameters,\nregardless of their type, become elements of the bag:\n\n    my $n = bag \"a\" => 0, \"b\" => 1, \"c\" => 2, \"c\" => 2;\n    say $n.keys.raku;        # OUTPUT: «(:c(2), :b(1), :a(0)).Seq␤»\n    say $n.keys.map(&WHAT);  # OUTPUT: «((Pair) (Pair) (Pair))␤»\n    say $n.values.raku;      # OUTPUT: «(2, 1, 1).Seq␤»\n\nAlternatively, the C<.Bag> coercer (or its functional form, C<Bag()>)\ncan be called on an existing object to coerce it to a C<Bag>.  Its\nsemantics depend on the type and contents of the object.  In general it\nevaluates the object in list context and creates a bag with the\nresulting items as elements, although for Hash-like objects or Pair\nitems, only the keys become elements of the bag, and the (cumulative)\nvalues become the associated integer weights:\n\n    my $n = (\"a\" => 0, \"b\" => 1, \"c\" => 2, \"c\" => 2).Bag;\n    say $n.keys.raku;        # OUTPUT: «(\"b\", \"c\").Seq␤»\n    say $n.keys.map(&WHAT);  # OUTPUT: «((Str) (Str))␤»\n    say $n.values.raku;      # OUTPUT: «(1, 4).Seq␤»\n\nFurthermore, you can get a C<Bag> by using bag operators (see next\nsection) on objects of other types such as L<C<List>|/type/List>, which will\nact like they internally call C<.Bag> on them before performing the operation.\nBe aware of the tight precedence of those operators though, which may\nrequire you to use parentheses around arguments:\n\n    say (1..5) (+) 4;  # OUTPUT: «Bag(1 2 3 4(2) 5)␤»\n\nYou can also create a C<Bag> with the C<.new> method.\n\n    my $breakfast = Bag.new( <spam eggs spam spam bacon spam> );\n\nSince 6.d (2019.03 and later) you can also use this syntax for parameterization\nof the C<Bag>, to specify which type of values are acceptable:\n\n    # only allow strings (Str) in the Bag\n    my $breakfast = Bag[Str].new( <spam eggs spam spam bacon spam> );\n\n    # only allow whole numbers (Int) in the Bag\n    my $breakfast = Bag[Int].new( <spam eggs spam spam bacon spam> );\n    # Type check failed in binding; expected Int but got Str (\"spam\")\n\nFinally, you can create Bag masquerading as a hash by using the C<is> trait:\n\n    my %b is Bag = <a b c>;\n    say %b<a>;  # OUTPUT: «True␤»\n    say %b<d>;  # OUTPUT: «False␤»\n\nSince 6.d (2019.03 and later), this syntax also allows you to specify the\ntype of values you would like to allow:\n\n    # limit to strings\n    my %b is Bag[Str] = <a b c>;\n    say %b<a>;  # OUTPUT: «True␤»\n    say %b<d>;  # OUTPUT: «False␤»\n\n    # limit to whole numbers\n    my %b is Bag[Int] = <a b c>;\n    # Type check failed in binding; expected Int but got Str (\"a\")\n\n=head1 Operators\n\nSee L<Operators with set\nsemantics|/language/setbagmix#Operators_with_set_semantics> for a complete\nlist of \"set operators\" applicable to, among other types, C<Bag>.\n\nExamples:\n\n=begin code\nmy ($a, $b) = bag(2, 2, 4), bag(2, 3, 3, 4);\n\nsay $a (<) $b;   # OUTPUT: «False␤»\nsay $a (<=) $b;  # OUTPUT: «False␤»\nsay $a (^) $b;   # OUTPUT: «Bag(3(2) 2)␤»\nsay $a (+) $b;   # OUTPUT: «Bag(2(3) 4(2) 3(2))␤»\n\n# Unicode versions:\nsay $a ⊂ $b;  # OUTPUT: «False␤»\nsay $a ⊆ $b;  # OUTPUT: «False␤»\nsay $a ⊖ $b;  # OUTPUT: «Bag(3(2) 2)␤»\nsay $a ⊎ $b;  # OUTPUT: «Bag(2(3) 4(2) 3(2))␤»\n=end code\n\n=head1 Subroutines\n\n=head2 sub bag\n\n    sub bag(*@args --> Bag)\n\nCreates a new C<Bag> from C<@args>.\n\n=head1 Note on C<reverse> and ordering\n\nThis method is inherited from L<C<Any>|/type/Any#routine_reverse>, however,\nL<C<Mix>|/type/Mix>es do not have an inherent order and you should not trust it\nreturning a consistent output.\n\n=head1 See also\n\nL<Sets, Bags, and Mixes|/language/setbagmix>\n\n=end pod\n"
  },
  {
    "path": "doc/Type/BagHash.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class BagHash\n\n=SUBTITLE Mutable collection of distinct objects with integer weights\n\n    class BagHash does Baggy { }\n\nA C<BagHash> is a mutable bag/multiset, meaning a collection of distinct\nitems in no particular order that each have an integer weight assigned to\nthem signifying how many copies of that element are considered \"in the\nbag\".  If you do not need the mutability that a C<BagHash> provides,\nconsider using the I<immutable> L<C«Bag»|/type/Bag> type instead.\n\nAn item may be a definite object of any type – not just a L<C<Str>|/type/Str>.  For\nexample, you can store L<C«Sub»|/type/Sub>'s in a C<BagHash>, and you\nwill store the actual L<C<Sub>|/type/Sub> rather than a string with the same name\nas the L<C<Sub>|/type/Sub>.  Within a C<BagHash>, items that would compare\npositively with the L<===|/routine/===> operator are considered the\nsame element, with the number of how many there were as its weight.\nAlternatively, you can use the C<kxxv> method to easily get back the\nexpanded list of items (without the order):\n\n=begin code\nmy $breakfast = <spam eggs spam spam bacon spam>.BagHash;\n\nsay $breakfast.elems;      # OUTPUT: «3␤»\nsay $breakfast.keys.sort;  # OUTPUT: «bacon eggs spam␤»\n\nsay $breakfast.total;      # OUTPUT: «6␤»\nsay $breakfast.kxxv.sort;  # OUTPUT: «bacon eggs spam spam spam spam␤»\n=end code\n\nC<BagHash>es can be treated as object hashes using the L«C<{ }>\npostcircumfix operator|/language/operators#postcircumfix_{_}», or the\nL«C«< >» postcircumfix operator|/language/operators#postcircumfix_<_>»\nfor literal string keys, which returns the corresponding integer weight\nfor keys that are elements of the bag, and C<0> for keys that aren't.  These\noperators can also be used to modify weights (see\nL<Updating BagHash Objects|#Updating_BagHash_Objects>, below).\n\n=begin code\nmy $breakfast = <spam eggs spam spam bacon spam>.BagHash;\nsay $breakfast<bacon>;     # OUTPUT: «1␤»\nsay $breakfast<spam>;      # OUTPUT: «4␤»\nsay $breakfast<sausage>;   # OUTPUT: «0␤»\n\n$breakfast<sausage> = 2;\n$breakfast<bacon>--;\nsay $breakfast.kxxv.sort;  # OUTPUT: «eggs sausage sausage spam spam spam spam␤»\n=end code\n\n=head1 Creating C<BagHash> objects\n\nC<BagHash>es can be composed using C<BagHash.new>.  Any positional parameters,\nregardless of their type, become elements of the bag:\n\n    my $n = BagHash.new: \"a\", \"b\", \"c\", \"c\";\n    say $n.raku;             # OUTPUT: «(\"b\"=>1,\"a\"=>1,\"c\"=>2).BagHash␤»\n    say $n.keys.raku;        # OUTPUT: «(\"b\", \"a\", \"c\").Seq␤»\n    say $n.values.raku;      # OUTPUT: «(1, 1, 2).Seq␤»\n\nBesides, C<BagHash.new-from-pairs> can create a C<BagHash> with items and their\noccurrences.\n\n    my $n = BagHash.new-from-pairs: \"a\" => 0, \"b\" => 1, \"c\" => 2, \"c\" => 2;\n    say $n.raku;             # OUTPUT: «(\"b\"=>1,\"c\"=>4).BagHash␤»\n    say $n.keys.raku;        # OUTPUT: «(\"b\", \"c\").Seq␤»\n    say $n.values.raku;      # OUTPUT: «(1, 4).Seq␤»\n\nAlternatively, the C<.BagHash> coercer (or its functional form, C<BagHash()>)\ncan be called on an existing object to coerce it to a C<BagHash>.  Its semantics\ndepend on the type and contents of the object.  In general it evaluates the\nobject in list context and creates a bag with the resulting items as elements,\nalthough for Hash-like objects or Pair items, only the keys become elements of\nthe bag, and the (cumulative) values become the associated integer weights:\n\n    my $m = (\"a\", \"b\", \"c\", \"c\").BagHash;\n    my $n = (\"a\" => 0, \"b\" => 1, \"c\" => 2, \"c\" => 2).BagHash;\n    say $m.raku;             # OUTPUT: «(\"b\"=>1,\"a\"=>1,\"c\"=>2).BagHash␤»\n    say $n.raku;             # OUTPUT: «(\"b\"=>1,\"c\"=>4).BagHash␤»\n\nYou can also create C<BagHash> masquerading as a hash by using the C<is> trait:\n\n    my %bh is BagHash = <a b b c c c>;\n    say %bh<b>;  # OUTPUT: «2␤»\n    say %bh<d>;  # OUTPUT: «0␤»\n\nSince 6.d (2019.03 and later) it is also possible to specify the type of values\nyou would like to allow in a C<BagHash>.  This can either be done when calling\nC<.new>:\n\n    # only allow strings\n    my $n = BagHash[Str].new: <a b b c c c>;\n\nor using the masquerading syntax:\n\n    # only allow strings\n    my %bh is BagHash[Str] = <a b b c c c>;\n    say %bh<b>;  # OUTPUT: «2␤»\n    say %bh<d>;  # OUTPUT: «0␤»\n\n    # only allow whole numbers\n    my %bh is BagHash[Int] = <a b b c c c>;\n    # Type check failed in binding; expected Int but got Str (\"a\")\n\n=head1 Updating BagHash Objects\n\nOnce you have created a C<BagHash>, you can update its values in two\nways.  First, you can use the C<add> and C<remove> methods:\n\n    my $n = BagHash.new: \"a\", \"b\", \"c\", \"c\";\n    say $n.raku;             # OUTPUT: «(\"b\"=>1,\"a\"=>1,\"c\"=>2).BagHash␤»\n    $n.add('c');\n    say $n.raku;             # OUTPUT: «(\"b\"=>1,\"c\"=>3,\"a\"=>1).BagHash␤»\n    $n.remove(('b', 'a'),);\n    say $n.raku;             # OUTPUT: «(\"c\"=>3).BagHash␤»\n    $n.remove('c');\n    say $n.raku;             # OUTPUT: «(\"c\"=>2).BagHash␤»\n\nNote that, as shown in the final example, the C<remove> method removes\na I<single> value from the C<BagHash>; it doesn't entirely remove the\nkey from the C<BagHash>.\n\nAlternatively, you can use assignment (including with L<autoincrement\noperators|/language/operators#Autoincrement_precedence> such as C<++>\nand C<-->) to modify the C<BagHash>'s contents.\n\n    my $n = BagHash.new: \"a\", \"b\", \"c\", \"c\";\n    say $n.raku;             # OUTPUT: «(\"b\"=>1,\"a\"=>1,\"c\"=>2).BagHash␤»\n    $n<c>++;\n    say $n.raku;             # OUTPUT: «(\"b\"=>1,\"c\"=>3,\"a\"=>1).BagHash␤»\n    $n<b> -= 1;\n    say $n.raku;             # OUTPUT: «(\"a\"=>1,\"c\"=>3).BagHash␤»\n    $n{'a'} = 0;\n    say $n.raku;             # OUTPUT: «(\"c\"=>3).BagHash␤»\n\nUsing either syntax, if you set the value of an item to zero or less\nthan zero, the item will be removed from the C<BagHash>.\n\n=head1 Operators\n\nSee L<Operators with set\nsemantics|/language/setbagmix#Operators_with_set_semantics> for a complete\nlist of \"set operators\" applicable to, among other types, C<BagHash>.\n\nExamples:\n\n=begin code\nmy ($a, $b) = BagHash.new(2, 2, 4), BagHash.new(2, 3, 3, 4);\n\nsay $a (<) $b;   # OUTPUT: «False␤»\nsay $a (<=) $b;  # OUTPUT: «False␤»\nsay $a (^) $b;   # OUTPUT: «BagHash(3(2) 2)␤»\nsay $a (+) $b;   # OUTPUT: «BagHash(2(3) 4(2) 3(2))␤»\n\n# Unicode versions:\nsay $a ⊂ $b;  # OUTPUT: «False␤»\nsay $a ⊆ $b;  # OUTPUT: «False␤»\nsay $a ⊖ $b;  # OUTPUT: «BagHash(3(2) 2)␤»\nsay $a ⊎ $b;  # OUTPUT: «BagHash(2(3) 4(2) 3(2))␤»\n=end code\n\n=head1 Note on C<reverse> and ordering.\n\nBagHash inherits C<reverse> from L<Any|/type/Any#routine_reverse>,\nhowever, L<C<Bag>|/type/Bag>s do not have an inherent order and you should not trust\nit returning a consistent output.\n\nIf you sort a BagHash, the result is a list of pairs, at which point\nC<reverse> makes perfect sense:\n\n=begin code\nmy $a = BagHash.new(2, 2, 18, 3, 4);\nsay $a;  # OUTPUT: «BagHash(18 2(2) 3 4)␤»\n\nsay $a.sort;  # OUTPUT: «(2 => 2 3 => 1 4 => 1 18 => 1)␤»\nsay $a.sort.reverse;  # OUTPUT: «(18 => 1 4 => 1 3 => 1 2 => 2)␤»\n=end code\n\n=head2 method add\n\n    method add(BagHash: \\to-add, *%_ --> Nil)\n\nWhen C<to-add> is a single item, C<add> inserts it into the C<BagHash>\nor, if it was already present, increases its weight by 1.  When\nC<to-add> is a L<C<List>|/type/List>, L<C<Array>|/type/Array>, L<C<Seq>|/type/Seq>, or any other type that\nC<does> the L<C«Iterator»|/type/Iterator> Role, C<add> inserts each\nelement of the L<C<Iterator>|/type/Iterator> into the L<C<SetHash>|/type/SetHash> or increments the\nweight of each element by 1.\n\nI<Note:> Added in release 2020.02.\n\n=head2 method remove\n\n    method remove(BagHash: \\to-remove, *%_ --> Nil)\n\nWhen C<to-remove> is a single item, C<remove> reduces the weight of\nthat item by one.  If this results in the item having a weight of 0,\nthis removes the item from the C<BagHash>.  If the item is not present\nin the C<BagHash>, C<remove> has no effect.  When C<to-remove> is a\nL<C<List>|/type/List>, L<C<Array>|/type/Array>, L<C<Seq>|/type/Seq>, or any other type that C<does> the\nL<C«Iterator»|/type/Iterator> Role, C<remove> reduces the weight of\neach element by 1 and removes any items with the resulting weight of\n0.\n\nI<Note:> Added in release 2020.02.\n\n=head1 See Also\n\nL<Sets, Bags, and Mixes|/language/setbagmix>\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Baggy.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"composite\")\n\n=TITLE role Baggy\n\n=SUBTITLE Collection of distinct weighted objects\n\n    role Baggy does QuantHash { }\n\nA role for collections of weighted objects.  See L<C<Bag>|/type/Bag>, L<C<BagHash>|/type/BagHash>, and\nL<C<Mixy>|/type/Mixy>.\n\n=head1 Methods\n\n=head2 method new-from-pairs\n\n    method new-from-pairs(Baggy: *@pairs --> Baggy:D)\n\nConstructs a Baggy objects from a list of L«C<Pair>|/type/Pair» objects\ngiven as positional arguments:\n\n    say Mix.new-from-pairs: 'butter' => 0.22, 'sugar' => 0.1, 'sugar' => 0.02;\n    # OUTPUT: «Mix(butter(0.22) sugar(0.12))␤»\n\nB<Note:> be sure you aren't accidentally passing the Pairs as positional arguments;\nthe quotes around the keys in the above example are significant.\n\n=head2 method grab\n\n    multi method grab(Baggy:D: --> Any)\n    multi method grab(Baggy:D: $count --> Seq:D)\n\nLike L<pick|#method pick>, a C<grab> returns a random selection of elements, weighted\nby the values corresponding to each key. Unlike C<pick>, it works only on mutable\nstructures, e.g. L<C<BagHash>|/type/BagHash>. Use of C<grab> on an immutable structure results in an\nL<C<X::Immutable>|/type/X::Immutable> exception. If C<*> is passed as C<$count>, or C<$count> is greater than\nor equal to the L<total|#method total> of the invocant, then C<total> elements from the\ninvocant are returned in a random sequence; i.e. they are returned shuffled.\n\nGrabbing decrements the grabbed key's weight by one (deleting the key\nwhen it reaches 0). By definition, the C<total> of the invocant also decreases by one, so the\nprobabilities stay consistent through subsequent C<grab> operations.\n\n    my $cars = ('Ford' => 2, 'Rover' => 3).BagHash;\n    say $cars.grab;                                   # OUTPUT: «Ford␤»\n    say $cars.grab(2);                                # OUTPUT: «(Rover Rover)␤»\n    say $cars.grab(*);                                # OUTPUT: «(Rover Ford)␤»\n\n    my $breakfast = ('eggs' => 2, 'bacon' => 3).Bag;\n    say $breakfast.grab;\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Immutable: Cannot call 'grab' on an immutable 'Bag'␤»\n\n=head2 method grabpairs\n\n    multi method grabpairs(Baggy:D: --> Any)\n    multi method grabpairs(Baggy:D: $count --> Seq:D)\n\nReturns a L<C<Pair>|/type/Pair> or a L<C<Seq>|/type/Seq> of L<C<Pair>|/type/Pair>s depending on the version of the method\nbeing invoked. Each L<C<Pair>|/type/Pair> returned has an element of the invocant as its key and the\nelement's weight as its value. Unlike L<pickpairs|/routine/pickpairs>, it works only on mutable structures,\ne.g. L<C<BagHash>|/type/BagHash>. Use of C<grabpairs> on an immutable structure results in\nan C<X::Immutable> exception. If C<*> is passed as C<$count>, or C<$count> is greater\nthan or equal to the number of L<elements|#method elems> of the invocant, then all\nelement/weight L<C<Pair>|/type/Pair>s from the invocant are returned in a random sequence.\n\nWhat makes C<grabpairs> different from L<pickpairs|#method pickpairs> is that the\n'grabbed' elements are in fact removed from the invocant.\n\n    my $breakfast = (eggs => 2, bacon => 3).BagHash;\n    say $breakfast.grabpairs;                         # OUTPUT: «bacon => 3␤»\n    say $breakfast;                                   # OUTPUT: «BagHash.new(eggs(2))␤»\n    say $breakfast.grabpairs(1);                      # OUTPUT: «(eggs => 2)␤»\n    say $breakfast.grabpairs(*);                      # OUTPUT: «()␤»\n\n    my $diet = ('eggs' => 2, 'bacon' => 3).Bag;\n    say $diet.grabpairs;\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Immutable: Cannot call 'grabpairs' on an immutable 'Bag'␤»\n\n=head2 method pick\n\n    multi method pick(Baggy:D: --> Any)\n    multi method pick(Baggy:D: $count --> Seq:D)\n\nLike an ordinary list L<pick|/type/List#routine_pick>, but returns keys\nof the invocant weighted by their values, as if the keys were replicated\nthe number of times indicated by the corresponding value and then list\npick used. The underlying metaphor for picking is that you're pulling\ncolored marbles out a bag. (For \"picking with replacement\" see\nL<roll|#method roll> instead). If C<*> is passed as C<$count>, or C<$count> is\ngreater than or equal to the L<total|#method total> of the invocant, then\nC<total> elements from the invocant are returned in a random sequence.\n\nNote that each C<pick> invocation maintains its own private state and has\nno effect on subsequent C<pick> invocations.\n\n    my $breakfast = bag <eggs bacon bacon bacon>;\n    say $breakfast.pick;                              # OUTPUT: «eggs␤»\n    say $breakfast.pick(2);                           # OUTPUT: «(eggs bacon)␤»\n\n    say $breakfast.total;                             # OUTPUT: «4␤»\n    say $breakfast.pick(*);                           # OUTPUT: «(bacon bacon bacon eggs)␤»\n\n=head2 method pickpairs\n\n    multi method pickpairs(Baggy:D: --> Pair:D)\n    multi method pickpairs(Baggy:D: $count --> Seq:D)\n\nReturns a L<C<Pair>|/type/Pair> or a L<C<Seq>|/type/Seq> of L<C<Pair>|/type/Pair>s depending on the version of the method\nbeing invoked. Each L<C<Pair>|/type/Pair> returned has an element of the invocant as its key and the\nelement's weight as its value. The elements are 'picked' without replacement. If C<*>\nis passed as C<$count>, or C<$count> is greater than or equal to the number of\nL<elements|#method elems> of the invocant, then all element/weight L<C<Pair>|/type/Pair>s from\nthe invocant are returned in a random sequence.\n\nNote that each C<pickpairs> invocation maintains its own private state and has\nno effect on subsequent C<pickpairs> invocations.\n\n    my $breakfast = bag <eggs bacon bacon bacon>;\n    say $breakfast.pickpairs;                         # OUTPUT: «eggs => 1␤»\n    say $breakfast.pickpairs(1);                      # OUTPUT: «(bacon => 3)␤»\n    say $breakfast.pickpairs(*);                      # OUTPUT: «(eggs => 1 bacon => 3)␤»\n\n=head2 method roll\n\n    multi method roll(Baggy:D: --> Any:D)\n    multi method roll(Baggy:D: $count --> Seq:D)\n\nLike an ordinary list L<roll|/type/List#routine_roll>, but returns keys of the invocant weighted\nby their values, as if the keys were replicated the number of times indicated\nby the corresponding value and then list roll used. The underlying\nmetaphor for rolling is that you're throwing C<$count> dice that are\nindependent of each other, which (in bag terms) is equivalent to picking\na colored marble out your bag and then putting it back, and doing this\nC<$count> times. In dice terms, the number of marbles corresponds to the\nnumber of sides, and the number of marbles of the same color corresponds\nto the number of sides with the same color. (For \"picking without replacement\"\nsee L<pick|#method pick> instead).\n\nIf C<*> is passed to C<$count>, returns a lazy, infinite sequence of randomly\nchosen elements from the invocant.\n\n    my $breakfast = bag <eggs bacon bacon bacon>;\n    say $breakfast.roll;                                  # OUTPUT: «bacon␤»\n    say $breakfast.roll(3);                               # OUTPUT: «(bacon eggs bacon)␤»\n\n    my $random_dishes := $breakfast.roll(*);\n    say $random_dishes[^5];                               # OUTPUT: «(bacon eggs bacon bacon bacon)␤»\n\n=head2 method pairs\n\n    method pairs(Baggy:D: --> Seq:D)\n\nReturns all elements and their respective weights as a L<C<Seq>|/type/Seq> of L<C<Pair>|/type/Pair>s\nwhere the key is the element itself and the value is the weight of that element.\n\n    my $breakfast = bag <bacon eggs bacon>;\n    my $seq = $breakfast.pairs;\n    say $seq.sort;                                    # OUTPUT: «(bacon => 2 eggs => 1)␤»\n\n=head2 method antipairs\n\n    method antipairs(Baggy:D: --> Seq:D)\n\nReturns all elements and their respective weights as a L<C<Seq>|/type/Seq> of L<C<Pair>|/type/Pair>s,\nwhere the element itself is the value and the weight of that element is the key, i.e.\nthe opposite of method L<pairs|#method pairs>.\n\n    my $breakfast = bag <bacon eggs bacon>;\n    my $seq = $breakfast.antipairs;\n    say $seq.sort;                                    # OUTPUT: «(1 => eggs 2 => bacon)␤»\n\n=head2 method invert\n\n    method invert(Baggy:D: --> Seq:D)\n\nReturns all elements and their respective weights as a L<C<Seq>|/type/Seq> of\nL<C<Pair>|/type/Pair>s, where the element itself is the value and the weight of\nthat element is the key, i.e. the opposite of method L<pairs|#method pairs>.\nExcept for some esoteric cases, C<invert> on a Baggy type returns the same\nresult as L<antipairs|#method_antipairs>.\n\n    my $breakfast = bag <bacon eggs bacon>;\n    my $seq = $breakfast.invert;\n    say $seq.sort;                                    # OUTPUT: «(1 => eggs 2 => bacon)␤»\n\n=head2 method classify-list\n\n    multi method classify-list(&mapper, *@list --> Baggy:D)\n    multi method classify-list(%mapper, *@list --> Baggy:D)\n    multi method classify-list(@mapper, *@list --> Baggy:D)\n\nPopulates a I<mutable> C<Baggy> by classifying the\npossibly-empty C<@list> of values using the given C<mapper>. The C<@list>\ncannot be lazy.\n\n    say BagHash.new.classify-list: { $_ %% 2 ?? 'even' !! 'odd' }, ^10;\n    # OUTPUT: BagHash(even(5) odd(5))\n\n    my @mapper = <zero one two three four five>;\n    say MixHash.new.classify-list: @mapper, 1, 2, 3, 4, 4, 6;\n    # OUTPUT: MixHash((Any) two three four(2) one)\n\nThe mapper can be a L«C<Callable>|/type/Callable» that takes a single argument,\nan L«C<Associative>|/type/Associative», or an L«C<Iterable>|/type/Iterable».\nWith L«C<Associative>|/type/Associative» and an L«C<Iterable>|/type/Iterable»\nmappers, the values in the C<@list> represent the key and index of the mapper's\nvalue respectively. A L«C<Callable>|/type/Callable» mapper will be executed\nonce per each item in the C<@list>, with that item as the argument and its\nreturn value will be used as the mapper's value.\n\nThe mapper's value is used as the key of the C<Baggy> that will\nbe incremented by C<1>. See L«C<.categorize-list>|/routine/categorize-list» if\nyou wish to classify an item into multiple categories at once.\n\nB<Note:> unlike the L«C<Hash>|/type/Hash»'s\nC<.classify-list>, returning an L«C<Iterable>|/type/Iterable» mapper's value\nwill throw, as C<Baggy> types do not support nested\nclassification. For the same reason, C<Baggy>'s C<.classify-list>\ndoes not accept C<:&as> parameter.\n\n=head2 method categorize-list\n\n    multi method categorize-list(&mapper, *@list --> Baggy:D)\n    multi method categorize-list(%mapper, *@list --> Baggy:D)\n    multi method categorize-list(@mapper, *@list --> Baggy:D)\n\nPopulates a I<mutable> C<Baggy> by categorizing the\npossibly-empty C<@list> of values using the given C<mapper>. The C<@list>\ncannot be lazy.\n\n    say BagHash.new.categorize-list: {\n        gather {\n            take 'largish' if $_ > 5;\n            take .is-prime ?? 'prime' !! 'non-prime';\n            take $_ %% 2   ?? 'even'  !! 'odd';\n        }\n    }, ^10;\n    # OUTPUT: BagHash(largish(4) even(5) non-prime(6) prime(4) odd(5))\n\n    my %mapper = :sugar<sweet white>, :lemon<sour>, :cake('sweet', 'is-a-lie');\n    say MixHash.new.categorize-list: %mapper, <sugar lemon cake>;\n    # OUTPUT: MixHash(is-a-lie sour white sweet(2))\n\nThe mapper can be a L«C<Callable>|/type/Callable» that takes a single argument,\nan L«C<Associative>|/type/Associative», or an L«C<Iterable>|/type/Iterable».\nWith L«C<Associative>|/type/Associative» and an L«C<Iterable>|/type/Iterable»\nmappers, the values in the C<@list> represent the key and index of the mapper's\nvalue respectively. A L«C<Callable>|/type/Callable» mapper will be executed\nonce per each item in the C<@list>, with that item as the argument and its\nreturn value will be used as the mapper's value.\n\nThe mapper's value is used as a possibly-empty list of keys of the\nC<Baggy> that will be incremented by C<1>.\n\nB<Note:> unlike the L«C<Hash>|/type/Hash»'s\nC<.categorize-list>, returning a list of L«C<Iterables>|/type/Iterable»\nas mapper's value will throw, as C<Baggy> types do not support\nnested categorization. For the same reason, C<Baggy>'s\nC<.categorize-list> does not accept C<:&as> parameter.\n\n=head2 method keys\n\n    method keys(Baggy:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> of all keys in the C<Baggy> object without taking\ntheir individual weights into account as opposed to L<kxxv|#method kxxv>.\n\n    my $breakfast = bag <eggs spam spam spam>;\n    say $breakfast.keys.sort;                        # OUTPUT: «(eggs spam)␤»\n\n    my $n = (\"a\" => 5, \"b\" => 2).BagHash;\n    say $n.keys.sort;                                # OUTPUT: «(a b)␤»\n\n=head2 method values\n\n    method values(Baggy:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> of all values, i.e. weights, in the C<Baggy> object.\n\n    my $breakfast = bag <eggs spam spam spam>;\n    say $breakfast.values.sort;                      # OUTPUT: «(1 3)␤»\n\n    my $n = (\"a\" => 5, \"b\" => 2, \"a\" => 1).BagHash;\n    say $n.values.sort;                              # OUTPUT: «(2 6)␤»\n\n=head2 method kv\n\n    method kv(Baggy:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> of keys and values interleaved.\n\n    my $breakfast = bag <eggs spam spam spam>;\n    say $breakfast.kv;                                # OUTPUT: «(spam 3 eggs 1)␤»\n\n    my $n = (\"a\" => 5, \"b\" => 2, \"a\" => 1).BagHash;\n    say $n.kv;                                        # OUTPUT: «(a 6 b 2)␤»\n\n=head2 method kxxv\n\n    method kxxv(Baggy:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> of the keys of the invocant, with each key multiplied by its\nweight. Note that C<kxxv> only works for C<Baggy> types which have integer\nweights, i.e. L<C<Bag>|/type/Bag> and L<C<BagHash>|/type/BagHash>.\n\n    my $breakfast = bag <spam eggs spam spam bacon>;\n    say $breakfast.kxxv.sort;                         # OUTPUT: «(bacon eggs spam spam spam)␤»\n\n    my $n = (\"a\" => 0, \"b\" => 1, \"b\" => 2).BagHash;\n    say $n.kxxv;                                      # OUTPUT: «(b b b)␤»\n\n=head2 method elems\n\n    method elems(Baggy:D: --> Int:D)\n\nReturns the number of elements in the C<Baggy> object without\ntaking the individual elements' weight into account.\n\n    my $breakfast = bag <eggs spam spam spam>;\n    say $breakfast.elems;                             # OUTPUT: «2␤»\n\n    my $n = (\"b\" => 9.4, \"b\" => 2).MixHash;\n    say $n.elems;                                     # OUTPUT: «1␤»\n\n=head2 method total\n\n    method total(Baggy:D:)\n\nReturns the sum of weights for all elements in the C<Baggy>\nobject.\n\n    my $breakfast = bag <eggs spam spam bacon>;\n    say $breakfast.total;                             # OUTPUT: «4␤»\n\n    my $n = (\"a\" => 5, \"b\" => 1, \"b\" => 2).BagHash;\n    say $n.total;                                     # OUTPUT: «8␤»\n\n=head2 method default\n\n    method default(Baggy:D: --> 0)\n\nReturns zero.\n\n    my $breakfast = bag <eggs bacon>;\n    say $breakfast.default;                           # OUTPUT: «0␤»\n\n=head2 method hash\n\n    method hash(Baggy:D: --> Hash:D)\n\nReturns a L<C<Hash>|/type/Hash> where the elements of the invocant\nare the keys and their respective weights the values.\n\n    my $breakfast = bag <eggs bacon bacon>;\n    my $h = $breakfast.hash;\n    say $h.^name;                    # OUTPUT: «Hash[Any,Any]␤»\n    say $h;                          # OUTPUT: «{bacon => 2, eggs => 1}␤»\n\n=head2 method Bool\n\n    method Bool(Baggy:D: --> Bool:D)\n\nReturns C<True> if the invocant contains at least one element.\n\n    my $breakfast = ('eggs' => 1).BagHash;\n    say $breakfast.Bool;                              # OUTPUT: «True␤»\n                                                      # (since we have one element)\n    $breakfast<eggs> = 0;                             # weight == 0 will lead to element removal\n    say $breakfast.Bool;                              # OUTPUT: «False␤»\n\n=head2 method Set\n\n    method Set(--> Set:D)\n\nReturns a L<C<Set>|/type/Set> whose elements are the L<keys|#method keys> of the invocant.\n\n    my $breakfast = (eggs => 2, bacon => 3).BagHash;\n    say $breakfast.Set;                               # OUTPUT: «Set(bacon eggs)␤»\n\n=head2 method SetHash\n\n    method SetHash(--> SetHash:D)\n\nReturns a L<C<SetHash>|/type/SetHash> whose elements are the L<keys|#method keys> of the invocant.\n\n    my $breakfast = (eggs => 2, bacon => 3).BagHash;\n    my $sh = $breakfast.SetHash;\n    say $sh.^name;                            # OUTPUT: «SetHash␤»\n    say $sh.elems;                            # OUTPUT: «2␤»\n\n=head2 method ACCEPTS\n\n    method ACCEPTS($other --> Bool:D)\n\nUsed in smartmatching if the right-hand side is a C<Baggy>.\n\nIf the right-hand side is the type object, i.e. C<Baggy>, the method\nreturns C<True> if C<$other> L<does|/type/Mu#routine_does> C<Baggy>\notherwise C<False> is returned.\n\nIf the right-hand side is a C<Baggy> object, C<True> is returned only if\nC<$other> has the same elements, with the same weights, as the invocant.\n\n    my $breakfast = bag <eggs bacon>;\n    say $breakfast ~~ Baggy;                            # OUTPUT: «True␤»\n    say $breakfast.does(Baggy);                         # OUTPUT: «True␤»\n\n    my $second-breakfast = (eggs => 1, bacon => 1).Mix;\n    say $breakfast ~~ $second-breakfast;                # OUTPUT: «True␤»\n\n    my $third-breakfast = (eggs => 1, bacon => 2).Bag;\n    say $second-breakfast ~~ $third-breakfast;          # OUTPUT: «False␤»\n\n=head1 See Also\n\nL<Sets, Bags, and Mixes|/language/setbagmix>\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Blob.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"composite\")\n\n=TITLE role Blob\n\n=SUBTITLE Immutable buffer for binary data ('Binary Large OBject')\n\n    role Blob[::T = uint8] does Positional[T] does Stringy { }\n\nThe C<Blob> role is an immutable interface to binary types, and offers a\nlist-like interface to lists of integers, typically unsigned integers.\n\nHowever, it's a parameterized type, and you can instantiate with several\ninteger types:\n\n=for code\nmy $b = Blob[int32].new(3, -3, 0xff32, -44);\nsay $b; # OUTPUT: «Blob[int32]:0x<03 -3 FF32 -2C>␤»\n\nBy default, C<Blob> uses 8-bit unsigned integers, that is, it is\nequivalent to Blob[uint8]. Some other types of C<Blob>s which are used\noften get their own class name.\n\nX<|Types,blob8>X<|Types,blob16>X<|Types,blob32>X<|Types,blob64>\n=begin table\nblob8 | Blob[uint8]\nblob16 | Blob[uint16]\nblob32 | Blob[uint32]\nblob64 | Blob[uint64]\n=end table\n\nYou can use these in pretty much the same way you would with C<Blob>:\n\n    my $blob = blob8.new(3, 6, 254);\n    say $blob; # OUTPUT: «Blob[uint8]:0x<03 06 FE>␤»\n\n=head1 Methods\n\n=head2 method new\n\n    multi method new(Blob:)\n    multi method new(Blob: Blob:D $blob)\n    multi method new(Blob: int @values)\n    multi method new(Blob: @values)\n    multi method new(Blob: *@values)\n\n\nCreates an empty C<Blob>, or a new C<Blob> from another C<Blob>, or from a list\nof integers or values (which will have to be coerced into integers):\n\n    my $blob = Blob.new([1, 2, 3]);\n    say Blob.new(<1 2 3>); # OUTPUT: «Blob:0x<01 02 03>␤»\n\n=head2 method Bool\n\n    multi method Bool(Blob:D:)\n\nReturns C<False> if and only if the buffer is empty.\n\n    my $blob = Blob.new();\n    say $blob.Bool; # OUTPUT: «False␤»\n    $blob = Blob.new([1, 2, 3]);\n    say $blob.Bool; # OUTPUT: «True␤»\n\n=head2 method Capture\n\n    method Capture(Blob:D:)\n\nConverts the object to a L<C<List>|/type/List> which is, in turn, coerced to a L<C<Capture>|/type/Capture>.\n\n=head2 method elems\n\n    multi method elems(Blob:D:)\n\nReturns the number of elements of the buffer.\n\n    my $blob = Blob.new([1, 2, 3]);\n    say $blob.elems; # OUTPUT: «3␤»\n\n=head2 method bytes\n\n    method bytes(Blob:D: --> Int:D)\n\nReturns the number of bytes used by the elements in the buffer.\n\n    say Blob.new([1, 2, 3]).bytes;      # OUTPUT: «3␤»\n    say blob16.new([1, 2, 3]).bytes;    # OUTPUT: «6␤»\n    say blob64.new([1, 2, 3]).bytes;    # OUTPUT: «24␤»\n\n=head2 method chars\n\n    method chars(Blob:D:)\n\nThrows L<C<X::Buf::AsStr>|/type/X::Buf::AsStr> with C<chars> as payload.\n\n=head2 method Str\n\n    multi method Str(Blob:D:)\n\nThrows L<C<X::Buf::AsStr>|/type/X::Buf::AsStr> with L<C<Str>|/type/Str> as payload. In order to convert to a L<C<Str>|/type/Str>\nyou need to use L<C<.decode>|/routine/decode>.\n\n=head2 method Stringy\n\n    multi method Stringy(Blob:D:)\n\nThrows L<C<X::Buf::AsStr>|/type/X::Buf::AsStr> with L<C<Stringy>|/type/Stringy> as payload.\n\n=head2 method decode\n\n    multi method decode(Blob:D: $encoding = self.encoding // \"utf-8\")\n\n=for code :method\nmulti method decode(Blob:D: $encoding, Str :$replacement!,\n                    Bool:D :$strict = False)\n\n    multi method decode(Blob:D: $encoding, Bool:D :$strict = False)\n\nApplies an encoding to turn the blob into a L<C<Str>|/type/Str>; the encoding will\nbe UTF-8 by default.\n\n    my Blob $blob = \"string\".encode('utf-8');\n    say $blob.decode('utf-8'); # OUTPUT: «string␤»\n\nOn malformed utf-8 C<.decode> will throw X::AdHoc. To handle sloppy utf-8 use\nL«C<utf8-c8>|/language/unicode#UTF8-C8».\n\n=head2 method list\n\n    multi method list(Blob:D:)\n\nReturns a L<C<List>|/type/List> of integers:\n\n    say \"zipi\".encode(\"ascii\").list; # OUTPUT: «(122 105 112 105)␤»\n\n=head2 method gist\n\n    method gist(Blob:D: --> Str:D)\n\nReturns the string containing the \"gist\" of the C<Blob>,\nB<listing up to the first 100> elements, separated by space, appending an\nellipsis if the C<Blob> has more than 100 elements.\n\n    put Blob.new(1, 2, 3).gist; # OUTPUT: «Blob:0x<01 02 03>␤»\n    put Blob.new(1..2000).gist;\n    # OUTPUT:\n    # Blob:0x<01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15\n    # 16 17 18 19 1A 1B 1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B 2C\n    # 2D 2E 2F 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F 40 41 42 43\n    # 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52 53 54 55 56 57 58 59 5A\n    # 5B 5C 5D 5E 5F 60 61 62 63 64 ...>\n\n=head2 method subbuf\n\n    multi method subbuf(Int $from, Int $len = self.elems --> Blob:D)\n    multi method subbuf(Range $range --> Blob:D)\n    multi method subbuf(Blob:D: &From)\n    multi method subbuf(Blob:D: Int:D $From, &End)\n    multi method subbuf(Blob:D: &From, &End)\n    multi method subbuf(Blob:D: \\from, Whatever)\n    multi method subbuf(Blob:D: \\from, Numeric \\length)\n\nExtracts a part of the invocant buffer, starting from the index with\nelements C<$from>, and taking C<$len> elements (or less if the buffer is\nshorter), and creates a new buffer as the result.\n\n    say Blob.new(1..10).subbuf(2, 4);    # OUTPUT: «Blob:0x<03 04 05 06>␤»\n    say Blob.new(1..10).subbuf(*-2);     # OUTPUT: «Blob:0x<09 0a>␤»\n    say Blob.new(1..10).subbuf(*-5,2);   # OUTPUT: «Blob:0x<06 07>␤»\n\nFor convenience, also allows a L<C<Range>|/type/Range> to be specified to indicate which\npart of the invocant buffer you would like:\n\n    say Blob.new(1..10).subbuf(2..5);    # OUTPUT: «Blob:0x<03 04 05 06>␤»\n\n=head2 method allocate\n\n    multi method allocate(Blob:U: Int:D $elements)\n    multi method allocate(Blob:U: Int:D $elements, int $value)\n    multi method allocate(Blob:U: Int:D $elements, Int:D \\value)\n    multi method allocate(Blob:U: Int:D $elements, Mu:D $got)\n    multi method allocate(Blob:U: Int:D $elements, int @values)\n    multi method allocate(Blob:U: Int:D $elements, Blob:D $blob)\n    multi method allocate(Blob:U: Int:D $elements, @values)\n\nReturns a newly created C<Blob> object with the given number of elements.\nOptionally takes a second argument that indicates the pattern with which to fill\nthe C<Blob>: this can be a single (possibly native) integer value, or any\nL<C<Iterable>|/type/Iterable> that generates integer values, including another C<Blob>. The\npattern will be repeated if not enough values are given to fill the entire\nC<Blob>.\n\n    my Blob $b0 = Blob.allocate(10,0);\n    $b0.say; # OUTPUT: «Blob:0x<00 00 00 00 00 00 00 00 00 00>␤»\n\nIf the pattern is a general L<C<Mu>|/type/Mu> value, it will fail.\n\n=head2 routine unpack\n\nThis method is considered B<experimental>, in order to use it you will need to\ndo:\n\n    use experimental :pack;\n\n    multi method unpack(Blob:D: Str:D $template)\n    multi method unpack(Blob:D: @template)\n    multi        unpack(Blob:D \\blob, Str:D $template)\n    multi        unpack(Blob:D \\blob, @template)\n\nExtracts features from the blob according to the template string, and\nreturns them as a list.\n\nThe template string consists of zero or more units that begin with an ASCII\nletter, and are optionally followed by a quantifier.  The quantifier can be\nC<*> (which typically stands for \"use up the rest of the Blob here\"), or a\npositive integer (without a C<+>).\n\nWhitespace between template units is ignored.\n\nExamples of valid templates include C<\"A4 C n*\"> and C<\"A*\">.\n\nThe following letters are recognized:\n\n=begin table\n\n    Letter  Meaning\n    ======  =======\n    A       Extract a string, where each element of the Blob maps to a codepoint\n    a       Same as 'A'\n    C       Extract an element from the blob as an integer\n    H       Extracts a hex string\n    L       Extracts four elements and returns them as a single unsigned integer\n    n       Extracts two elements and combines them in \"network\" (BigEndian) byte order into a single integer\n    N       Extracts four elements and combines them in \"network\" (BigEndian) byte order into a single integer\n    S       Extracts two elements and returns them as a single unsigned integer\n    v       Same as 'S'\n    V       Same as 'L'\n    x       Drop an element from the blob (that is, ignore it)\n    Z       Same as 'A'\n\n=end table\n\nExample:\n\n    use experimental :pack;\n    say Blob.new(1..10).unpack(\"C*\");\n    # OUTPUT: «(1 2 3 4 5 6 7 8 9 10)␤»\n\n=head2 sub pack\n\nThis subroutine is considered B<experimental>,  in order to use it you will need\nto do:\n\n=for code\nuse experimental :pack;\n\n=for code\nmulti pack(Str $template, *@items)\nmulti pack(@template, *@items)\n\nPacks the given items according to the template and returns a buffer\ncontaining the packed bytes.\n\nThe template string consists of zero or more units that begin with an ASCII\nletter, and are optionally followed by a quantifier.  For details, see\nL<unpack|/routine/unpack>.\n\n=head2 method reverse\n\n    method reverse(Blob:D: --> Blob:D)\n\nReturns a Blob with all elements in reversed order.\n\n    say Blob.new([1, 2, 3]).reverse;    # OUTPUT: «Blob:0x<03 02 01>␤»\n    say blob16.new([2]).reverse;        # OUTPUT: «Blob[uint16]:0x<02>␤»\n    say blob32.new([16, 32]).reverse;   # OUTPUT: «Blob[uint32]:0x<20 10>␤»\n\n=head1 Methods on blob8 only (6.d, 2018.12 and later)\n\nThese methods are available on the blob8 (and C<buf8>) types only.  They allow\nlow level access to reading bytes from the underlying data and interpreting\nthem in different ways with regards to type (integer or floating point (num)),\nsize (8, 16, 32, 64 or 128 bits), signed or unsigned (for integer values) and\nendianness (native, little and big endianness).  The returned values are\nalways expanded to a 64 bit native value where possible, and to a (big)\ninteger value if that is not possible.\n\nEndianness must be indicated by using values of the L<C<Endian>|/type/Endian>\nenum as the B<second> parameter to these methods.  If no endianness is\nspecified, C<NativeEndian> will be assumed.  Other values are\nC<LittleEndian> and C<BigEndian>.\n\n=head2 method read-uint8\n\n    method read-uint8(blob8:D: uint $pos, $endian = NativeEndian --> uint)\n\nReturns an unsigned native integer value for the byte at the given position.\nThe C<$endian> parameter has no meaning, but is available for consistency.\n\n=head2 method read-int8\n\n    method read-int8(blob8:D: uint $pos, $endian = NativeEndian --> int)\n\nReturns a native C<int> value for the byte at the given position.\nThe C<$endian> parameter has no meaning, but is available for consistency.\n\n=head2 method read-uint16\n\n    method read-uint16(blob8:D: uint $pos, $endian = NativeEndian --> uint)\n\nReturns a native C<uint> value for the B<two> bytes starting at the\ngiven position.\n\n=head2 method read-int16\n\n    method read-int16(blob8:D: uint $pos, $endian = NativeEndian --> int)\n\nReturns a native C<int> value for the B<two> bytes starting at the given\nposition.\n\n=head2 method read-uint32\n\n    method read-uint32(blob8:D: uint $pos, $endian = NativeEndian --> uint)\n\nReturns a native C<uint> value for the B<four> bytes starting at the\ngiven position.\n\n=head2 method read-int32\n\n    method read-int32(blob8:D: uint $pos, $endian = NativeEndian --> int)\n\nReturns a native C<int> value for the B<four> bytes starting at the given\nposition.\n\n=head2 method read-uint64\n\n    method read-uint64(blob8:D: uint $pos, $endian = NativeEndian --> UInt:D)\n\nReturns an unsigned integer value for the B<eight> bytes starting at the\ngiven position.\n\n=head2 method read-int64\n\n    method read-int64(blob8:D: uint $pos, $endian = NativeEndian --> int)\n\nReturns a native C<int> value for the B<eight> bytes starting at the given\nposition.\n\n=head2 method read-uint128\n\n    method read-uint128(blob8:D: uint $pos, $endian = NativeEndian --> UInt:D)\n\nReturns an unsigned integer value for the B<sixteen> bytes starting at the\ngiven position.\n\n=head2 method read-int128\n\n    method read-int128(blob8:D: uint $pos, $endian = NativeEndian --> Int:D)\n\nReturns an integer value for the B<sixteen> bytes starting at the given\nposition.\n\n=head2 method read-num32\n\n    method read-num32(blob8:D: uint $pos, $endian = NativeEndian --> int)\n\nReturns a native C<num> value for the B<four> bytes starting at the given\nposition.\n\n=head2 method read-num64\n\n    method read-num64(blob8:D: uint $pos, $endian = NativeEndian --> int)\n\nReturns a native C<num> value for the B<eight> bytes starting at the given\nposition.\n\n=head1 Methods on blob8 only (6.d, 2019.03 and later)\n\n=head2 method read-ubits\n\n    method read-ubits(blob8:D: uint $pos, uint $bits --> UInt:D)\n\nReturns an unsigned integer value for the B<bits> from the given B<bit> offset\nand given number of bits.  The endianness of the bits is assumed to be\nC<BigEndian>.\n\n=head2 method read-bits\n\n    method read-bits(blob8:D: uint $pos, uint $bits --> Int:D)\n\nReturns a signed integer value for the B<bits> from the given B<bit> offset\nand given number of bits.  The endianness of the bits is assumed to be\nC<BigEndian>.\n\n=head2 method Buf\n\n    method Buf(Blob:D: --> Buf:D)\n\nAvailable as of the 2021.06 Rakudo compiler release.\n\nCoerces the invocant into a mutable L<C<Buf>|/type/Buf> object.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Block.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Block\n\n=SUBTITLE Code object with its own lexical scope\n\n    class Block is Code { }\n\nA C<Block> is a code object meant for small-scale code reuse.  A block is\ncreated syntactically by a list of statements enclosed in curly braces. The literal for\ncreating an empty block is C<{;}>.\n\nWithout an explicit signature or placeholder arguments, a block has C<$_>\nas a positional argument, which defaults to the outer scope's C<$_>. Thus it\nwill inherit the L<topic|/language/variables#index-entry-topic_variable> if there is any.\n\n    my $block = { uc $_; };\n    say $block.^name;           # OUTPUT: «Block␤»\n    say $block('hello');        # OUTPUT: «HELLO␤»\n    say {;}.signature;          # OUTPUT: «(;; $_? is raw = OUTER::<$_>)␤»\n\nA block can have a L«C<Signature>|/type/Signature» between C«->» or C«<->»\nand the block:\n\n    my $add = -> $a, $b = 2 { $a + $b };\n    say $add(40);               # OUTPUT: «42␤»\n\nIf the signature is introduced with C«<->», then the parameters are marked\nas C<rw> by default:\nX«|Syntax,<->»\n\n    my $swap = <-> $a, $b { ($a, $b) = ($b, $a) };\n    my ($a, $b) = (2, 4);\n    $swap($a, $b);\n    say $a;                     # OUTPUT: «4␤»\n\nBlocks that aren't of type L«C<Routine>|/type/Routine» (which is a subclass of C<Block>) are\ntransparent to L«C<return>|/syntax/return».\n\n    sub f() {\n        say <a b c>.map: { return 42 };\n                       #   ^^^^^^   exits &f, not just the block\n    }\n\nThe last statement is the implicit return value of the block.\n\n    say {1}.(); # OUTPUT: «1␤»\n\nBare blocks are automatically executed in the order they appear:\n\n    say 1;                # OUTPUT: «1␤»\n    {\n        say 2;            # OUTPUT: «2␤»; executed directly, not a Block object\n    }\n    say 3;                # OUTPUT: «3␤»\n\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Bool.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"enum\") :category(\"basic\")\n\n=TITLE enum Bool\n\n=SUBTITLE Logical Boolean\n\n    enum Bool <False True>\n\nX<|Syntax,True>\nX<|Syntax,False>\nX<|Language,Boolean>\nAn enum for Boolean true/false decisions.\n\n=head1 Methods\n\n=head2 method ACCEPTS\n\n   method ACCEPTS(Bool:D: --> Bool:D)\n\nUsed for smartmatch comparison. When the right side is C<True> returns always\nC<True>, when the right side of the match is C<False> returns always C<False>.\nIn particular, C<ACCEPTS> returns always the instance on which it is invoked,\nthat is the right side of a smartmatch. As an example:\n\n=begin code\n\nmy $b = Bool.new( True );\n# when True on the right side returns\n# always True\nTrue  ~~ $b;     # True\nFalse ~~ $b;     # True\n\n$b = Bool.new( False );\n# when False on the right side\n# returns always False\nFalse ~~ $b;     # False\nTrue ~~ $b;      # False\n=end code\n\n\n=head2 routine succ\n\n    method succ(--> Bool:D)\n\nReturns C<True>.\n\n    say True.succ;                                    # OUTPUT: «True␤»\n    say False.succ;                                   # OUTPUT: «True␤»\n\nC<succ> is short for \"successor\"; it returns the next enum value. Bool is a\nspecial enum with only two values, C<False> and C<True>. When sorted, C<False>\ncomes first, so C<True> is its successor. And since C<True> is the \"highest\"\nBool enum value, its own successor is also C<True>.\n\n=head2 routine pred\n\n    method pred(--> Bool:D)\n\nReturns C<False>.\n\n    say True.pred;                                    # OUTPUT: «False␤»\n    say False.pred;                                   # OUTPUT: «False␤»\n\nC<pred> is short for \"predecessor\"; it returns the previous enum value. Bool is\na special enum with only two values, C<False> and C<True>. When sorted, C<False>\ncomes first, so C<False> is the predecessor to C<True>. And since C<False> is\nthe \"lowest\" Bool enum value, its own predecessor is also C<False>.\n\n=head2 routine enums\n\n    method enums(--> Hash:D)\n\nReturns a L<C<Hash>|/type/Hash> of enum-pairs. Works on both the C<Bool> type\nand any key.\n\n    say Bool.enums;                                   # OUTPUT: «{False => 0, True => 1}␤»\n    say False.enums;                                  # OUTPUT: «{False => 0, True => 1}␤»\n\n=head2 routine pick\n\n    multi method pick(Bool:U: --> Bool:D)\n    multi method pick(Bool:U: $count --> Seq:D)\n\nReturns a random pick of C<True> and/or C<False>.\n\nIf it's called without an argument then it returns just one pick:\n\n    say Bool.pick;                                    # OUTPUT: «True␤»\n\nIf it's called with a C<$count> of one then it returns a L<C<Seq>|/type/Seq> with just one pick:\n\n    say Bool.pick(1);                                 # OUTPUT: «(False)␤»\n\nIf C<$count> is C<*> or greater than or equal to two then it returns a L<C<Seq>|/type/Seq>\nwith I<two> elements -- either C<True> then C<False>, or C<False> then C<True>:\n\n    say Bool.pick(*);                                 # OUTPUT: «(False True)␤»\n\n=head2 routine roll\n\n    multi method roll(Bool:U --> Bool:D)\n    multi method roll(Bool:U $count --> Seq:D)\n\nReturns C<True> or C<False> if called without any argument. Otherwise returns\nC<$count> elements chosen at random. Note that each random choice from the\nC<enum> is made independently, like a separate coin toss where each side of the\ncoin represents one of the two values of the C<enum>. If C<*> is passed as\nC<$count> an infinite L<C<Seq>|/type/Seq> of C<Bool>s is returned.\n\n    say Bool.roll;                                    # OUTPUT: «True␤»\n    say Bool.roll(3);                                 # OUTPUT: «(True False False)␤»\n    say Bool.roll(*);                                 # OUTPUT: «(...)␤»\n\n=head2 routine Int\n\n    multi method Int(Bool:D --> Int:D)\n\nReturns the value part of the C<enum> pair.\n\n    say False.Int;                                # OUTPUT: «0␤»\n    say True.Int;                                 # OUTPUT: «1␤»\n\n=head2 routine Numeric\n\n    multi method Numeric(Bool:D --> Int:D)\n\nReturns the value part of the C<enum> pair.\n\n    say False.Numeric;                                # OUTPUT: «0␤»\n    say True.Numeric;                                 # OUTPUT: «1␤»\n\n=head1 Operators\n\n=head2 prefix ?\n\n    multi prefix:<?>(Mu --> Bool:D)\n\nCoerces its argument to C<Bool>.\n\n=head2 prefix so\n\n    multi prefix:<so>(Mu --> Bool:D)\n\nCoerces its argument to C<Bool>, has looser precedence than C«prefix:<?>».\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Buf.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"composite\")\n\n=TITLE role Buf\n\n=SUBTITLE Mutable buffer for binary data\n\n    role Buf[::T = uint8] does Blob[T] is repr('VMArray') is array_type(T){ ... }\n\nA C<Buf> does the role of a mutable sequence of (usually unsigned) integers.\n\n    my $bú = Buf.new(1, 2, 3);\n    $bú[1] = 42;\n    say $bú.raku; # OUTPUT: «Buf.new(1,42,3)␤»\n\nHowever, it's a parameterized type, and you can instantiate with several\ninteger types:\n\n    my $bú = Buf[int32].new(3, -3, 0xff32, -44);\n    say $bú; # OUTPUT: «Buf[int32]:0x<03 -3 FF32 -2C>␤»\n\nBy default, C<Buf> uses 8-bit unsigned integers, that is, it is\nequivalent to Buf[uint8]. Some other types of C<Buf>s which are used\noften get their own class name.\n\nX<|Types,buf8>X<|Types,buf16>X<|Types,buf32>X<|Types,buf64>\n=begin table\nbuf8 | Buf[uint8]\nbuf16 | Buf[uint16]\nbuf32 | Buf[uint32]\nbuf64 | Buf[uint64]\n=end table\n\nYou can use these the same way you would with C<Buf>:\n\n    my $bú = buf8.new(3, 6, 254);\n    say $bú; # OUTPUT: «Buf[uint8]:0x<03 06 fe>␤»\n\nThere are some methods on other objects, e.g.\nL<C<encode>|/type/Str#method_encode> that might return a C<buf8> in some\ncases where it is the best representation for a particular encoding.\n\n=head1 Methods\n\n=head2 method subbuf-rw\n\n    method subbuf-rw($from = 0, $elems = self.elems - $from) is rw\n\nA mutable version of C<subbuf> that returns a L<C<Proxy>|/type/Proxy>\nfunctioning as a writable reference to a part of a buffer. Its first\nargument, C<$from> specifies the index in the buffer from which a\nsubstitution should occur, and its last argument, C<$elems> specifies\nhow many elements are to be replaced.\n\nFor example, to replace one element at index 3 with two elements, C<100>\nand C<101>:\n\n    my Buf $bú .= new(0..5);\n    $bú.subbuf-rw(3,1) = Buf.new(100, 101);\n    say $bú.raku;   # OUTPUT: «Buf.new(0,1,2,100,101,4,5)␤»\n\nIn the case the C<$elems> argument is not specified, the substitution\nhappens at the specified index C<$from> removing all trailing elements:\n\n    my Buf $bú .= new(0..5);\n    $bú.subbuf-rw(3) = Buf.new(200);\n    say $bú.raku;   # OUTPUT: «Buf.new(0,1,2,200)␤»\n\nIn the case the C<$from> argument is not specified, the substitution\nhappens from the very beginning of the buffer:\n\n    my Buf $bú .= new(0..5);\n    $bú.subbuf-rw = Buf.new(123, 123);\n    say $bú.raku;   # OUTPUT: «Buf.new(123, 123)␤»\n\n=head2 routine subbuf-rw\n\n    multi subbuf-rw(Buf:D \\b) is rw\n    multi subbuf-rw(Buf:D \\b, Int() $from) is rw\n    multi subbuf-rw(Buf:D \\b, $from, $elems) is rw\n\nReturns a writable reference to a part of a buffer.\nInvokes the C<subbuf-rw> method on the specified C<Buf>:\n\n    my Buf $bú .= new(1,2,3);\n    subbuf-rw($bú,2,1) = Buf.new(42);\n    say $bú.raku;   # OUTPUT: «Buf.new(1,2,42)␤»\n\n=head2 method reallocate\n\n    method reallocate(Buf:D: Int:D $elems)\n\nChange the number of elements of the C<Buf>, returning the changed\nC<Buf>. The size of C<Buf> will be adapted depending on the number of\nC<$elems> specified: if it is smaller than the actual size of the C<Buf>\nthe resulting C<Buf> will be shrunk down, otherwise it will be enlarged\nto fit the number of C<$elems>. In the case the C<Buf> is enlarged,\nnewly created items will be assigned a Virtual Machine specific null\nvalue, therefore you should not rely upon their value since it could be\ninconsistent across different virtual machines.\n\n    my Buf $bú .= new(^10);\n    $bú.reallocate(5);\n    say $bú.raku;  # OUTPUT: «Buf.new(0,1,2,3,4)␤»\n\n    $bú = Buf.new( 1..3 );\n    $bú.reallocate( 10 );\n    say $bú.raku; # OUTPUT: «Buf.new(1,2,3,0,0,0,0,0,0,0)␤»\n\n=head2 method list\n\n    multi method list(Buf:D:)\n\nReturns a L<C<List>|/type/List> of integers.\n\n    say Buf.new(122,105,112,205).list; # OUTPUT: «(122 105 112 205)␤»\n\n=head2 method push\n\n    method push( $elems )\n\nAdds elements at the end of the buffer.\n\n     my $bú = Buf.new( 1, 1, 2, 3, 5 );\n     $bú.push( 8 );\n     say $bú.raku; # OUTPUT: «Buf.new(1,1,2,3,5,8)␤»\n\n=head2 method pop\n\n    method pop()\n\nReturns and removes the last element of the buffer.\n\n     my $bú = Buf.new( 1, 1, 2, 3, 5 );\n     say $bú.pop(); # OUTPUT: «5␤»\n     say $bú.raku;  # OUTPUT: «Buf.new(1,1,2,3)␤»\n\n=head2 method append\n\n    method append( $elems )\n\nAppends to the end of the buffer.\n\n     my $bú = Buf.new( 1, 1, 2, 3, 5 );\n     $bú.append(9, 8, 7, 6);\n     say $bú.raku; # OUTPUT: «Buf.new(1,1,2,3,5,9,8,7,6)␤»\n\n=head2 method prepend\n\n    method prepend( $elems )\n\nInserts elements at the beginning of the buffer.\n\n    my $bú = Buf.new( 1, 1, 2, 3, 5 );\n    $bú.prepend( 0 );\n    say $bú.raku; # OUTPUT: «Buf.new(0,1,1,2,3,5)␤»\n\n=for comment\nDuplicated from Array.prepend\n\nThe difference from method C<unshift> is that if you prepend a B<single> array\nor list argument, C<prepend> will flatten that array / list, whereas C<unshift>\nprepends the list / array as just a single element.\n\n=head2 method shift\n\n    method shift()\n\nRemoves and returns the first element of the buffer.\n\n    my $bú = Buf.new( 1, 1, 2, 3, 5 );\n    say $bú.shift(); # OUTPUT: «1␤»\n    say $bú.raku;    # OUTPUT: «Buf.new(1,2,3,5)␤»\n\n=head2 method unshift\n\n    method unshift()\n\nInserts elements at the beginning of the buffer.\n\n    my $bú = Buf.new( 1, 1, 2, 3, 5 );\n    $bú.unshift( 0 );\n    say $bú.raku; # OUTPUT: «Buf.new(0,1,1,2,3,5)␤»\n\n=head2 method splice\n\n    method splice( Buf:D: $start = 0, $elems?, *@replacement --> Buf)\n\nSubstitutes elements of the buffer by other elements, returning a buffer\nwith the removed elements.\n\n    my $bú = Buf.new( 1, 1, 2, 3, 5 );\n    say $bú.splice:  0, 3, <3 2 1>;  # OUTPUT: «Buf:0x<01 01 02>␤»\n    say $bú.raku;                    # OUTPUT: «Buf.new(3,2,1,3,5)␤»\n\n=head1 Methods on buf8 only (6.d, 2018.12 and later)\n\nThese methods are available on the C<buf8> type only.  They allow low level\naccess to writing bytes to the underlying data and in different ways with\nregards to type (integer or floating point (num)), size (8, 16, 32, 64 or 128\nbits), signed or unsigned (for integer values) and endianness (native, little\nand big endianness).  These methods always return L<C<Nil>|/type/Nil>.\n\nEndianness must be indicated by using values of the L<C<Endian>|/type/Endian>\nenum as the B<third> parameter to these methods.  If no endianness is\nspecified, C<NativeEndian> will be assumed.  Other values are\nC<LittleEndian> and C<BigEndian>.\n\nThe buffer will be automatically resized to support any bytes being written\nif it is not large enough yet.\n\n=head2 method write-uint8\n\n    method write-uint8(buf8:D: uint $pos, uint8 $value, $endian = NativeEndian --> Nil)\n\nWrites an unsigned 8-bit integer value at the given position.  The C<$endian>\nparameter has no meaning, but is available for consistency.\n\n=head2 method write-int8\n\n    method write-int8(buf8:D: uint $pos, int8 $value, $endian = NativeEndian --> Nil)\n\nWrites a signed 8-bit integer value at the given position.  The C<$endian>\nparameter has no meaning, but is available for consistency.\n\n=head2 method write-uint16\n\n    method write-uint16(buf8:D: uint $pos, uint16 $value, $endian = NativeEndian --> Nil)\n\nWrites an unsigned 16-bit integer value at the given position with the given\nendianness.\n\n=head2 method write-int16\n\n    method write-int16(buf8:D: uint $pos, int16 $value, $endian = NativeEndian --> Nil)\n\nWrites a signed 16-bit integer value at the given position with the given\nendianness.\n\n=head2 method write-uint32\n\n    method write-uint32(buf8:D: uint $pos, uint32 $value, $endian = NativeEndian --> Nil)\n\nWrites an unsigned 32-bit integer value at the given position with the given\nendianness.\n\n=head2 method write-int32\n\n    method write-int32(buf8:D: uint $pos, int32 $value, $endian = NativeEndian --> Nil)\n\nWrites a signed 32-bit integer value at the given position with the given\nendianness.\n\n=head2 method write-uint64\n\n    method write-uint64(buf8:D: uint $pos, uint64 $value, $endian = NativeEndian --> Nil)\n\nWrites an unsigned 64-bit integer value at the given position with the given\nendianness.\n\n=head2 method write-int64\n\n    method write-int64(buf8:D: uint $pos, Int:D $value, $endian = NativeEndian --> Nil)\n\nWrites a signed 64-bit integer value at the given position with the given\nendianness.\n\n=head2 method write-uint128\n\n    method write-uint128(buf8:D: uint $pos, UInt:D $value, $endian = NativeEndian --> Nil)\n\nWrites an unsigned 128-bit integer value at the given position with the given\nendianness.\n\n=head2 method write-int128\n\n    method write-int128(buf8:D: uint $pos, Int:D $value, $endian = NativeEndian --> Nil)\n\nWrites a signed 128-bit integer value at the given position with the given\nendianness.\n\n=head2 method write-num32\n\n    method write-num32(buf8:D: uint $pos, num32 $value, $endian = NativeEndian --> Nil)\n\nWrites a native C<num32> IEEE floating point value at the given position with\nthe given endianness.\n\n=head2 method write-num64\n\n    method write-num64(buf8:D: uint $pos, num64 $value, $endian = NativeEndian --> Nil)\n\nWrites a native C<num64> IEEE floating point value at the given position with\nthe given endianness.\n\n=head1 Methods on buf8 only (6.d, 2019.03 and later)\n\n=head2 method write-ubits\n\n    method write-ubits(buf8:D: uint $pos, uint $bits, UInt:D $value --> Nil)\n\nWrites an unsigned integer value to the B<bits> from the given B<bit> offset\nand given number of bits.  The endianness of the bits is assumed to be\nC<BigEndian>.  Always returns Nil.\n\n=head2 method write-bits\n\n    method write-bits(buf8:D: uint $pos, uint $bits, Int:D $value --> Nil)\n\nWrites a signed integer value for the B<bits> from the given B<bit> offset\nand given number of bits.  The endianness of the bits is assumed to be\nC<BigEndian>.  Always returns Nil.\n\n=head1 Methods on buf8 only (6.d, 2019.10 and later)\n\nThese methods are available on the C<buf8> type only.  They allow low level\naccess to writing bytes to the underlying data and in different ways with\nregards to type (integer or floating point (num)), size (8, 16, 32, 64 or 128\nbits), signed or unsigned (for integer values) and endianness (native, little\nand big endianness).\n\nThese methods can also be called on the C<buf8> type object, in which case\na new C<buf8> object will be returned.  Otherwise, the invocant will be\nreturned to allow for easier chaining of operations on the C<buf8> object.\nThe buffer will be automatically resized to support any bytes being written\nif it is not large enough yet.\n\nEndianness must be indicated by using values of the L<C<Endian>|/type/Endian>\nenum as the B<third> parameter to these methods.  If no endianness is\nspecified, C<NativeEndian> will be assumed.  Other values are\nC<LittleEndian> and C<BigEndian>.\n\n=head2 method write-uint8\n\n    method write-uint8(buf8: uint $pos, uint8 $value, $endian = NativeEndian --> buf8:D)\n\nWrites an unsigned 8-bit integer value at the given position.  The C<$endian>\nparameter has no meaning, but is available for consistency.\n\n=head2 method write-int8\n\n    method write-int8(buf8: uint $pos, int8 $value, $endian = NativeEndian --> buf8:D)\n\nWrites a signed 8-bit integer value at the given position.  The C<$endian>\nparameter has no meaning, but is available for consistency.\n\n=head2 method write-uint16\n\n    method write-uint16(buf8: uint $pos, uint16 $value, $endian = NativeEndian --> buf8:D)\n\nWrites an unsigned 16-bit integer value at the given position with the given\nendianness.\n\n=head2 method write-int16\n\n    method write-int16(buf8: uint $pos, int16 $value, $endian = NativeEndian --> buf8:D)\n\nWrites a signed 16-bit integer value at the given position with the given\nendianness.\n\n=head2 method write-uint32\n\n    method write-uint32(buf8: uint $pos, uint32 $value, $endian = NativeEndian --> buf8:D)\n\nWrites an unsigned 32-bit integer value at the given position with the given\nendianness.\n\n=head2 method write-int32\n\n    method write-int32(buf8: uint $pos, int32 $value, $endian = NativeEndian --> buf8:D)\n\nWrites a signed 32-bit integer value at the given position with the given\nendianness.\n\n=head2 method write-uint64\n\n    method write-uint64(buf8: uint $pos, uint64 $value, $endian = NativeEndian --> buf8:D)\n\nWrites an unsigned 64-bit integer value at the given position with the given\nendianness.\n\n=head2 method write-int64\n\n    method write-int64(buf8: uint $pos, Int:D $value, $endian = NativeEndian --> buf8:D)\n\nWrites a signed 64-bit integer value at the given position with the given\nendianness.\n\n=head2 method write-uint128\n\n    method write-uint128(buf8: uint $pos, UInt:D $value, $endian = NativeEndian --> buf8:D)\n\nWrites an unsigned 128-bit integer value at the given position with the given\nendianness.\n\n=head2 method write-int128\n\n    method write-int128(buf8: uint $pos, Int:D $value, $endian = NativeEndian --> buf8:D)\n\nWrites a signed 128-bit integer value at the given position with the given\nendianness.\n\n=head2 method write-num32\n\n    method write-num32(buf8: uint $pos, num32 $value, $endian = NativeEndian --> buf8:D)\n\nWrites a native C<num32> IEEE floating point value at the given position with\nthe given endianness.\n\n=head2 method write-num64\n\n    method write-num64(buf8: uint $pos, num64 $value, $endian = NativeEndian --> buf8:D)\n\nWrites a native C<num64> IEEE floating point value at the given position with\nthe given endianness.\n\n=head2 method write-ubits\n\n    method write-ubits(buf8: uint $pos, uint $bits, UInt:D $value --> buf8:D)\n\nWrites an unsigned integer value to the B<bits> from the given B<bit> offset\nand given number of bits.  The endianness of the bits is assumed to be\nC<BigEndian>.\n\n=head2 method write-bits\n\n    method write-bits(buf8: uint $pos, uint $bits, Int:D $value --> buf8:D)\n\nWrites a signed integer value for the B<bits> from the given B<bit> offset\nand given number of bits.  The endianness of the bits is assumed to be\nC<BigEndian>.\n\n=head2 method Blob\n\n    method Buf(Buf:D: --> Blob:D)\n\nAvailable as of the 2021.06 Rakudo compiler release.\n\nCoerces the invocant into an immutable L<C<Blob>|/type/Blob> object.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/CX/Done.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class CX::Done\n\n=SUBTITLE Done control exception\n\n    class CX::Done does X::Control { }\n\nA L<control exception|/language/exceptions#Control_exceptions> to be used to\nindicate a supply block is finished by calling C<done>.\n\n=head1 Methods\n\n=head2 method message\n\n    method message()\n\nReturns C<'<done control exception>'>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/CX/Emit.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE role CX::Emit\n\n=SUBTITLE Emit control exception\n\n    class CX::Emit does X::Control { }\n\nA L<control exception|/language/exceptions#Control_exceptions> to be used when\nemit is used inside a L<C<Supply>|/type/Supply> block.\n\n=head1 Methods\n\n=head2 method message\n\n    method message()\n\nReturns C<'<emit control exception>'>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/CX/Last.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE role CX::Last\n\n=SUBTITLE Last control exception\n\n    class CX::Last does X::Control { }\n\nA L<control exception|/language/exceptions#Control_exceptions> that is thrown\nwhen C<last> is called.\n\n=head1 Methods\n\n=head2 method message\n\n    method message()\n\nReturns C<'<last control exception>'>. Since this type of exception is to be\nconsumed by type and not really by the content of the message, this is a generic\nmessage, similar to all other C<CX::*> exceptions.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/CX/Next.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE role CX::Next\n\n=SUBTITLE Next control exception\n\n    class CX::Next does X::Control { }\n\nA L<control exception|/language/exceptions#Control_exceptions> that is triggered\nwhen C<next> is called.\n\n=for code\nfor ^10 {\n    CONTROL {\n      when CX::Next { say \"We're next\" };\n    }\n    next if $_ %% 2;\n    say \"We're in $_\";\n}\n\nThis will print:\n\n=for code :lang<text>\nWe're next\nWe're in 1\nWe're next\nWe're in 3\nWe're next\nWe're in 5\nWe're next\nWe're in 7\nWe're next\nWe're in 9\n\n\n=head1 Methods\n\n=head2 method message\n\n    method message()\n\nReturns C<'<next control exception>'>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/CX/Proceed.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE role CX::Proceed\n\n=SUBTITLE Proceed control exception\n\n    class CX::Proceed does X::Control { }\n\nA L<control exception|/language/exceptions#Control_exceptions> to be used when\nC<proceed> is used within C<when> or C<default> blocks.\n\n=head1 Methods\n\n=head2 method message\n\n    method message()\n\nReturns C<'<proceed control exception>'>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/CX/Redo.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE role CX::Redo\n\n=SUBTITLE Redo control exception\n\n    class CX::Redo does X::Control { }\n\nA L<control exception|/language/exceptions#Control_exceptions> thrown when\nC<redo> is called.\n\n=head1 Methods\n\n=head2 method message\n\n    method message()\n\nReturns C<'<redo control exception>'>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/CX/Return.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE role CX::Return\n\n=SUBTITLE Return control exception\n\n    class CX::Return does X::Control { }\n\nA L<control exception|/language/exceptions#Control_exceptions> to be used when\nreturn is called from within a sub.\n\n=head1 Methods\n\n=head2 method message\n\n    method message()\n\nReturns C<'<return control exception>'>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/CX/Succeed.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE role CX::Succeed\n\n=SUBTITLE Succeed control exception\n\n    class CX::Succeed does X::Control { }\n\nA L<control exception|/language/exceptions#Control_exceptions> thrown when\nC<succeed> is called from a C<when> or C<default> block.\n\n=head1 Methods\n\n=head2 method message\n\n    method message()\n\nReturns C<'<next control exception>'>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/CX/Take.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE role CX::Take\n\n=SUBTITLE Take control exception\n\n    class CX::Take does X::Control { }\n\nA L<control exception|/language/exceptions#Control_exceptions> triggered by\nC<take>.\n\n=head1 Methods\n\n=head2 method message\n\n    method message()\n\nReturns C<'<take control exception>'>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/CX/Warn.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE role CX::Warn\n\n=SUBTITLE Control exception warning\n\n    class CX::Warn does X::Control { }\n\nA L<control exception|/language/exceptions#Control_exceptions> triggered when C<warn> is called to warn about any\nincidence.\n\n=head1 Methods\n\n=head2 method new\n\nC<CX::Warn> objects are created when a warning is thrown in any block.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/CallFrame.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class CallFrame\n\n=SUBTITLE Captures the current frame state\n\n    class CallFrame {}\n\nA C<CallFrame> will be usually captured from the\ncurrent state of a program using the L<callframe|/routine/callframe> subroutine.\n\n    my $frame = callframe;\n    say \"The above line of code ran at {$frame.file}:{$frame.line}.\";\n\nWith no arguments the callframe will give you frame information for the line\ncalling C<callframe>. The file and line annotations will be identical to those\nin L«C<$?FILE>|/language/variables#Compile-time_variables» and\nL«C<$?LINE>|/language/variables#Compile-time_variables».\n\nYou may, however, pass a number to C<callframe> to specify a different frame\nlevel. A positive number will move upward through the levels of frame. A\nnegative number will move downward into the C<callframe> method and class itself\nat the point at which they are running to construct this information for you.\n\nThe frames themselves do not necessarily match only method or subroutine calls.\nRaku constructs a frames for blocks and such as well, so if you need a callframe\nfor a particular method call, do not assume it is a fixed number of levels up.\n\nEach frame stores L<annotations|/routine/annotations>, including the\nL<file|/routine/file> and L<line|/routine/line> annotations, which have\nconvenience methods for accessing them directly. You can also retrieve a\nreference to the code block of the currently executing frame using the\nL<code|/routine/code> method.  The frame also captures all lexical variables\nstored with the frame, which are available by calling L<my|/routine/my> on the\nframe object.\n\nHere's a short example that will find the calling routine and print the package\nof the caller using the C<callframe> interface.\n\n    sub calling-frame() {\n        for 1..* -> $level {\n            given callframe($level) -> $frame {\n                when $frame ~~ CallFrame {\n                        next unless $frame.code ~~ Routine;\n                        say $frame.code.package;\n                        last;\n                }\n                default {\n                        say \"no calling routine or method found\";\n                        last;\n                }\n            }\n        }\n    }\n\n    calling-frame;\n\nIf you just need to trace caller information, L<C<Backtrace>|/type/Backtrace> may\nprovide a better means of getting it. C<CallFrame>\ncontains more information about a specific frame, but provides a tedious\ninterface for enumerating a call stack.\n\n=head1 Methods\n\nB<Note> From version 6.d, C<.raku> (C<.perl> before release 2019.11) can be\ncalled on C<CallFrame>.\n\n=head2 method code\n\n    method code()\n\nReturn the callable code for the current block. When called on the object\nreturned by C<callframe(0)>, this will be the same value found in\nL«C<&?BLOCK>|/language/variables#Compile-time_variables».\n\n=for code\nmy $frame;\nfor ^3 { FIRST $frame = callframe; say $_ * 3 };\nsay $frame.code()\n\nThe C<$frame> variable will hold the L<C<Code>|/type/Code> for the block inside the loop in\nthis case.\n\n=head2 method file\n\n    method file()\n\nThis is a shortcut for looking up the C<file> annotation. Therefore, the\nfollowing code prints C<True>.\n\n    my $frame = callframe(0);\n    say $frame.file eq $frame.annotations<file>;\n\n=head2 method line\n\n    method line()\n\nThis is a shortcut for looking up the C<line> annotation. For example, the\nfollowing two calls are identical.\n\n    say callframe(1).line;\n    say callframe(1).annotations<line>;\n\n=head2 method annotations\n\n    method annotations()\n\nReturns a L<C<Map>|/type/Map> containing the invocants annotations, i.e. C<line>\nand C<file>. An easier way to get hold of the annotation information is to use\none of the convenience methods instead.\n\n    say callframe.annotations.^name;                   # OUTPUT: «Map␤»\n    say callframe.annotations<file> eq callframe.file; # OUTPUT: «True␤»\n\n=head2 method my\n\n    method my()\n\nReturn a L<C<Hash>|/type/Hash> that names all the variables and their values\nassociated with the lexical scope of the frame.\n\n    sub some-value {\n        my $the-answer = 42;\n        callframe(0);\n    }\n\n    my $frame = some-value();\n    say $frame.my<$the-answer>; # OUTPUT: «42␤»\n\n=head1 Routines\n\n=head2 sub callframe\n\n    sub callframe(Int:D $level = 0)\n\nReturns a C<CallFrame> object for the given level. If no level\nis given, the default level is 0. Positive levels move up the frame stack and\nnegative levels move down (into the call to C<callframe> and deeper).\n\nReturns L<C<Mu>|/type/Mu> if there is no call information for the given level.\nNegative levels may result in an exception.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Callable.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"basic\")\n\n=TITLE role Callable\n\n=SUBTITLE Invocable code object\n\n    role Callable { ... }\n\nRole for objects which support calling them. It's used in L<C<Block>|/type/Block>,\nL<C<Routine>|/type/Routine>, L<C<Sub>|/type/Sub>, L<C<Method>|/type/Method>, L<C<Submethod>|/type/Submethod> and L<C<Macro>|/type/Macro> types.\n\nCallables can be stored in C<&>-sigiled containers, the default type constraint\nof such a container is C<Callable>.\n=comment A signature object can be used to\n=comment force a check against the signature of the Callable to be stored into the\n=comment container.\n\n    my &a = {;}; # Empty block needs a semicolon\n    my &b = -> {};\n    my &c = sub () {};\n    sub foo() {};\n    my &d = &foo;\n=comment commented out until it's implemented for code\n=comment my &f:(Int) = sub bar(Int) {}; # Not yet implemented\n=comment my &f:(Str) = -> Str {};       # Not yet implemented\n\n=head1 Methods\n\n=head2 method CALL-ME\n\n    method CALL-ME(Callable:D $self: |arguments)\n\nThis method is required for the L«C<( )> postcircumfix operator|/language/operators#postcircumfix_(_)»\nand the L«C<.( )> postcircumfix operator|/language/operators#index-entry-.(_)». It's what makes\nan object actually call-able and needs to be overloaded to let a given object\nact like a routine. If the object needs to be stored in an C<&>-sigiled\ncontainer, it has to implement Callable.\n\n    class A does Callable {\n        submethod CALL-ME(|c){ 'called' }\n    }\n    my &a = A;\n    say a(); # OUTPUT: «called␤»\n\nApplying the C<Callable> role is not a requirement to make an object callable;\nif a class simply wants to add subroutine-like semantics in a regular scalar\ncontainer, the submethod C<CALL-ME> can be used for that.\n\n    class A {\n        has @.values;\n        submethod CALL-ME(Int $x where 0 <= * < @!values.elems) {\n            @!values[$x]\n        }\n    }\n    my $a = A.new: values => [4,5,6,7];\n    say $a(2); # OUTPUT: «6␤»\n\n=head2 method Capture\n\n    method Capture()\n\nThrows L<C<X::Cannot::Capture>|/type/X::Cannot::Capture>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Cancellation.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Cancellation\n\n=SUBTITLE Removal of a task from a Scheduler before normal completion\n\n    my class Cancellation {}\n\nA low level part of the Raku L<concurrency|/language/concurrency#Schedulers>\nsystem. Some L<C<Scheduler>|/type/Scheduler> objects return a C<Cancellation> with the\nL<.cue|/type/Scheduler#method_cue> method which can be used to cancel the\nscheduled execution before normal completion.  C<Cancellation.cancelled> is a\nBoolean that is true after C<cancel> is called.\n\n=head1 Methods\n\n=head2 method cancel\n\n    method cancel()\n\nUsage:\n\n=begin code\nCancellation.cancel\n=end code\n\nCancels the scheduled execution of a task before normal completion.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Capture.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class Capture\n\n=SUBTITLE Argument list suitable for passing to a Signature\n\nX<|Syntax,capture literal (Capture)>\nX<|Syntax,\\() (Capture)>\n\n=for code\nclass Capture { }\n\nA C<Capture> is a container for passing arguments to a code object. Captures\nare the flip-side of L<C<Signature>|/type/Signature>s. Thus, captures are the\ncaller-defined arguments, while signatures are the callee-defined parameters.\nFor example when you call C<print $a, $b>, the C<$a, $b> part is a capture.\n\nCaptures contain a list-like part for positional arguments and a hash-like part\nfor named arguments, thus behaving as L<C<Positional>|/type/Positional> and\nL<C<Associative>|/type/Associative>, although it does not actually mix in those\nroles. Like any other data structure, a stand-alone capture can be created,\nstored, and used later.\n\nA literal C<Capture> can be created by prefixing a term with a backslash C<\\>.\nCommonly, this term will be a L«C<List>|/type/List» of terms, from which\nthe forms C«key => value» and C«:key<value>» of a L«C<Pair>|/type/Pair» literal\nwill be placed in the named part, and all other terms will be placed in the\npositional part (including L<C<Pair>|/type/Pair>s of the form C«'key' => value»).\n\n    my $a = \\(42);                      # Capture with one positional arg\n    my $b = \\(1, 2, verbose => True);   # Capture with two positional args and one named arg\n    my $c = \\(1, 2, :verbose(True));    # same as before\n    my $c = \\(1, 2, 'verbose' => True); # Capture with three positional args\n\nTo reiterate, named arguments in a capture must be created using one of two\nways:\n\n=item Use an I<unquoted> key naming a parameter, followed by C«=>», followed by\nthe argument. For example, C«as => by => {1/$_}».\n\n=item Use a L<colon-pair|/language/glossary#Colon_pair_and_colon_list> literal\nnamed after the parameter. For example, C<:into(my %leap-years)>.\n\nFor example:\n\n    sub greet(:$name, :$age) {\n        \"$name, $age\"\n    }\n\n    my $d = \\(name => 'Mugen', age => 19);   # OK\n    my $e = \\(:name('Jin'), :age(20));       # OK\n    my $f = \\('name' => 'Fuu', 'age' => 15); # Not OK, keys are quoted.\n\nFor the C<greet> subroutine that accepts two named arguments C<name> and\nC<age>, the captures C<$d> and C<$e> will work fine while the capture C<$f>\nwill throw a C<Too many positionals passed...> error. This is because\nC«'age' => 20» isn't a named argument (as per the two ways of creating one\nmentioned above) but a positional argument of which C<greet> expects none. In\nthe context of captures, quoted keys don't create named arguments. Any C«'key'\n=> value» is just another positional parameter, thus exercise some caution when\ncreating captures with named arguments.\n\nOnce a capture is created, you may use it by prefixing it with a vertical bar\nC<|> in a subroutine call, and it will be as if the values in the capture were\npassed directly to the subroutine as arguments — named arguments will be passed\nas named arguments and positional arguments will be passed as positional\narguments. You may re-use the capture as many times as you want, even with\ndifferent subroutines.\n\n=for code :preamble<my $d;my $e; sub greet {...}>\nsay greet |$d;                # OUTPUT: «Mugen, 19␤»\nsay greet |$e;                # OUTPUT: «Jin, 20␤»\n\n    my $x = \\(4, 2, 3, -2);\n    say reverse |$x;              # OUTPUT: «(-2 3 2 4)␤»\n    say sort 5, |$x;              # OUTPUT: «(-2 2 3 4 5)␤»\n\n    say unique |$x, as => {.abs}; # OUTPUT: «(4 2 3)␤»\n    say unique |$x, :as({.abs});  # OUTPUT: «(4 2 3)␤»\n\n    my $y = \\(1, 7, 3, by => {1/$_});\n    say min |$y;                  # OUTPUT: «7␤», same as min 1, 7, 3, by => {1/$_}\n    say max |$y;                  # OUTPUT: «1␤», same as max 1, 7, 3, by => {1/$_}\n\nInside a L<C<Signature>|/type/Signature>, a C<Capture> may be created by prefixing a\nL<sigilless parameter|/language/variables#Sigilless_variables> with a\nvertical bar C<|>. This packs the remainder of the argument list into that\nL<capture parameter|/language/signatures#Capture_parameters>.\n\n    sub f($a, |c) {\n        say $a;\n        say c;\n        say c.^name;\n        say c.list; # see Methods section\n        say c.hash; # see Methods section\n    }\n\n    f 1, 2, 3, a => 4, :b(5);\n    # OUTPUT:\n    # 1\n    # \\(2, 3, :a(4), :b(5))\n    # Capture\n    # (2 3)\n    # Map.new((a => 4, b => 5))\n\nNote that C<Capture>s are still like L<C<List>|/type/List>s in that they may contain containers,\nnot just literal values:\n\n    my $b = 1;\n    my $c = \\(4, 2, $b, 3);\n    say min |$c;        # OUTPUT: «1␤»\n    $b = -5;\n    say min |$c;        # OUTPUT: «-5␤»\n\n=head1 Methods\n\n=head2 method list\n\n    method list(Capture:D:)\n\nReturns the positional part of the C<Capture>.\n\n    my Capture $c = \\(2, 3, 5, apples => (red => 2));\n    say $c.list; # OUTPUT: «(2 3 5)␤»\n\n=head2 method hash\n\n    method hash(Capture:D:)\n\nReturns the named/hash part of the C<Capture>.\n\n    my Capture $c = \\(2, 3, 5, apples => (red => 2));\n    say $c.hash; # OUTPUT: «Map.new((:apples(:red(2))))␤»\n\n=head2 method elems\n\n    method elems(Capture:D: --> Int:D)\n\nReturns the number of positional elements in the C<Capture>.\n\n    my Capture $c = \\(2, 3, 5, apples => (red => 2));\n    say $c.elems; # OUTPUT: «3␤»\n\n=head2 method keys\n\n    multi method keys(Capture:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> containing all positional keys followed by all\nnamed keys. For positional arguments the keys are the respective arguments'\nordinal positions starting from zero.\n\n    my $capture = \\(2, 3, 5, apples => (red => 2));\n    say $capture.keys; # OUTPUT: «(0 1 2 apples)␤»\n\n=head2 method values\n\n    multi method values(Capture:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> containing all positional values followed by all\nnamed argument values.\n\n    my $capture = \\(2, 3, 5, apples => (red => 2));\n    say $capture.values; # OUTPUT: «(2 3 5 red => 2)␤»\n\n=head2 method kv\n\n    multi method kv(Capture:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> of alternating L<keys|#method_keys> and\nL<values|#method_values>. The positional keys and values, if any, come\nfirst followed by the named keys and values.\n\n    my $capture = \\(2, 3, apples => (red => 2));\n    say $capture.kv; # OUTPUT: «(0 2 1 3 apples red => 2)␤»\n\n=head2 method pairs\n\n    multi method pairs(Capture:D: --> Seq:D)\n\nReturns all arguments, the positional followed by the named, as a\nL<C<Seq>|/type/Seq> of L<C<Pair>|/type/Pair>s. Positional arguments have\ntheir respective ordinal value, starting at zero, as key while the\nnamed arguments have their names as key.\n\n    my Capture $c = \\(2, 3, apples => (red => 2));\n    say $c.pairs; # OUTPUT: «(0 => 2 1 => 3 apples => red => 2)␤»\n\n=head2 method antipairs\n\n    multi method antipairs(Capture:D: --> Seq:D)\n\nReturns all arguments, the positional followed by the named, as a\nL<C<Seq>|/type/Seq> of L<C<Pair>|/type/Pair>s where the keys and values\nhave been swapped, i.e. the value becomes the key and the key becomes\nthe value. This behavior is the opposite of the L<pairs|#method_pairs>\nmethod.\n\n    my $capture = \\(2, 3, apples => (red => 2));\n    say $capture.antipairs; # OUTPUT: «(2 => 0 3 => 1 (red => 2) => apples)␤»\n\n=head2 method Bool\n\n    method Bool(Capture:D: --> Bool:D)\n\nReturns C<True> if the C<Capture> contains at least one named or one\npositional argument.\n\n    say \\(1,2,3, apples => 2).Bool; # OUTPUT: «True␤»\n    say \\().Bool;                   # OUTPUT: «False␤»\n\n=head2 method Capture\n\n    method Capture(Capture:D: --> Capture:D)\n\nReturns itself, i.e. the invocant.\n\n    say \\(1,2,3, apples => 2).Capture; # OUTPUT: «\\(1, 2, 3, :apples(2))␤»\n\n=head2 method Numeric\n\n    method Numeric(Capture:D: --> Int:D)\n\nReturns the number of positional elements in the C<Capture>.\n\n    say \\(1,2,3, apples => 2).Numeric; # OUTPUT: «3␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Channel.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Channel\n\n=SUBTITLE Thread-safe queue for sending values from producers to consumers\n\n    class Channel {}\n\nA C<Channel> is a thread-safe queue that helps you to send a series of objects\nfrom one or more producers to one or more consumers.  Each object will arrive at\nonly one such consumer, selected by the scheduler.  If there is only one\nconsumer and one producer, the order of objects is guaranteed to be preserved.\nSending on a C<Channel> is non-blocking.\n\n    my $c = Channel.new;\n    await (^10).map: {\n        start {\n            my $r = rand;\n            sleep $r;\n            $c.send($r);\n        }\n    }\n    $c.close;\n    say $c.list;\n\nFurther examples can be found in the L<concurrency page|/language/concurrency#Channels>\n\n=head1 Methods\n\n=head2 method send\n\n    method send(Channel:D: \\item)\n\nEnqueues an item into the C<Channel>. Throws an exception of type\nL<C<X::Channel::SendOnClosed>|/type/X::Channel::SendOnClosed> if the C<Channel> has been\nclosed already. This call will B<not> block waiting for a consumer to take the object.\nThere is no set limit on the number of items that may be queued, so\ncare should be taken to prevent runaway queueing.\n\n    my $c = Channel.new;\n    $c.send(1);\n    $c.send([2, 3, 4, 5]);\n    $c.close;\n    say $c.list; # OUTPUT: «(1 [2 3 4 5])␤»\n\n=head2 method receive\n\n    method receive(Channel:D:)\n\nReceives and removes an item from the C<Channel>. It blocks if no item is\npresent, waiting for a C<send> from another thread.\n\nThrows an exception of\ntype L<C<X::Channel::ReceiveOnClosed>|/type/X::Channel::ReceiveOnClosed> if the C<Channel>\nhas been closed, and the last item has been removed already, or if C<close> is called\nwhile C<receive> is waiting for an item to arrive.\n\nIf the C<Channel> has been marked as erratic with method C<fail>, and the last\nitem has been removed, throws the argument that was given to C<fail> as an\nexception.\n\nSee method C<poll> for a non-blocking version that won't throw exceptions.\n\n    my $c = Channel.new;\n    $c.send(1);\n    say $c.receive; # OUTPUT: «1␤»\n\n=head2 method poll\n\n    method poll(Channel:D:)\n\nReceives and removes an item from the C<Channel>. If no item is present, returns\nL<C<Nil>|/type/Nil> instead of waiting.\n\n    my $c = Channel.new;\n    Promise.in(2).then: { $c.close; }\n    ^10 .map({ $c.send($_); });\n    loop {\n        if $c.poll -> $item { $item.say };\n        if $c.closed  { last };\n        sleep 0.1;\n    }\n\nSee method C<receive> for a blocking version that properly responds to C<Channel>\nclosing and failure.\n\n=head2 method close\n\n    method close(Channel:D:)\n\nClose the C<Channel>, normally.  This makes subsequent C<send> calls die with\nL<C<X::Channel::SendOnClosed>|/type/X::Channel::SendOnClosed>.  Subsequent calls of\nC<.receive> may still drain any remaining items that were previously sent, but if\nthe queue is empty, will throw an L<C<X::Channel::ReceiveOnClosed>|/type/X::Channel::ReceiveOnClosed>\nexception.  Since you can produce a L<C<Seq>|/type/Seq> from a C<Channel> by contextualizing to array with C<@()>\nor by calling the C<.list> method, these methods will not terminate until the C<Channel> has been\nclosed. A L<whenever|/language/concurrency#whenever>-block will also\nterminate properly on a closed C<Channel>.\n\n=for code\nmy $c = Channel.new;\n$c.close;\n$c.send(1);\nCATCH { default { put .^name, ': ', .Str } };\n# OUTPUT: «X::Channel::SendOnClosed: Cannot send a message on a closed channel␤»\n\nPlease note that any exception thrown may prevent C<.close> from being called,\nthis may hang the receiving thread. Use a L<LEAVE|/language/phasers#LEAVE>\nphaser to enforce the C<.close> call in this case.\n\n=head2 method list\n\n    method list(Channel:D:)\n\nReturns a list based on the L<C<Seq>|/type/Seq> which will iterate items in the queue and\nremove each item from it as it iterates. This can only terminate once the\nC<close> method has been called.\n\n    my $c = Channel.new; $c.send(1); $c.send(2);\n    $c.close;\n    say $c.list; # OUTPUT: «(1 2)␤»\n\n=head2 method closed\n\n    method closed(Channel:D: --> Promise:D)\n\nReturns a promise that will be kept once the C<Channel> is closed by a call to\nmethod C<close>.\n\n    my $c = Channel.new;\n    $c.closed.then({ say \"It's closed!\" });\n    $c.close;\n    sleep 1;\n\n=head2 method fail\n\n    method fail(Channel:D: $error)\n\nCloses the C<Channel> (that is, makes subsequent C<send> calls die), and enqueues\nthe error to be thrown as the final element in the C<Channel>. Method C<receive>\nwill throw that error as an exception.  Does nothing if the C<Channel> has already\nbeen closed or C<.fail> has already been called on it.\n\n    my $c = Channel.new;\n    $c.fail(\"Bad error happens!\");\n    $c.receive;\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::AdHoc: Bad error happens!␤»\n\n=head2 method Capture\n\n    method Capture(Channel:D: --> Capture:D)\n\nEquivalent to calling L«C<.List.Capture>|/type/List#method_Capture»\non the invocant.\n\n=head2 method Supply\n\n    method Supply(Channel:D:)\n\nThis returns an C<on-demand> L<C<Supply>|/type/Supply> that emits a value for every value\nreceived on the C<Channel>. C<done> will be called on the L<C<Supply>|/type/Supply> when the C<Channel>\nis closed.\n\n    my $c = Channel.new;\n    my Supply $s1 = $c.Supply;\n    my Supply $s2 = $c.Supply;\n    $s1.tap(-> $v { say \"First $v\" });\n    $s2.tap(-> $v { say \"Second $v\" });\n    ^10 .map({ $c.send($_) });\n    sleep 1;\n\nMultiple calls to this method produce multiple instances of Supply, which compete\nover the values from the C<Channel>.\n\n=head2 sub await\n\n    multi await(Channel:D)\n    multi await(*@)\n\nWaits until all of one or more C<Channel>s has a value available, and returns\nthose values (it calls C<.receive> on the C<Channel>). Also works with\nL<C<Promise>|/type/Promise>s.\n\n    my $c = Channel.new;\n    Promise.in(1).then({$c.send(1)});\n    say await $c;\n\nSince 6.d, it no longer blocks a thread while waiting.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Code.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Code\n\n=SUBTITLE Code object\n\n    class Code is Any does Callable {}\n\nC<Code> is the ultimate base class of all code objects in Raku. It\nexposes functionality that all code objects have. While thunks are\ndirectly of type C<Code>, most code objects (such as those resulting\nfrom blocks, subroutines or methods) will belong to some subclass of C<Code>.\n\n=head1 Methods\n\n=head2 method ACCEPTS\n\n    multi method ACCEPTS(Code:D: Mu $topic)\n\nUsually calls the code object and passes C<$topic> as an argument.\nHowever, when called on a code object that takes no arguments, the code\nobject is invoked with no arguments and C<$topic> is dropped. The\nresult of the call is returned.\n\n=head2 method arity\n\n    method arity(Code:D: --> Int:D)\n\nReturns the minimum number of positional arguments that must be passed\nin order to call the code object. Any optional or slurpy parameters in the\ncode object's L<C<Signature>|/type/Signature> do not contribute, nor do named parameters.\n\n    sub argless() { }\n    sub args($a, $b?) { }\n    sub slurpy($a, $b, *@c) { }\n    say &argless.arity;             # OUTPUT: «0␤»\n    say &args.arity;                # OUTPUT: «1␤»\n    say &slurpy.arity;              # OUTPUT: «2␤»\n\n=head2 method assuming\n\n    method assuming(Callable:D $self: |primers)\n\nReturns a new L<C<Callable>|/type/Callable> that has been L<primed|/language/glossary#priming>\nwith the arguments passed to C<assuming>.  In other words, the new function\nimplements the same behavior as the original, but has the values passed to\nC<.assuming> already bound to the corresponding parameters.\n\n    my sub slow($n){ my $i = 0; $i++ while $i < $n; $i }\n\n    # takes only one parameter and as such wont forward $n\n    sub bench(&c) { c, now - ENTER now }\n\n    say &slow.assuming(10000000).&bench; # OUTPUT: «(10000000 7.5508834)␤»\n\nFor a sub with arity greater than one, you can use L«C<Whatever> C<*>|/type/Whatever» for all of\nthe positional parameters that are not \"assumed\".\n\n    sub first-and-last ( $first, $last ) {\n        say \"Name is $first $last\";\n    }\n\n    my &surname-smith = &first-and-last.assuming( *, 'Smith' );\n\n    surname-smith( 'Joe' ); # OUTPUT: «Name is Joe Smith␤»\n\nYou can handle any combination of assumed and not assumed positional parameters:\n\n=begin code\nsub longer-names ( $first, $middle, $last, $suffix ) {\n    say \"Name is $first $middle $last $suffix\";\n}\n\nmy &surname-public = &longer-names.assuming( *, *, 'Public', * );\n\nsurname-public( 'Joe', 'Q.', 'Jr.'); # OUTPUT: «Name is Joe Q. Public Jr.␤»\n=end code\n\nNamed parameters can be assumed as well:\n\n    sub foo { say \"$^a $^b $:foo $:bar\" }\n    &foo.assuming(13, foo => 42)(24, bar => 72); # OUTPUT: «13 24 42 72␤»\n\nAnd you can use C<.assuming> on all types of L<Callables|/type/Callable>,\nincluding L<Methods|/type/Method> and L<Blocks|/type/Block>:\n\n    # We use a Whatever star for the invocant:\n    my &comber = Str.^lookup('comb').assuming( *, /R \\w+/ );\n    say comber 'Raku is awesome! Ruby is great! And Rust is OK too';\n    # OUTPUT: «(Raku Ruby Rust)␤»\n\n    my &learner = {\n        \"It took me $:months months to learn $^lang\"\n    }.assuming: 'Raku';\n    say learner months => 2;  # OUTPUT: «It took me 2 months to learn Raku␤»\n\n=head2 method count\n\n    method count(Code:D: --> Real:D)\n\nReturns the maximum number of positional arguments that may be passed\nwhen calling the code object. For code objects that can accept any\nnumber of positional arguments (that is, they have a slurpy parameter),\nC<count> will return C<Inf>. Named parameters do not contribute.\n\n    sub argless() { }\n    sub args($a, $b?) { }\n    sub slurpy($a, $b, *@c) { }\n    say &argless.count;             # OUTPUT: «0␤»\n    say &args.count;                # OUTPUT: «2␤»\n    say &slurpy.count;              # OUTPUT: «Inf␤»\n\n=head2 method of\n\n    method of(Code:D: --> Mu)\n\nReturns the L<return type constraint|/language/signatures#Constraining_return_types>\nof the C<Code>:\n\n    say -> () --> Int {}.of; # OUTPUT: «(Int)␤»\n\n=head2 method signature\n\n    multi method signature(Code:D: --> Signature:D)\n\nReturns the L<C<Signature>|/type/Signature> object for this code object, which describes\nits parameters.\n\n    sub a(Int $one, Str $two) {};\n    say &a.signature; # OUTPUT: «(Int $one, Str $two)␤»\n\n=head2 method cando\n\n    method cando(Capture $c)\n\nReturns a list of candidates that can be called with the given\nL<C<Capture>|/type/Capture>.  Since C<Code> objects do not have any multiple\ndispatch, this either returns a list with the object, or an empty list.\n\n    my $single = \\'a';         # a single argument Capture\n    my $plural = \\('a', 42);   # a two argument Capture\n    my &block = { say $^a };   # a Block object, that is a subclass of Code, taking one argument\n    say &block.cando($single); # OUTPUT: «(-> $a { #`(Block|94212856419136) ... })␤»\n    say &block.cando($plural); # OUTPUT: «()␤»\n\n=head2 method Str\n\n    multi method Str(Code:D: --> Str:D)\n\nWill output the method name, but also produce a warning. Use C<.raku> or\nC<.gist> instead.\n\n    sub marine() { }\n    say ~&marine;\n    # OUTPUT: «Sub object coerced to string (please use .gist or .raku to do that)␤marine␤»\n    say &marine.Str;\n    # OUTPUT: «Sub object coerced to string (please use .gist or .raku to do that)␤marine␤»\n    say &marine.raku; # OUTPUT: «sub marine { #`(Sub|94280758332168) ... }␤»\n\n=head2 method file\n\n    method file(Code:D: --> Str:D)\n\nReturns the name of the file in which the code object was declared.\n\n    say &infix:<+>.file;   # OUTPUT: «SETTING::src/core.c/Numeric.rakumod␤»\n\n=head2 method line\n\n    method line(Code:D: --> Int:D)\n\nReturns the line number in the source code at which the code object's\ndeclaration begins.\n\n    say &infix:<+>.line;   # OUTPUT: «208␤»\n\nIf the code object was generated automatically (and thus I<not>\ndeclared in the source code), then C<line> returns the line on which\nthe enclosing scope's declaration begins.  For example, when called on\nan L<automatically generated accessor method|\n/language/objects#Attributes> produced by the C<has $.name>\nsyntax, C<line> returns the line on which the method's class's\ndeclaration begins.\n\nFor example, if you have the following source file:\n\n    class Food {                # Line 1\n        has $.ingredients;      # Line 2\n                                # Line 3\n        method eat {};          # Line 4\n    }                           # Line 5\n\nThen the C<line> method would give you the following output:\n\n=begin code :preamble<class Food { has $.ingredients; method eat {};}>\nsay Food.^lookup('eat').line;          # OUTPUT: «4␤»\nsay Food.^lookup('ingredients').line;  # OUTPUT: «1␤»\n=end code\n\n=head2 method bytecode-size\n\n    method bytecode-size(--> Int:D)\n\nNote: this method has been available in Rakudo compiler on the MoarVM backend only, starting from 2022.06 release.\n\nReturns the number of bytes that the code object occupies in memory.  Note\nthat if the code object is in fact a C<multi>, then the bytecode size will\nbe reported for the C<proto>.  You can use the C<.candidates> method to\nobtain each candidate, and then call the C<bytecode-size> methods on them.\n\n    say &grep.bytecode-size;              # OUTPUT: «114␤»\n    say &grep.cadidates>>.bytecode-size;  # OUTPUT: «424␤258␤»\n\n=head2 method is-implementation-detail\n\n    method is-implementation-detail(--> False)\n\nNote: this method has been available in Rakudo compiler starting from 2020.05 release.\n\nReturns C<True> if the code object was marked with\nL«C<is implementation-detail> trait|/language/traits#is_implementation-detail_trait»,\nC<False> otherwise.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Collation.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Collation\n\n=SUBTITLE Encapsulates instructions about how strings should be sorted\n\n=for code\nclass Collation { }\n\nC<Collation> is the class that allows proper sorting, taking into account all\nUnicode characteristics. It's the class the object\nL<C<$*COLLATION>|/language/variables#index-entry-%24*COLLATION> is instantiated\nto, and thus includes I<collation levels>, that is, what kind of features should\nbe looked up when comparing two strings and in which order.\n\n=head1 Methods\n\n=head2 method set\n\n=for code :method\nmethod set (\n    Int :$primary    = 1,\n    Int :$secondary  = 1,\n    Int :$tertiary   = 1,\n    Int :$quaternary = 1)\n\nSets if the different levels should be used in ascending or descending order, or\nif they are going to be ignored (when set to 0).\n\n=for code\nmy $*COLLATION = Collation.new;\nsay 'a' coll 'z'; # OUTPUT: «Less␤»\n$*COLLATION.set(:primary(-1));\nsay 'a' coll 'z'; # OUTPUT: «More␤»\n\n=head2 method primary\n\n    method primary\n\nReturns the state of the primary collation level.\n\n=head2 method secondary\n\n    method secondary\n\nReturns the state of the secondary collation level.\n\n=head2 method tertiary\n\n    method tertiary\n\nReturns the state of the tertiary collation level.\n\n=head2 method quaternary\n\n    method quaternary\n\nReturns the state of the quaternary collation level.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/CompUnit/PrecompilationRepository.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"domain-specific\")\n\n=TITLE role CompUnit::PrecompilationRepository\n\n=SUBTITLE CompUnit::PrecompilationRepository\n\nThis class provides stubs for each of the following methods. The methods are provided by sub-classes,\nsuch as C<PrecompilationRepository::File>. Sub-classes are implementation dependent.\n\n=head1 Methods\n\n=head2 method new-unit\n\n    method new-unit(| --> CompUnit::PrecompilationUnit:D)\n    { ... }\n\nPrepare a new implementation specific PrecompilationUnit for storage\n\n=head2 method load-unit\n\n    method load-unit(CompUnit::PrecompilationId $compiler-id,\n                CompUnit::PrecompilationId $precomp-id)\n    { ... }\n\nLoad the precompilation identified by the pairing of the specified\ncompiler and precompilation ID.\n\n=head2 method load-repo-id\n\n    method load-repo-id(CompUnit::PrecompilationId $compiler-id,\n                CompUnit::PrecompilationId $precomp-id)\n    { ... }\n\nReturn the repository id for which the specified precomp file's\ndependencies have been validated\n\n=head2 method store-file\n\n    method store-file(CompUnit::PrecompilationId $compiler-id,\n                 CompUnit::PrecompilationId $precomp-id,\n                 IO::Path:D $path,\n                 :$extension = '')\n    { ... }\n\nStore the file at the specified path in the precompilation store,\nunder the given compiler ID and precompilation ID.\n\n=head2 method store-unit\n\n    method store-unit(CompUnit::PrecompilationId $compiler-id,\n                 CompUnit::PrecompilationId $precomp-id,\n                 CompUnit::PrecompilationUnit $unit)\n    { ... }\n\nStore the given precompilation unit in the precompilation store\nunder the given compiler ID and precompilation ID.\n\n=head2 method store-repo-id\n\n    method store-repo-id(CompUnit::PrecompilationId $compiler-id,\n                 CompUnit::PrecompilationId $precomp-id,\n                 :$repo-id!)\n    { ... }\n\nStore the given repo-id for a precompilation under the given\ncompiler ID and precompilation ID.\n\n=head2 method delete\n\n    method delete(CompUnit::PrecompilationId $compiler-id,\n                  CompUnit::PrecompilationId $precomp-id)\n    { ... }\n\nDelete an individual precompilation.\n\n=head2 method delete-by-compiler\n\n    method delete-by-compiler(CompUnit::PrecompilationId $compiler-id)\n    { ... }\n\nDelete all precompilations for a particular compiler.\n=end pod\n"
  },
  {
    "path": "doc/Type/CompUnit/Repository/FileSystem.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class CompUnit::Repository::FileSystem\n\n=SUBTITLE CompUnit::Repository::FileSystem\n\n=for code :preamble<role CompUnit::Repository::Locally {}; role CompUnit::Repository {};>\nclass CompUnit::Repository::FileSystem\n    does CompUnit::Repository::Locally\n    does CompUnit::Repository\n    { }\n\nA L<C<CompUnit::Repository>|/type/CompUnit::Repository> implementation backed by the filesystem typically used\nin development situations. This is what is used by C<-I .> / C<-I lib> (which are\nactually C<-I file#.> and C<-I file#lib>) or C<use lib \".\"> / C<use lib \"lib\">.\nUnlike L<C<CompUnit::Repository::Installation>|/type/CompUnit::Repository::Installation>, this represents a single distribution.\n\n=head1 Methods\n\n=head2 method candidates\n\n    multi method candidates(Str:D $name, :$auth, :$ver, :$api)\n    multi method candidates(CompUnit::DependencySpecification $spec)\n\nReturn all distributions that contain a module matching the specified C<$name>, C<auth>,\nC<ver>, and C<api>.\n\n    # assuming one is cloned into the zef git repository...\n    my $repo = CompUnit::Repository::FileSystem.new(prefix => $*CWD);\n    with $repo.candidates(\"Zef\").head -> $dist {\n        say \"Zef version: \" ~ $dist.meta<version>;\n    }\n    else {\n        say \"No candidates for 'Zef' found\";\n    }\n\n=head2 method files\n\n    multi method files(Str:D $name, :$auth, :$ver, :$api)\n    multi method files(CompUnit::DependencySpecification $spec)\n\nReturn all distributions that match the specified C<auth> C<ver> and C<api>, and\ncontains a non-module file matching the specified C<$name>.\n\n    # assuming one is cloned into the zef git repository...\n    my $repo = CompUnit::Repository::FileSystem.new(prefix => $*CWD);\n    say $repo.files('bin/zef', :ver<419.0+>).head.<name>              // \"Nada\"; # OUTPUT: «Nada␤»\n    say $repo.files('resources/config.txt', :ver<419.0+>).head.<name> // \"Nada\"; # OUTPUT: «Nada␤»\n\n    say $repo.files('bin/zef', :ver<0.4.0+>).head.<name>;                        # OUTPUT: «zef␤»\n    say $repo.files('resources/config.txt', :ver<0.4.0+>).head.<name>;           # OUTPUT: «zef␤»\n\n=head2 method resolve\n\n    method resolve(CompUnit::DependencySpecification $spec --> CompUnit:D)\n\nReturns a L<C<CompUnit>|/type/CompUnit> mapped to the highest version distribution matching C<$spec> from\nthe first repository in the repository chain that contains any version of a distribution\nmatching C<$spec>.\n\n=head2 method need\n\n=for code :method :preamble<method !precomp-stores() {...};>\nmethod need(\n    CompUnit::DependencySpecification $spec,\n    CompUnit::PrecompilationRepository $precomp = self.precomp-repository(),\n    CompUnit::PrecompilationStore :@precomp-stores = self!precomp-stores(),\n    --> CompUnit:D)\n\nLoads and returns a L<C<CompUnit>|/type/CompUnit> which is mapped to the highest version distribution\nmatching C<$spec> from the first repository in the repository chain that contains\nany version of a distribution matching C<$spec>.\n\n=head2 method load\n\n    method load(IO::Path:D $file --> CompUnit:D)\n\nLoad the C<$file> and return a L<C<CompUnit>|/type/CompUnit> object representing it.\n\n=head2 method loaded\n\n    method loaded(--> Iterable:D)\n\nReturns all L<C<CompUnit>|/type/CompUnit>s this repository has loaded.\n\n=head2 method short-id\n\n    method short-id()\n\nReturns the repo short-id, which for this repository is C<file>.\n\n=head2 attribute extensions\n\n    my $repo = CompUnit::RepositoryFileSystem.new(:prefix($*CWD));\n    say $repo.extensions; # OUTPUT: «[rakumod pm6 pm]␤»\n\nThe extensions of files the repository will consider raku modules when C<prefix> does\nnot contain a META6.json file. This can be set when including the library path itself\nby setting the attribute through the path spec:\n\n=for code :lang<shell>\n    # Like '-I lib', but only considers .rakumod and .pm6 files as raku modules\n    raku -I \"file#extensions<rakumod pm6>#lib\" -e 'use MyModule'\n\n=end pod\n"
  },
  {
    "path": "doc/Type/CompUnit/Repository/Installation.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class CompUnit::Repository::Installation\n\n=SUBTITLE CompUnit::Repository::Installation\n\n=for code :preamble<role CompUnit::Repository::Locally {}; role CompUnit::Repository::Installable {}>\nclass CompUnit::Repository::Installation\n    does CompUnit::Repository::Locally\n    does CompUnit::Repository::Installable\n    { }\n\nA L<C<CompUnit::Repository>|/type/CompUnit::Repository> implementation backed by the filesystem, but uses an internal\nstorage format to:\n\n=item Handle case sensitivity issues on filesystems that may conflict as a L<C<CompUnit::Repository::FileSystem>|/type/CompUnit::Repository::FileSystem>.\n=item Handle allowable filename issues (e.g. unicode) on filesystems that don't support them.\n=item Allow multiple distributions with the same name, but with different C<ver> and/or C<auth> and/or C<api> values, to be installed and separately accessible in a single repository.\n=item Enable faster module loading by providing module precompilation.\n\nBecause of the internal storage format the usual way to add a distribution is not by copying\nfiles but by calling L<CompUnit::Repository::Installation#method_install|/type/CompUnit::Repository::Installation#method_install>.\n\n=head1 Methods\n\n=head2 method install\n\n    method install(Distribution $distribution, Bool :$force)\n\nCopies modules into a special location so that they can be loaded afterwards.\n\nC<:$force> will allow installing over an existing distribution that has the same C<name>,\nC<auth>, C<api>, and C<ver>. Otherwise such a situation will result in L<C<Failure>|/type/Failure>.\n\n    my $inst-repo = CompUnit::RepositoryRegistry.repository-for-name(\"site\");\n    my $dist = Distribution::Path.new(...);\n    $inst-repo.install($dist);\n\n=head2 method uninstall\n\n    method uninstall(Distribution $distribution)\n\nRemoves the C<$distribution> from the repository. C<$distribution> should be obtained from\nthe repository it is being removed from:\n\n    my $inst-repo = CompUnit::RepositoryRegistry.repository-for-name(\"site\");\n    my $dist = $inst-repo.candidates(\"Acme::Unused\").head;\n    $inst-repo.uninstall($dist);\n\n=head2 method candidates\n\n    multi method candidates(Str:D $name, :$auth, :$ver, :$api)\n    multi method candidates(CompUnit::DependencySpecification $spec)\n\nReturn all distributions that contain a module matching the specified C<$name>, C<auth>,\nC<ver>, and C<api>.\n\n    my $inst-repo-path = CompUnit::RepositoryRegistry.repository-for-name(\"perl\").prefix;\n    my $inst-repo = CompUnit::Repository::Installation.new(prefix => $inst-repo-path);\n    my $dist = $inst-repo.candidates(\"Test\").head;\n    say \"Test version: \" ~ $dist.meta<ver>; # OUTPUT: «6.d␤»\n\n=head2 method files\n\n    multi method files(Str:D $name, :$auth, :$ver, :$api)\n    multi method files(CompUnit::DependencySpecification $spec)\n\nReturn all distributions that match the specified C<auth> C<ver> and C<api>, and\ncontains a non-module file matching the specified C<$name>.\n\n    # assuming Zef is installed to the default location...\n    my $repo = CompUnit::RepositoryRegistry.repository-for-name(\"site\");\n\n    say $repo.files('bin/zef', :ver<419.0+>).head.<name>              // \"Nada\"; # OUTPUT: «Nada␤»\n    say $repo.files('resources/config.txt', :ver<419.0+>).head.<name> // \"Nada\"; # OUTPUT: «Nada␤»\n\n    say $repo.files('bin/zef', :ver<0.4.0+>).head.<name>;                        # OUTPUT: «zef␤»\n    say $repo.files('resources/config.txt', :ver<0.4.0+>).head.<name>;           # OUTPUT: «zef␤»\n\n=head2 method resolve\n\n    method resolve(CompUnit::DependencySpecification $spec --> CompUnit:D)\n\nReturns a L<C<CompUnit>|/type/CompUnit> mapped to the highest version distribution matching C<$spec> from\nthe first repository in the repository chain that contains any version of a distribution\nmatching C<$spec>.\n\n=head2 method need\n\n=for code :method :preamble<method !precomp-stores() {}; method precomp-repository() {}>\nmethod need(\n    CompUnit::DependencySpecification $spec,\n    CompUnit::PrecompilationRepository $precomp = self.precomp-repository(),\n    CompUnit::PrecompilationStore :@precomp-stores = self!precomp-stores(),\n    --> CompUnit:D)\n\nLoads and returns a L<C<CompUnit>|/type/CompUnit> which is mapped to the highest version distribution\nmatching C<$spec> from the first repository in the repository chain that contains\nany version of a distribution matching C<$spec>.\n\n=head2 method load\n\n    method load(IO::Path:D $file --> CompUnit:D)\n\nLoad the C<$file> and return a L<C<CompUnit>|/type/CompUnit> object representing it.\n\n=head2 method loaded\n\n    method loaded(--> Iterable:D)\n\nReturns all L<C<CompUnit>|/type/CompUnit>s this repository has loaded.\n\n=head2 method short-id\n\n    method short-id()\n\nReturns the repo short-id, which for this repository is C<inst>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/CompUnit/Repository/Unknown.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class CompUnit::Repository::Unknown\n\n=SUBTITLE CompUnit::Repository::Unknown\n\n=for code :preamble<role CompUnit::Repository {};>\nclass CompUnit::Repository::FileSystem\n    does CompUnit::Repository\n    { }\n\nA L<C<CompUnit::Repository>|/type/CompUnit::Repository> placeholder that is used\nwhen the type of the Repository is unknown.\nin development situations. This is what is used by C<-I .> / C<-I lib> (which are\nactually C<-I file#.> and C<-I file#lib>) or C<use lib \".\"> / C<use lib \"lib\">.\nUnlike L<C<CompUnit::Repository::Installation>|/type/CompUnit::Repository::Installation>, this represents a single distribution.\n\n=head1 Methods\n\n=head2 method need\n\n=for code :method :preamble<method !precomp-stores() {...};>\nmethod need(\n    CompUnit::DependencySpecification $spec,\n    CompUnit::PrecompilationRepository $precomp?,\n    CompUnit::PrecompilationStore :@precomp-stores\n    --> CompUnit:D)\n\nThis class passes any requests up the repository chain, and does not resolve them itself.\n\n=head2 method loaded\n\n    method loaded(--> Iterable:D)\n\nAlways returns an empty L<C<Iterable>|/type/Iterable>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/CompUnit/Repository.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"domain-specific\")\n\n=TITLE role CompUnit::Repository\n\n=SUBTITLE CompUnit::Repository\n\nThe C<CompUnit::Repository> role defines the interface of the implementation\nof CompUnit::Repositories such as L<C<CompUnit::Repository::Installation>|/type/CompUnit::Repository::Installation>\nand L<C<CompUnit::Repository::FileSystem>|/type/CompUnit::Repository::FileSystem>.\n\n=head1 Methods\n\n=head2 method resolve\n\n    method resolve(CompUnit::DependencySpecification $spec --> CompUnit:D)\n\nReturns a L<C<CompUnit>|/type/CompUnit> mapped to the highest version distribution matching\nC<$spec> from the first repository in the repository chain that contains any\nversion of a distribution matching C<$spec>.\n\n=head2 method need\n\nLoads and returns a L<C<CompUnit>|/type/CompUnit> which is mapped to the highest version\ndistribution matching C<$spec> from the first repository in the repository\nchain that contains any version of a distribution matching C<$spec>.\n\n=head2 method load\n\n    method load(IO::Path:D $file --> CompUnit:D)\n\nLoad the C<$file> and return a L<C<CompUnit>|/type/CompUnit> object representing it.\n\n=head2 method loaded\n\n    method loaded(--> Iterable:D)\n\nReturns all L<C<CompUnit>|/type/CompUnit>s this repository has loaded.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/CompUnit.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class CompUnit\n\n=SUBTITLE CompUnit\n\n    class CompUnit {}\n\nThe C<CompUnit> represents the meta-information about a compilation unit.\nThis usually relates to source code that resides in a file on a filesystem,\nrather than code that is executed using an C<EVAL> statement.\n\n=head1 Methods\n\n=head2 method auth\n\n    method auth(--> Str:D)\n\nReturns the authority information with which the C<CompUnit> object was created\n(if any).\n\n=head2 method distribution\n\n    method distribution(--> Distribution:D)\n\nReturns the L<C<Distribution>|/type/Distribution> object with which the C<CompUnit> object was\ncreated (if any).\n\n=head2 method from\n\n    method from(--> Str:D)\n\nReturns the name of the language with which the C<CompUnit> object was created\n(if any). It will be C<Raku> by default.\n\n=head2 method precompiled\n\n    method precompiled(--> Bool:D)\n\nReturns whether the C<CompUnit> object originated from a precompiled source.\n\n=head2 method repo\n\n    method repo(--> CompUnit::Repository:D)\n\nReturns the L<C<CompUnit::Repository>|/type/CompUnit::Repository> object with which the C<CompUnit> object\nwas created.\n\n=head2 method repo-id\n\n    method repo-id(--> Str:D)\n\nReturns the identification string with which the C<CompUnit> object can be\nidentified in the associated L<repo|#method_repo>.\n\n=head2 method short-name\n\n    method short-name(--> Str:D)\n\nReturns The short name with which the C<CompUnit> object was created (if any).\n\n=head2 method version\n\n    method version(--> Version:D)\n\nReturns the version information with which the C<CompUnit> object was created\n(if any).\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Compiler.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Compiler\n\n=SUBTITLE Information related to the compiler that is being used\n\n    class Compiler does Systemic {}\n\nBuilt-in class for providing compiler related information.  Usually accessed\nthrough the C<compiler> attribute of the\nL«C<$*RAKU>|/language/variables#Dynamic_variables» dynamic variable.\n\n    say $*RAKU.compiler; # OUTPUT: «rakudo (2020.02.16.g.28.bd.4247.a)␤»\n\nB<Note>: Before Rakudo release 2020.1 this was only available through\nthe C<compiler> attribute of the C<$*PERL> dynamic variable. Since\nRakudo release 2020.1 this is available through both the C<$*RAKU>\nand the C<$*PERL> variables.\n\n=head1 Methods\n\n=head2 method id\n\nReturns a unique identifier, a long hexadecimal string\n\n=head2 method release\n\nIt's empty, but it might contain the release number for specific releases.\n\n=head2 method codename\n\nIt's empty, but it might contain the codename for specific releases.\n\n\n=head2 method backend\n\n    method backend()\n\nSince Rakudo release 2020.02, returns the name of the compiler's backend.\n\n\n=head2 method build-date\n\n    method build-date()\n\nUp to Rakudo release 2019.03.1, it returned the date when it was built.\n\n    say $*PERL.compiler.build-date; # OUTPUT: «2018-05-05T21:49:43Z␤»\n\n=head2 method verbose-config\n\n    method verbose-config(:$say)\n\nIf C<$say> is C<True>, it prints the different items included in the\nconfiguration of the compiler; if it is not, returns a L<C<Hash>|/type/Hash> with the same\ninformation.\n\n    say $*RAKU.compiler.verbose-config; # OUTPUT: «distro::auth=https://www.opensuse.org/␤distro::desc=2018-05-06T09:19:17.571307+02:00␤» ... And the rest of the configuration\n\n\nSee Also: L<C<Systemic>|/type/Systemic>\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Complex.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Complex\n\n=SUBTITLE Complex number\n\n    class Complex is Cool does Numeric {}\n\nRepresents a number in the complex plane.\n\nComplex objects are immutable.\n\n=head1 Operators\n\n=head2 postfix i\n\nAdding a trailing C<i> to a number literal makes it a Complex, for example:\n\n    say 2i;     # same as Complex.new(0, 2);\n    say 1-2e3i; # same as Complex.new(1, -2e3);\n\n=head1 Methods\n\n=head2 method new\n\n    multi method new(Real $re, Real $im --> Complex:D)\n\nCreates a new C<Complex> object from real and imaginary parts.\n\n    my $complex = Complex.new(1, 1);\n    say $complex;    # OUTPUT: «1+1i␤»\n\nWhen created without arguments, both parts are considered to be zero.\n\n    say Complex.new; # OUTPUT: «0+0i␤»\n\n=head2 method re\n\n    method re(Complex:D: --> Real:D)\n\nReturns the real part of the complex number.\n\n    say (3+5i).re;    # OUTPUT: «3␤»\n\n=head2 method im\n\n    method im(Complex:D: --> Real:D)\n\nReturns the imaginary part of the complex number.\n\n    say (3+5i).im;    # OUTPUT: «5␤»\n\n=head2 method reals\n\n    method reals(Complex:D: --> Positional:D)\n\nReturns a two-element list containing the real and imaginary parts for this value.\n\n    say (3+5i).reals;    # OUTPUT: «(3 5)␤»\n\n=head2 method isNaN\n\n    method isNaN(Complex:D: --> Bool:D)\n\nReturns true if the real or imaginary part is L<C<NaN>|/type/Num#NaN> (not a number).\n\n    say (NaN+5i).isNaN; # OUTPUT: «True␤»\n    say (7+5i).isNaN;   # OUTPUT: «False␤»\n\n=head2 method polar\n\n    method polar(Complex:D: --> Positional:D)\n\nReturns a two-element list of the polar coordinates for this value,\ni.e. magnitude and angle in radians.\n\n    say (10+7i).polar; # OUTPUT: «(12.2065556157337 0.610725964389209)␤»\n\n=head2 method floor\n\n    method floor(Complex:D: --> Complex:D)\n\nReturns C<self.re.floor + self.im.floor>. That is, each of the real and\nimaginary parts is rounded to the highest integer not greater than\nthe value of that part.\n\n    say (1.2-3.8i).floor;           # OUTPUT: «1-4i␤»\n\n=head2 method ceiling\n\n    method ceiling(Complex:D: --> Complex:D)\n\nReturns C<self.re.ceiling + self.im.ceiling>. That is, each of the real and\nimaginary parts is rounded to the lowest integer not less than the value\nof that part.\n\n    say (1.2-3.8i).ceiling;         # OUTPUT: «2-3i␤»\n\n=head2 routine sign\n\n    method sign(Complex:D: --> Complex:D)\n    multi  sign(Complex:D $z --> Complex:D)\n\nReturns C<0i> if the absolute value of the complex number is 0.  Otherwise\nreturns the complex number divided by its absolute value (the unit\ncomplex number in the same direction as $z).\n\nAvailable as of 6.e language version (early implementation exists in Rakudo\ncompiler 2023.02+).\n\n=head2 method round\n\n    multi method round(Complex:D: --> Complex:D)\n    multi method round(Complex:D: Real() $scale --> Complex:D)\n\nWith no arguments, rounds both the real and imaginary parts to the nearest\ninteger and returns a new C<Complex> number. If C<$scale> is given, rounds both\nparts of the invocant to the nearest multiple of C<$scale>. Uses the same\nalgorithm as L<Real.round|/type/Real#method_round> on each part of the number.\n\n    say (1.2-3.8i).round;           # OUTPUT: «1-4i␤»\n    say (1.256-3.875i).round(0.1);  # OUTPUT: «1.3-3.9i␤»\n\n=head2 method truncate\n\n    method truncate(Complex:D: --> Complex:D)\n\nRemoves the fractional part of both the real and imaginary parts of the\nnumber, using L<Real.truncate|/type/Real#method_truncate>, and returns the result as a new C<Complex>.\n\n    say (1.2-3.8i).truncate;        # OUTPUT: «1-3i␤»\n\n=head2 routine abs\n\n    method abs(Complex:D: --> Num:D)\n    multi  abs(Complex:D $z --> Num:D)\n\nReturns the absolute value of the invocant (or the argument in sub form).\nFor a given complex number C<$z> the absolute value C<|$z|> is defined as\nC<sqrt($z.re * $z.re + $z.im * $z.im)>.\n\n    say (3+4i).abs;                 # OUTPUT: «5␤»\n                                    # sqrt(3*3 + 4*4) == 5\n\n=head2 method conj\n\n    method conj(Complex:D: --> Complex:D)\n\nReturns the complex conjugate of the invocant (that is, the number with the\nsign of the imaginary part negated).\n\n    say (1-4i).conj;                # OUTPUT: «1+4i␤»\n\n=head2 method sqrt\n\n    method sqrt(Complex:D: --> Complex:D)\n\nReturns the complex square root of the invocant, i.e. the root\nwhere the real part is ≥ 0 and the imaginary part has the same\nsign as the imaginary part of the invocant.\n\n    say (3-4i).sqrt;                # OUTPUT: «2-1i␤»\n    say (-3+4i).sqrt;               # OUTPUT: «1+2i␤»\n\n=head2 method gist\n\n    method gist(Complex:D: --> Str:D)\n\nReturns a string representation of the form \"1+2i\", without internal spaces.\n(Str coercion also returns this.)\n\n    say (1-4i).gist;                # OUTPUT: «1-4i␤»\n\n=head2 method raku\n\n    method raku(Complex:D: --> Str:D)\n\nReturns an implementation-specific string that produces an L<equivalent|/routine/eqv> object\nwhen given to L<EVAL|/routine/EVAL>.\n\n    say (1-3i).raku;                # OUTPUT: «<1-3i>␤»\n\n=head2 method Real\n\n    multi method Real(Complex:D: --> Num:D)\n    multi method Real(Complex:U: --> Num:D)\n\nCoerces the invocant to L<C<Num>|/type/Num>. If the imaginary part isn't L<approximately|/routine/=~=> zero,\ncoercion L<fails|/routine/fail> with L<C<X::Numeric::Real>|/type/X::Numeric::Real>.\n\nThe C<:D> variant returns the result of that coercion. The C<:U> variant issues\na warning about using an uninitialized value in numeric context and then returns value C<0e0>.\n\n=head2 sub infix:<**>\n\n    multi infix:<**>(Complex:D \\a, Complex:D \\b --> Complex:D)\n    multi infix:<**>(Num(Real) \\a, Complex:D \\b --> Complex:D)\n    multi infix:<**>(Complex:D \\a, Num(Real) \\b --> Complex:D)\n\nThe X<exponentiation operator|Infix operators,exponentiation operator> coerces the second argument to C<Complex>\nand calculates the left-hand-side raised to the power of the right-hand side. Since 6.d,\neither argument can be equal to zero.\n\n    say i ** i;   # OUTPUT: «0.20787957635076193+0i␤»\n    say 2 ** i;   # OUTPUT: «0.7692389013639721+0.6389612763136348i␤»\n    say i ** 2;   # OUTPUT: «-1+1.2246467991473532e-16i␤»\n    say 0 ** i;   # OUTPUT: «0+0i␤»\n    say 0i ** 0i; # OUTPUT: «1+0i␤»\n=end pod\n"
  },
  {
    "path": "doc/Type/ComplexStr.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class ComplexStr\n\n=SUBTITLE Dual value complex number and string\n\n    class ComplexStr is Allomorph is Complex {}\n\nC<ComplexStr> is a dual value type, a subclass of both\nL«C<Allomorph>|/type/Allomorph», hence L«C<Str>|/type/Str», and\nL«C<Complex>|/type/Complex».\n\nSee L«C<Allomorph>|/type/Allomorph» for further details.\n\n=begin code\nmy $complex-str = <42+0i>;\nsay $complex-str.^name;             # OUTPUT: «ComplexStr␤»\n\nmy Complex $complex = $complex-str; # OK!\nmy Str     $str     = $complex-str; # OK!\n\n# ∈ operator cares about object identity\nsay 42+0i ∈ <42+0i  55  1>;         # OUTPUT: «False␤»\n=end code\n\n=head1 Methods\n\n=head2 method new\n\n    method new(Complex $i, Str $s)\n\nThe constructor requires both the L<C<Complex>|/type/Complex> and the L<C<Str>|/type/Str> value, when constructing one\ndirectly the values can be whatever is required:\n\n    my $f = ComplexStr.new(42+0i, \"forty two (but complicated)\");\n    say +$f; # OUTPUT: «42+0i␤»\n    say ~$f; # OUTPUT: «\"forty two (but complicated)\"␤»\n\n=head2 method Capture\n\n    method Capture(ComplexStr:D: --> Capture:D)\n\nEquivalent to L«C<Mu.Capture>|/type/Mu#method_Capture».\n\n=head2 method Complex\n\n    method Complex\n\nReturns the L<C<Complex>|/type/Complex> value of the C<ComplexStr>.\n\n=head2 method Numeric\n\n    multi method Numeric(ComplexStr:D: --> Complex:D)\n    multi method Numeric(ComplexStr:U: --> Complex:D)\n\nThe C<:D> variant returns the numeric portion of the invocant. The C<:U> variant issues\na warning about using an uninitialized value in numeric context and then returns value C«<0+0i>».\n\n=head2 method Real\n\n    multi method Real(ComplexStr:D: --> Num:D)\n    multi method Real(ComplexStr:U: --> Num:D)\n\nCoerces the numeric portion of the invocant to L<C<Num>|/type/Num>. If the imaginary part\nisn't L<approximately|/language/operators#infix_≅> zero,\ncoercion L<fails|/routine/fail> with L<C<X::Numeric::Real>|/type/X::Numeric::Real>.\n\nThe C<:D> variant returns the result of that coercion. The C<:U> variant issues\na warning about using an uninitialized value in numeric context and then returns value C<0e0>.\n\n=head1 Operators\n\n=head2 infix C«===»\n\n    multi infix:<===>(ComplexStr:D $a, ComplexStr:D $b)\n\nC<ComplexStr> Value identity operator. Returns C<True> if the L<C<Complex>|/type/Complex>\nvalues of C<$a> and C<$b> are L<identical|/routine/===> and their L<C<Str>|/type/Str>\nvalues are also L<identical|/routine/===>. Returns C<False> otherwise.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Cool.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Cool\n\n=SUBTITLE Object that can be treated as both a string and number\n\n    class Cool is Any { }\n\nC<Cool>, also known as the B<C>onvenient B<OO> B<L>oop, is a base class employed\nby a number of built-in classes whose instances can be meaningfully coerced to a\nstring and a number. For example, an L<C<Array>|/type/Array> can be used in\nmathematical operations, where its numerical representation is the number of\nelements it contains. At the same time, it can be concatenated to a string,\nwhere its stringy representation is all of its elements L<joined|/routine/join>\nby a space. Because L<C<Array>|/type/Array> is C<Cool>, the appropriate\ncoercion happens automatically.\n\nMethods in C<Cool> coerce the invocant to a more specific type, and then call\nthe same method on that type. For example both L<C<Int>|/type/Int> and\nL<C<Str>|/type/Str> inherit from C<Cool>, and calling method C<substr> on an L<C<Int>|/type/Int>\nconverts the integer to L<C<Str>|/type/Str> first.\n\n    123.substr(1, 1);   # '2', same as 123.Str.substr(1, 1)\n\nSeveral built-in types inherit from C<Cool>. See the L<Type Graph|#typegraphrelations> below\nfor a snapshot.\n\nThe following table summarizes the methods that C<Cool> provides, and\nwhat type they coerce to:\n\n=begin table\n\n    method          coercion type\n\n    abs             Numeric\n    conj            Numeric\n    sqrt            Numeric\n    sign            Real\n    rand            Numeric\n    sin             Numeric\n    asin            Numeric\n    cos             Numeric\n    acos            Numeric\n    tan             Numeric\n    tanh            Numeric\n    atan            Numeric\n    atan2           Numeric\n    atanh           Numeric\n    sec             Numeric\n    asec            Numeric\n    cosec           Numeric\n    acosec          Numeric\n    cotan           Numeric\n    cotanh          Numeric\n    acotan          Numeric\n    sinh            Numeric\n    asinh           Numeric\n    cosh            Numeric\n    acosh           Numeric\n    sech            Numeric\n    asech           Numeric\n    cosech          Numeric\n    acosech         Numeric\n    acotanh         Numeric\n    cis             Numeric\n    log             Numeric\n    exp             Numeric\n    roots           Numeric\n    log10           Numeric\n    log2            Numeric\n    unpolar         Numeric\n    round           Numeric\n    floor           Numeric\n    ceiling         Numeric\n    truncate        Numeric\n    chr             Int\n    ord             Str\n    chars           Str\n    fmt             Str\n    uniname         Str\n    uninames        Seq\n    unival          Str\n    univals         Str\n    uniprop         Str\n    unimatch        Str\n    uc              Str\n    lc              Str\n    fc              Str\n    tc              Str\n    tclc            Str\n    flip            Str\n    trans           Str\n    contains        Str\n    index           Str\n    rindex          Str\n    ords            Str\n    split           Str\n    match           Str\n    comb            Str\n    subst           Str\n    sprintf         Str\n    printf          Str\n    samecase        Str\n    trim            Str\n    trim-leading    Str\n    trim-trailing   Str\n    EVAL            Str\n    chomp           Str\n    chop            Str\n    codes           Str\n    Complex         Numeric\n    FatRat          Numeric\n    Int             Numeric\n    Num             Numeric\n    Rat             Numeric\n    Real            Numeric\n    UInt            Numeric\n\n=end table\n\n=head1 Methods\n\n=head2 routine abs\n\n    sub abs(Numeric() $x)\n    method abs()\n\nCoerces the invocant (or in the sub form, the argument) to\nL<C<Numeric>|/type/Numeric> and returns the absolute value (that is, a\nnon-negative number).\n\n    say (-2).abs;       # OUTPUT: «2␤»\n    say abs \"6+8i\";     # OUTPUT: «10␤»\n\n=head2 method conj\n\n    method conj()\n\nCoerces the invocant to L<C<Numeric>|/type/Numeric> and returns the\nL<C<Complex>|/type/Complex> conjugate (that is, the number with the sign of the\nimaginary part negated).\n\n    say \"1+2i\".conj;        # OUTPUT: «1-2i␤»\n\n=head2 method EVAL\n\n=for code :method\nmethod EVAL(*%_)\n\nIt calls the L<subroutine form|/type/independent-routines#routine_EVAL> with the\ninvocant as the first argument, C<$code>, passing along named args, if any.\n\n\n=head2 routine sqrt\n\n    sub sqrt(Numeric(Cool) $x)\n    method sqrt()\n\nCoerces the invocant to L<C<Numeric>|/type/Numeric> (or in the sub form, the\nargument) and returns the square root, that is, a number that, when\nmultiplied with itself, produces the original number.\n\n    say 4.sqrt;             # OUTPUT: «2␤»\n    say sqrt(2);            # OUTPUT: «1.4142135623731␤»\n\nReturns C<NaN> for negative arguments.  As of 6.e language version (early\nimplementation exists in Rakudo compiler 2023.02+), will return a\nL<C<Complex>|/type/Complex> value for negative arguments.\n\n    say sqrt(-1);           # OUTPUT: «0+1i␤»\n\n=head2 method sign\n\n    method sign()\n\nCoerces the invocant to L<C<Real>|/type/Real> and returns its sign, that\nis, 0 if the number is 0, 1 for positive and -1 for negative values.\n\n    say 6.sign;             # OUTPUT: «1␤»\n    say (-6).sign;          # OUTPUT: «-1␤»\n    say \"0\".sign;           # OUTPUT: «0␤»\n\n=head2 method rand\n\n    method rand()\n\nCoerces the invocant to L<C<Num>|/type/Num> and returns a pseudo-random value\nbetween zero and the number.\n\n    say 1e5.rand;           # OUTPUT: «33128.495184283␤»\n\n=head2 routine sin\n\n    sub sin(Numeric(Cool))\n    method sin()\n\nCoerces the invocant (or in the sub form, the argument) to L<C<Numeric>|/type/Numeric>, interprets it as radians,\nreturns its L<sine|https://en.wikipedia.org/wiki/Sine>.\n\n    say sin(0);             # OUTPUT: «0␤»\n    say sin(pi/4);          # OUTPUT: «0.707106781186547␤»\n    say sin(pi/2);          # OUTPUT: «1␤»\n\nNote that Raku is no computer algebra system, so C<sin(pi)> typically does\nnot produce an exact 0, but rather a very small L<C<Num>|/type/Num>.\n\n=head2 routine asin\n\n    sub asin(Numeric(Cool))\n    method asin()\n\nCoerces the invocant (or in the sub form, the argument) to\nL<C<Numeric>|/type/Numeric>, and returns its\nL<arc-sine|https://en.wikipedia.org/wiki/Inverse_trigonometric_functions> in\nradians.\n\n    say 0.1.asin;               # OUTPUT: «0.10016742116156␤»\n    say asin(0.1);              # OUTPUT: «0.10016742116156␤»\n\n=head2 routine cos\n\n    sub cos(Numeric(Cool))\n    method cos()\n\nCoerces the invocant (or in sub form, the argument) to L<C<Numeric>|/type/Numeric>,\ninterprets it as radians, returns its\nL<cosine|https://en.wikipedia.org/wiki/Cosine>.\n\n    say 0.cos;                  # OUTPUT: «1␤»\n    say pi.cos;                 # OUTPUT: «-1␤»\n    say cos(pi/2);              # OUTPUT: «6.12323399573677e-17␤»\n\n=head2 routine acos\n\n    sub acos(Numeric(Cool))\n    method acos()\n\nCoerces the invocant (or in sub form, the argument) to L<C<Numeric>|/type/Numeric>, and returns its\nL<arc-cosine|https://en.wikipedia.org/wiki/Inverse_trigonometric_functions> in\nradians.\n\n    say 1.acos;                 # OUTPUT: «0␤»\n    say acos(-1);               # OUTPUT: «3.14159265358979␤»\n\n=head2 routine tan\n\n    sub tan(Numeric(Cool))\n    method tan()\n\nCoerces the invocant (or in sub form, the argument) to L<C<Numeric>|/type/Numeric>, interprets it as radians,\nreturns its L<tangent|https://en.wikipedia.org/wiki/Tangent>.\n\n    say tan(3);                 # OUTPUT: «-0.142546543074278␤»\n    say 3.tan;                  # OUTPUT: «-0.142546543074278␤»\n\n=head2 routine atan\n\n    sub atan(Numeric(Cool))\n    method atan()\n\nCoerces the invocant (or in sub form, the argument) to L<C<Numeric>|/type/Numeric>, and returns its\nL<arc-tangent|https://en.wikipedia.org/wiki/Inverse_trigonometric_functions> in\nradians.\n\n    say atan(3);                # OUTPUT: «1.24904577239825␤»\n    say 3.atan;                 # OUTPUT: «1.24904577239825␤»\n\n=head2 routine atan2\n\n    sub atan2($y, $x = 1e0)\n    method atan2($x = 1e0)\n\nThe sub should usually be written with two arguments for clarity as it\nis seen in other languages and in mathematical texts, but the\nsingle-argument form is available; its result will always match that of\nL<atan|/routine/atan>.\n\n    say atan2 3, 1;             # OUTPUT: «1.2490457723982544␤»\n    say atan2 3;                # OUTPUT: «1.2490457723982544␤»\n    say atan2 ⅔, ⅓;             # OUTPUT: «1.1071487177940904␤»\n\nThe method coerces self and its single argument to\nL<C<Numeric>|/type/Numeric>, using them to compute the two-argument\nL<arc-tangent|https://en.wikipedia.org/wiki/Atan2> in radians.\n\n    say 3.atan2;                # OUTPUT: «1.24904577239825␤»\n    say ⅔.atan2(⅓);             # OUTPUT: «1.1071487177940904␤»\n\nThe $x argument in either the method or the sub defaults to 1 so, in both\nsingle-argument cases, the function will return the angle θ in radians\nbetween the x-axis and a vector that goes from the origin to the point\n(3, 1).\n\n=head2 routine sec\n\n    sub sec(Numeric(Cool))\n    method sec()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>, interprets it as radians,\nreturns its L<secant|https://en.wikipedia.org/wiki/Trigonometric_functions#Reciprocal_functions>,\nthat is, the reciprocal of its cosine.\n\n    say 45.sec;                 # OUTPUT: «1.90359440740442␤»\n    say sec(45);                # OUTPUT: «1.90359440740442␤»\n\n=head2 routine asec\n\n    sub asec(Numeric(Cool))\n    method asec()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>,\nand returns its\nL<arc-secant|https://en.wikipedia.org/wiki/Inverse_trigonometric_functions> in\nradians.\n\n    say 1.asec;                 # OUTPUT: «0␤»\n    say sqrt(2).asec;           # OUTPUT: «0.785398163397448␤»\n\n=head2 routine cosec\n\n    sub cosec(Numeric(Cool))\n    method cosec()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>,\ninterprets it as radians, returns its\nL<cosecant|https://en.wikipedia.org/wiki/Trigonometric_functions#Reciprocal_functions>,\nthat is, the reciprocal of its sine.\n\n    say 0.45.cosec;             # OUTPUT: «2.29903273150897␤»\n    say cosec(0.45);            # OUTPUT: «2.29903273150897␤»\n\n=head2 routine acosec\n\n    sub acosec(Numeric(Cool))\n    method acosec()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>,\nand returns its\nL<arc-cosecant|https://en.wikipedia.org/wiki/Inverse_trigonometric_functions> in\nradians.\n\n    say 45.acosec;              # OUTPUT: «0.0222240516182672␤»\n    say acosec(45)              # OUTPUT: «0.0222240516182672␤»\n\n=head2 routine cotan\n\n    sub cotan(Numeric(Cool))\n    method cotan()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>,\ninterprets it as radians, returns its\nL<cotangent|https://en.wikipedia.org/wiki/Trigonometric_functions#Reciprocal_functions>,\nthat is, the reciprocal of its tangent.\n\n    say 45.cotan;               # OUTPUT: «0.617369623783555␤»\n    say cotan(45);              # OUTPUT: «0.617369623783555␤»\n\n=head2 routine acotan\n\n    sub acotan(Numeric(Cool))\n    method acotan()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>,\nand returns its\nL<arc-cotangent|https://en.wikipedia.org/wiki/Inverse_trigonometric_functions>\nin radians.\n\n    say 45.acotan;              # OUTPUT: «0.0222185653267191␤»\n    say acotan(45)              # OUTPUT: «0.0222185653267191␤»\n\n=head2 routine sinh\n\n    sub sinh(Numeric(Cool))\n    method sinh()\n\nCoerces the invocant (or in method form, its argument) to\nL<C<Numeric>|/type/Numeric>, and returns its\nL<Sine hyperbolicus|https://en.wikipedia.org/wiki/Hyperbolic_function>.\n\n    say 1.sinh;                 # OUTPUT: «1.1752011936438␤»\n    say sinh(1);                # OUTPUT: «1.1752011936438␤»\n\n=head2 routine asinh\n\n    sub asinh(Numeric(Cool))\n    method asinh()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>, and returns its\nL<Inverse Sine hyperbolicus|https://en.wikipedia.org/wiki/Inverse_hyperbolic_function>.\n\n    say 1.asinh;                # OUTPUT: «0.881373587019543␤»\n    say asinh(1);               # OUTPUT: «0.881373587019543␤»\n\n=head2 routine cosh\n\n    sub cosh(Numeric(Cool))\n    method cosh()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>, and returns its\nL<Cosine hyperbolicus|https://en.wikipedia.org/wiki/Hyperbolic_function>.\n\n    say cosh(0.5);              # OUTPUT: «1.12762596520638␤»\n\n=head2 routine acosh\n\n    sub acosh(Numeric(Cool))\n    method acosh()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>, and returns its\nL<Inverse Cosine hyperbolicus|https://en.wikipedia.org/wiki/Inverse_hyperbolic_function>.\n\n    say acosh(45);              # OUTPUT: «4.4996861906715␤»\n\n=head2 routine tanh\n\n    sub tanh(Numeric(Cool))\n    method tanh()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>, interprets it as\nradians and returns its L<Tangent hyperbolicus|https://en.wikipedia.org/wiki/Hyperbolic_function>.\n\n    say tanh(0.5);              # OUTPUT: «0.46211715726001␤»\n    say tanh(atanh(0.5));       # OUTPUT: «0.5␤»\n\n=head2 routine atanh\n\n    sub atanh(Numeric(Cool))\n    method atanh()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>, and returns its\nL<Inverse tangent hyperbolicus|https://en.wikipedia.org/wiki/Inverse_hyperbolic_function>.\n\n    say atanh(0.5);             # OUTPUT: «0.549306144334055␤»\n\n=head2 routine sech\n\n    sub sech(Numeric(Cool))\n    method sech()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>, and returns its\nL<Secant hyperbolicus|https://en.wikipedia.org/wiki/Hyperbolic_function>.\n\n    say 0.sech;                 # OUTPUT: «1␤»\n\n=head2 routine asech\n\n    sub asech(Numeric(Cool))\n    method asech()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>, and returns its\nL<Inverse hyperbolic secant|https://en.wikipedia.org/wiki/Hyperbolic_function>.\n\n    say 0.8.asech;              # OUTPUT: «0.693147180559945␤»\n\n=head2 routine cosech\n\n    sub cosech(Numeric(Cool))\n    method cosech()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>, and returns its\nL<Hyperbolic cosecant|https://en.wikipedia.org/wiki/Hyperbolic_function>.\n\n    say cosech(pi/2);           # OUTPUT: «0.434537208094696␤»\n\n=head2 routine acosech\n\n    sub acosech(Numeric(Cool))\n    method acosech()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>, and returns its\nL<Inverse hyperbolic cosecant|https://en.wikipedia.org/wiki/Inverse_hyperbolic_function>.\n\n    say acosech(4.5);           # OUTPUT: «0.220432720979802␤»\n\n=head2 routine cotanh\n\n    sub cotanh(Numeric(Cool))\n    method cotanh()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>, and returns its\nL<Hyperbolic cotangent|https://en.wikipedia.org/wiki/Hyperbolic_function>.\n\n    say cotanh(pi);             # OUTPUT: «1.00374187319732␤»\n\n=head2 routine acotanh\n\n    sub acotanh(Numeric(Cool))\n    method acotanh()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>, and returns its\nL<Inverse hyperbolic cotangent|https://en.wikipedia.org/wiki/Inverse_hyperbolic_function>.\n\n    say acotanh(2.5);           # OUTPUT: «0.423648930193602␤»\n\n=head2 routine cis\n\n    sub cis(Numeric(Cool))\n    method cis()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>, and returns\nL<cos(argument) + i*sin(argument)|https://en.wikipedia.org/wiki/Cis_%28mathematics%29>.\n\n    say cis(pi/4);              # OUTPUT: «0.707106781186548+0.707106781186547i␤»\n\n=head2 routine log\n\n    multi        log(Numeric(Cool) $number, Numeric(Cool) $base?)\n    multi method log(Cool:D: Cool:D $base?)\n\nCoerces the arguments (including the invocant in the method form) to\nL<C<Numeric>|/type/Numeric>, and returns its\nL<Logarithm|https://en.wikipedia.org/wiki/Logarithm> to base C<$base>, or to\nbase C<e> (Euler's Number) if no base was supplied\n(L<Natural logarithm|https://en.wikipedia.org/wiki/Natural_logarithm>).\nThrows an exception if C<$base> is C<1>.\n\n    say (e*e).log;              # OUTPUT: «2␤»\n\nReturns C<NaN> for negative arguments.  As of 6.e language version (early\nimplementation exists in Rakudo compiler 2023.02+), will return a\nL<C<Complex>|/type/Complex> value for negative arguments.\n\n=head2 routine log10\n\n    multi method log10()\n    multi        log10(Numeric $x)\n    multi        log10(Cool    $x)\n\nCoerces the invocant (or in the sub form, the argument) to\nL<C<Numeric>|/type/Numeric> (or uses it directly if it's already in that form), and\nreturns its L<Logarithm|https://en.wikipedia.org/wiki/Logarithm> in base 10,\nthat is, a number that approximately produces the original number when 10 is\nraised to its power. Returns C<-Inf> for C<0>.\n\n    say log10(1001);            # OUTPUT: «3.00043407747932␤»\n\nReturns C<NaN> for negative arguments.  As of 6.e language version (early\nimplementation exists in Rakudo compiler 2023.02+), will return a\nL<C<Complex>|/type/Complex> value for negative arguments.\n\n\n=head2 routine log2\n\n    multi method log2()\n    multi        log2(Numeric $x)\n    multi        log2(Cool    $x)\n\nCoerces the invocant to L<C<Numeric>|/type/Numeric>, and returns its\nL<Logarithm|https://en.wikipedia.org/wiki/Logarithm> in base 2, that is, a\nnumber that approximately (due to computer precision limitations) produces the\noriginal number when 2 is raised to its power. Returns C<-Inf> for C<0>.\n\n    say log2(5);            # OUTPUT: «2.321928094887362␤»\n    say \"4\".log2;           # OUTPUT: «2␤»\n    say 4.log2;             # OUTPUT: «2␤»\n\nReturns C<NaN> for negative arguments.  As of 6.e language version (early\nimplementation exists in Rakudo compiler 2023.02+), will return a\nL<C<Complex>|/type/Complex> value for negative arguments.\n\n=head2 routine exp\n\n    multi        exp(Cool:D $pow, Cool:D $base?)\n    multi method exp(Cool:D: Cool:D $base?)\n\nCoerces the arguments (including the invocant in the method from) to L<C<Numeric>|/type/Numeric>, and returns C<$base>\nraised to the power of the first number. If no C<$base> is supplied, C<e> (Euler's\nNumber) is used.\n\n    say 0.exp;      # OUTPUT: «1␤»\n    say 1.exp;      # OUTPUT: «2.71828182845905␤»\n    say 10.exp;     # OUTPUT: «22026.4657948067␤»\n\n=head2 method unpolar\n\n    method unpolar(Numeric(Cool))\n\nCoerces the arguments (including the invocant in the method form) to L<C<Numeric>|/type/Numeric>, and returns\na complex number from the given polar coordinates. The invocant (or the first argument in sub form) is the magnitude while\nthe argument (i.e. the second argument in sub form) is the angle. The angle is assumed to be in radians.\n\n    say sqrt(2).unpolar(pi/4);      # OUTPUT: «1+1i␤»\n\n=head2 routine round\n\n    multi        round(Numeric(Cool), $scale = 1)\n    multi method round(Cool:D: $scale = 1)\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>, and rounds it to the unit of\nC<$scale>. If C<$scale> is 1, rounds to the nearest integer; an arbitrary scale will result in the closest\nmultiple of that number.\n\n    say 1.7.round;          # OUTPUT: «2␤»\n    say 1.07.round(0.1);    # OUTPUT: «1.1␤»\n    say 21.round(10);       # OUTPUT: «20␤»\n    say round(1000, 23.01)  # OUTPUT: «989.43␤»\n\nAlways rounds B<up> if the number is at mid-point:\n\n    say (−.5 ).round;       # OUTPUT: «0␤»\n    say ( .5 ).round;       # OUTPUT: «1␤»\n    say (−.55).round(.1);   # OUTPUT: «-0.5␤»\n    say ( .55).round(.1);   # OUTPUT: «0.6␤»\n\nB<Pay attention> to types when using this method, as ending up with the wrong type may\naffect the precision you seek to achieve. For L<C<Real>|/type/Real> types, the type of the result\nis the type of the argument (L<C<Complex>|/type/Complex> argument gets coerced to L<C<Real>|/type/Real>, ending up a L<C<Num>|/type/Num>).\nIf rounding a L<C<Complex>|/type/Complex>, the result is L<C<Complex>|/type/Complex> as well, regardless of the type of the argument.\n\n    9930972392403501.round(1)      .raku.say; # OUTPUT: «9930972392403501␤»\n    9930972392403501.round(1e0)    .raku.say; # OUTPUT: «9.9309723924035e+15␤»\n    9930972392403501.round(1e0).Int.raku.say; # OUTPUT: «9930972392403500␤»\n\n=head2 routine floor\n\n    multi        floor(Numeric(Cool))\n    multi method floor\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>, and rounds it downwards to\nthe nearest integer.\n\n    say \"1.99\".floor;       # OUTPUT: «1␤»\n    say \"-1.9\".floor;       # OUTPUT: «-2␤»\n    say 0.floor;            # OUTPUT: «0␤»\n\n=head2 method fmt\n\n    method fmt($format = '%s')\n\nUses C<$format> to return a formatted representation of the invocant; equivalent\nto calling L<sprintf|/routine/sprintf> with C<$format> as format and the\ninvocant as the second argument. The C<$format> will be coerced to\nL<C<Stringy>|/type/Stringy> and defaults to C<'%s'>.\n\nFor more information about formats strings, see L<sprintf|/routine/sprintf>.\n\n    say 11.fmt('This Int equals %03d');         # OUTPUT: «This Int equals 011␤»\n    say '16'.fmt('Hexadecimal %x');             # OUTPUT: «Hexadecimal 10␤»\n\n=head2 routine ceiling\n\n    multi        ceiling(Numeric(Cool))\n    multi method ceiling\n\nCoerces the invocant (or in sub form, its argument) to L<C<Numeric>|/type/Numeric>,\nand rounds it upwards to the nearest integer.\n\n    say \"1\".ceiling;        # OUTPUT: «1␤»\n    say \"-0.9\".ceiling;     # OUTPUT: «0␤»\n    say \"42.1\".ceiling;     # OUTPUT: «43␤»\n\n=head2 routine truncate\n\n    multi        truncate(Numeric(Cool))\n    multi method truncate()\n\nCoerces the invocant (or in sub form, its argument) to\nL<C<Numeric>|/type/Numeric>, and rounds it towards zero.\n\n    say 1.2.truncate;       # OUTPUT: «1␤»\n    say truncate -1.2;      # OUTPUT: «-1␤»\n\n=head2 routine ord\n\n    sub ord(Str(Cool))\n    method ord()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Str>|/type/Str>, and\nreturns the L<Unicode code point|https://en.wikipedia.org/wiki/Code_point>\nnumber of the first code point.\n\n    say 'a'.ord;            # OUTPUT: «97␤»\n\nThe inverse operation is L<chr|/routine/chr>.\n\nMnemonic: returns an ordinal number\n\n=head2 method path\n\n    method path(Cool:D: --> IO::Path:D)\n\nB<DEPRECATED>. I<It's been deprecated as of the 6.d version. Will be removed in\nthe next ones.>\n\nStringifies the invocant and converts it to L<C<IO::Path>|/type/IO::Path> object.\nUse the L«C<.IO method>|/routine/IO» instead.\n\n=head2 routine chr\n\n    sub chr(Int(Cool))\n    method chr()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Int>|/type/Int>,\ninterprets it as a\nL<Unicode code points|https://en.wikipedia.org/wiki/Code_point>, and returns a\nL<C<Str>|/type/Str> made of that code point.\n\n    say '65'.chr;       # OUTPUT: «A␤»\n\nThe inverse operation is L<ord|/routine/ord>.\n\nMnemonic: turns an integer into a I<char>acter.\n\n=head2 routine chars\n\n    multi  chars(Cool $x)\n    multi  chars(Str:D $x)\n    multi  chars(str $x --> int)\n    method chars(--> Int:D)\n\nCoerces the invocant (or in sub form, its argument) to L<C<Str>|/type/Str>, and\nreturns the number of characters in the string. Please note that on the JVM, you\ncurrently get codepoints instead of graphemes.\n\n    say 'møp'.chars;    # OUTPUT: «3␤»\n    say 'ã̷̠̬̊'.chars;     # OUTPUT: «1␤»\n    say '👨‍👩‍👧‍👦🏿'.chars;    # OUTPUT: «1␤»\n\nIf the string is native, the number of chars will be also returned as a native\nC<int>.\n\nX<|Syntax,Grapheme>\n\nGraphemes are user visible characters. That is, this is what the user\nthinks of as a “character”.\n\nGraphemes can contain more than one\ncodepoint. Typically the number of graphemes and codepoints differs\nwhen C<Prepend> or C<Extend> characters are involved (also known as\nL<Combining characters|https://en.wikipedia.org/wiki/Combining_character>), but\nthere are many other cases when this may happen. Another example is C<\\c[ZWJ]>\n(L<Zero-width joiner|https://en.wikipedia.org/wiki/Zero-width_joiner>).\n\nYou can check C<Grapheme_Cluster_Break> property of a character in\norder to see how it is going to behave:\n\n    say ‘ã̷̠̬̊’.uniprops(‘Grapheme_Cluster_Break’); # OUTPUT: «(Other Extend Extend Extend Extend)␤»\n    say ‘👨‍👩‍👧‍👦🏿’.uniprops(‘Grapheme_Cluster_Break’); # OUTPUT: «(E_Base_GAZ ZWJ E_Base_GAZ ZWJ E_Base_GAZ ZWJ E_Base_GAZ E_Modifier)␤»\n\nYou can read more about graphemes in the\nL<Unicode Standard|https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries>,\nwhich Raku tightly follows, using a method called L<NFG, normal form graphemes|/language/glossary#NFG> for efficiently representing them.\n\n=head2 routine codes\n\n    sub codes(Str(Cool))\n    method codes()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Str>|/type/Str>, and\nreturns the number of L<Unicode code points|https://en.wikipedia.org/wiki/Code_point>.\n\n    say 'møp'.codes;    # OUTPUT: «3␤»\n\nThe same result will be obtained with\n\n    say +'møp'.ords;    # OUTPUT: «3␤»\n\nL<ords|/routine/ords> first obtains the actual codepoints, so there might be a difference in speed.\n\n=head2 routine flip\n\n    sub flip(Cool $s --> Str:D)\n    method flip()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Str>|/type/Str>, and\nreturns a reversed version.\n\n    say 421.flip;       # OUTPUT: «124␤»\n\n=head2 routine trim\n\n    sub trim(Str(Cool))\n    method trim()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Str>|/type/Str>, and\nreturns the string with both leading and trailing whitespace stripped.\n\n    my $stripped = '  abc '.trim;\n    say \"<$stripped>\";          # OUTPUT: «<abc>␤»\n\n=head2 routine trim-leading\n\n    sub trim-leading(Str(Cool))\n    method trim-leading()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Str>|/type/Str>, and\nreturns the string with leading whitespace stripped.\n\n    my $stripped = '  abc '.trim-leading;\n    say \"<$stripped>\";          # OUTPUT: «<abc >␤»\n\n=head2 routine trim-trailing\n\n    sub trim-trailing(Str(Cool))\n    method trim-trailing()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Str>|/type/Str>, and\nreturns the string with trailing whitespace stripped.\n\n    my $stripped = '  abc '.trim-trailing;\n    say \"<$stripped>\";          # OUTPUT: «<  abc>␤»\n\n=head2 routine lc\n\n    sub lc(Str(Cool))\n    method lc()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Str>|/type/Str>, and\nreturns it case-folded to lowercase.\n\n    say \"ABC\".lc;       # OUTPUT: «abc␤»\n\n=head2 routine uc\n\n    sub uc(Str(Cool))\n    method uc()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Str>|/type/Str>, and\nreturns it case-folded to uppercase (capital letters).\n\n    say \"Abc\".uc;       # OUTPUT: «ABC␤»\n\n=head2 routine fc\n\n    sub fc(Str(Cool))\n    method fc()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Str>|/type/Str>, and\nreturns the result a Unicode \"case fold\" operation suitable for doing caseless\nstring comparisons. (In general, the returned string is unlikely to be useful\nfor any purpose other than comparison.)\n\n    say \"groß\".fc;       # OUTPUT: «gross␤»\n\n=head2 routine tc\n\n    sub tc(Str(Cool))\n    method tc()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Str>|/type/Str>, and\nreturns it with the first letter case-folded to titlecase (or where not\navailable, uppercase).\n\n    say \"abC\".tc;       # OUTPUT: «AbC␤»\n\n=head2 routine tclc\n\n    sub tclc(Str(Cool))\n    method tclc()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Str>|/type/Str>, and returns it with the first letter\ncase-folded to titlecase (or where not available, uppercase), and the rest\nof the string case-folded to lowercase.\n\n    say 'abC'.tclc;     # OUTPUT: «Abc␤»\n\n=head2 routine wordcase\n\n    sub wordcase(Str(Cool) $input, :&filter = &tclc, Mu :$where = True)\n    method wordcase(:&filter = &tclc, Mu :$where = True)\n\nCoerces the invocant (or in sub form, the first argument) to L<C<Str>|/type/Str>, and filters each word that\nsmartmatches against C<$where> through the C<&filter>. With the default\nfilter (first character to uppercase, rest to lowercase) and matcher (which\naccepts everything), this titlecases each word:\n\n    say \"raku programming\".wordcase;        # OUTPUT: «Raku Programming␤»\n\nWith a matcher:\n\n    say \"have fun working on raku\".wordcase(:where({ .chars > 3 }));\n                                            # Have fun Working on Raku\n\nWith a customer filter too:\n\n    say \"have fun working on raku\".wordcase(:filter(&uc), :where({ .chars > 3 }));\n                                            # HAVE fun WORKING on RAKU\n\n=head2 routine samecase\n\n    sub samecase(Cool $string, Cool $pattern)\n    method samecase(Cool:D: Cool $pattern)\n\nCoerces the invocant (or in sub form, the\nfirst argument) to L<C<Str>|/type/Str>, and calls\nL«C<Str.samecase>|/type/Str#method_samecase» on it.\n\n\n    say \"raKu\".samecase(\"A_a_\"); # OUTPUT: «Raku␤»\n    say \"rAKU\".samecase(\"Ab\");   # OUTPUT: «Raku␤»\n\n=head2 routine uniprop\n\n    multi        uniprop(Str:D, |c)\n    multi        uniprop(Int:D $code)\n    multi        uniprop(Int:D $code, Stringy:D $propname)\n    multi method uniprop(|c)\n\nReturns the L<unicode property|https://en.wikipedia.org/wiki/Unicode_character_property>\nof the first character. If no property is specified returns the\nL<General Category|https://en.wikipedia.org/wiki/Unicode_character_property#General_Category>.\nReturns a Bool for Boolean properties. A L<uniprops|/routine/uniprops> routine can be used\nto get the property for every character in a string.\n\n    say 'a'.uniprop;               # OUTPUT: «Ll␤»\n    say '1'.uniprop;               # OUTPUT: «Nd␤»\n    say 'a'.uniprop('Alphabetic'); # OUTPUT: «True␤»\n    say '1'.uniprop('Alphabetic'); # OUTPUT: «False␤»\n\n=head2 sub uniprops\n\n    sub uniprops(Str:D $str, Stringy:D $propname = \"General_Category\")\n\nInterprets the invocant as a L<C<Str>|/type/Str>, and returns the\nL<unicode property|http://userguide.icu-project.org/strings/properties> for each character\nas a Seq. If no property is specified returns the\nL<General Category|https://en.wikipedia.org/wiki/Unicode_character_property#General_Category>.\nReturns a Bool for Boolean properties. Similar to\nL<uniprop|/routine/uniprop>, but for each character in the passed\nstring.\n\n=head2 routine uniname\n\n    sub uniname(Str(Cool) --> Str)\n    method uniname(--> Str)\n\nInterprets the invocant or first argument as a L<C<Str>|/type/Str>, and returns the\nUnicode codepoint name of the first codepoint of the first character. See\nL<uninames|/routine/uninames> for a routine that works with multiple\ncodepoints, and L<uniparse|/routine/uniparse> for the opposite direction.\n\n    # Camelia in Unicode\n    say ‘»ö«’.uniname;\n    # OUTPUT: «RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK␤»\n    say \"Ḍ̇\".uniname; # Note, doesn't show \"COMBINING DOT ABOVE\"\n    # OUTPUT: «LATIN CAPITAL LETTER D WITH DOT BELOW␤»\n\n    # Find the char with the longest Unicode name.\n    say (0..0x1FFFF).sort(*.uniname.chars)[*-1].chr.uniname;\n    # OUTPUT: «BOX DRAWINGS LIGHT DIAGONAL UPPER CENTRE TO MIDDLE RIGHT AND MIDDLE LEFT TO LOWER CENTRE␤»\n\nAvailable as of the 2021.04 Rakudo compiler release.\n\n=head2 routine uninames\n\n    sub uninames(Str:D)\n    method uninames()\n\nReturns of a L<C<Seq>|/type/Seq> of Unicode names for the all the codepoints in the L<C<Str>|/type/Str>\nprovided.\n\n    say ‘»ö«’.uninames.raku;\n    # OUTPUT: «(\"RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK\", \"LATIN SMALL LETTER O WITH DIAERESIS\", \"LEFT-POINTING DOUBLE ANGLE QUOTATION MARK\").Seq␤»\n\nNote this example, which gets a L<C<Seq>|/type/Seq> where each element is a L<C<Seq>|/type/Seq> of all the\ncodepoints in that character.\n\n    say \"Ḍ̇'oh\".comb>>.uninames.raku;\n    # OUTPUT: «((\"LATIN CAPITAL LETTER D WITH DOT BELOW\", \"COMBINING DOT ABOVE\").Seq, (\"APOSTROPHE\",).Seq, (\"LATIN SMALL LETTER O\",).Seq, (\"LATIN SMALL LETTER H\",).Seq)␤»\n\nSee L<uniname|/routine/uniname> for the name of the first codepoint of the first\ncharacter in the provided L<C<Str>|/type/Str> and L<uniparse|/routine/uniparse> for the\nopposite direction.\n\n=head2 routine unimatch\n\n    multi unimatch(Str:D $str, |c)\n    multi unimatch(Int:D $code, Stringy:D $pvalname, Stringy:D $propname = $pvalname)\n\nChecks if the given integer codepoint or the first letter of the given string\nhas a unicode property equal to the value you give. If you supply the Unicode\nproperty to be checked it will only return True if that property matches the\ngiven value.\n\n    say unimatch 'A', 'Latin';           # OUTPUT: «True␤»\n    say unimatch 'A', 'Latin', 'Script'; # OUTPUT: «True␤»\n    say unimatch 'A', 'Ll';              # OUTPUT: «False␤»\n\nThe last property corresponds to \"lowercase letter\", which explains why it\nreturns false.\n\n=head2 routine chop\n\n    sub chop(Str(Cool))\n    method chop()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Str>|/type/Str>, and\nreturns it with the last character removed.\n\n    say 'raku'.chop;                        # OUTPUT: «rak␤»\n\n=head2 routine chomp\n\n    sub chomp(Str(Cool))\n    method chomp()\n\nCoerces the invocant (or in sub form, its argument) to L<C<Str>|/type/Str>, and\nreturns it with the last character removed, if it is a logical newline.\n\n    say 'ab'.chomp.chars;                   # OUTPUT: «2␤»\n    say \"a\\n\".chomp.chars;                  # OUTPUT: «1␤»\n\n=head2 routine substr\n\n    sub substr(Str(Cool) $str, |c)\n    method substr(|c)\n\nCoerces the invocant (or in the sub form, the first argument) to\nL<C<Str>|/type/Str>, and calls L<Str.substr|/type/Str#routine_substr> with\nthe arguments.\n\n=head2 routine substr-rw\n\n    multi method substr-rw(|) is rw\n    multi        substr-rw(|) is rw\n\nCoerces the invocant (or in the sub form, the first argument) to\nL<C<Str>|/type/Str>, and calls L<Str.substr-rw|/type/Str#method_substr-rw> with\nthe arguments.\n\n=head2 routine ords\n\n    sub ords(Str(Cool) $str)\n    method ords()\n\nCoerces the invocant (or in the sub form, the first argument) to\nL<C<Str>|/type/Str>, and returns a list of Unicode codepoints for each character.\n\n    say \"Camelia\".ords;              # OUTPUT: «67 97 109 101 108 105 97␤»\n    say ords 10;                     # OUTPUT: «49 48␤»\n\nThis is the list-returning version of L<ord|/routine/ord>. The inverse operation in\nL<chrs|/routine/chrs>. If you are only interested in the number of codepoints,\nL<codes|/routine/codes> is a possibly faster option.\n\n=head2 routine chrs\n\n    sub chrs(*@codepoints --> Str:D)\n    method chrs()\n\nCoerces the invocant (or in the sub form, the argument list) to a list of\nintegers, and returns the string created by interpreting each integer as a\nUnicode codepoint, and joining the characters.\n\n    say <67 97 109 101 108 105 97>.chrs;   # OUTPUT: «Camelia␤»\n\nThis is the list-input version of L<chr|/routine/chr>. The inverse operation is L<ords|/routine/ords>.\n\n=head2 routine split\n\n    multi        split(  Str:D $delimiter, Str(Cool) $input, $limit = Inf, :$k, :$v, :$kv, :$p, :$skip-empty)\n    multi        split(Regex:D $delimiter, Str(Cool) $input, $limit = Inf, :$k, :$v, :$kv, :$p, :$skip-empty)\n    multi        split(@delimiters, Str(Cool) $input, $limit = Inf, :$k, :$v, :$kv, :$p, :$skip-empty)\n    multi method split(  Str:D $delimiter, $limit = Inf, :$k, :$v, :$kv, :$p, :$skip-empty)\n    multi method split(Regex:D $delimiter, $limit = Inf, :$k, :$v, :$kv, :$p, :$skip-empty)\n    multi method split(@delimiters, $limit = Inf, :$k, :$v, :$kv, :$p, :$skip-empty)\n\nN<I«the L<comb|/routine/comb> routine is a much better choice for many tasks that in other\nlanguages are handled by the C<split>.»>\n\nCoerces the invocant (or in the sub form, the second argument) to\nL<C<Str>|/type/Str>, splits it into pieces based on delimiters found in the\nstring and returns the result as a L«C<Seq>|/type/Seq».\n\nIf C<$delimiter> is a string, it is searched for literally and not treated\nas a regex. You can also provide multiple delimiters by specifying them as a\nlist, which can mix C<Cool> and L<C<Regex>|/type/Regex> objects.\n\n    say split(';', \"a;b;c\").raku;               # OUTPUT: «(\"a\", \"b\", \"c\").Seq␤»\n    say split(';', \"a;b;c\", 2).raku;            # OUTPUT: «(\"a\", \"b;c\").Seq␤»\n\n    say split(';', \"a;b;c,d\").raku;             # OUTPUT: «(\"a\", \"b\", \"c,d\").Seq␤»\n    say split(/\\;/, \"a;b;c,d\").raku;            # OUTPUT: «(\"a\", \"b\", \"c,d\").Seq␤»\n    say split(/<[;,]>/, \"a;b;c,d\").raku;        # OUTPUT: «(\"a\", \"b\", \"c\", \"d\").Seq␤»\n\n    say split(['a', /b+/, 4], '1a2bb345').raku; # OUTPUT: «(\"1\", \"2\", \"3\", \"5\").Seq␤»\n\nBy default, C<split> omits the matches, and returns a list of only those parts of\nthe string that did not match. Specifying one of the C<:k, :v, :kv, :p> adverbs\nchanges that. Think of the matches as a list that is interleaved with the\nnon-matching parts.\n\nThe C<:v> interleaves the values of that list, which will be either\nL<C<Match>|/type/Match> objects, if a L<C<Regex>|/type/Regex> was used as a matcher\nin the split, or L<C<Str>|/type/Str> objects, if a C<Cool> was used\nas matcher. If multiple delimiters are specified, L<C<Match>|/type/Match> objects\nwill be generated for all of them, unless B<all> of the delimiters are\nC<Cool>.\n\n    say 'abc'.split(/b/, :v);               # OUTPUT: «(a ｢b｣ c)␤»\n    say 'abc'.split('b', :v);               # OUTPUT: «(a b c)␤»\n\nC<:k> interleaves the keys, that is, the indexes:\n\n    say 'abc'.split(/b/, :k);               # OUTPUT: «(a 0 c)␤»\n\nC<:kv> adds both indexes and matches:\n\n    say 'abc'.split(/b/, :kv);               # OUTPUT: «(a 0 ｢b｣ c)␤»\n\nand C<:p> adds them as L<C<Pair>|/type/Pair>s, using the same types for\nvalues as C<:v> does:\n\n    say 'abc'.split(/b/, :p);               # OUTPUT: «(a 0 => ｢b｣ c)␤»\n    say 'abc'.split('b', :p);               # OUTPUT: «(a 0 => b c)␤»\n\nYou can only use one of the C<:k, :v, :kv, :p> adverbs in a single call\nto C<split>.\n\nNote that empty chunks are not removed from the result list.\nFor that behavior, use the C<:skip-empty> named argument:\n\n    say (\"f,,b,c,d\".split: /\",\"/             ).raku;  # OUTPUT: «(\"f\", \"\", \"b\", \"c\", \"d\").Seq␤»\n    say (\"f,,b,c,d\".split: /\",\"/, :skip-empty).raku;  # OUTPUT: «(\"f\", \"b\", \"c\", \"d\").Seq␤»\n\n=head2 routine lines\n\n    sub lines(Str(Cool))\n    method lines()\n\nCoerces the invocant (and in sub form, the argument) to L<C<Str>|/type/Str>,\ndecomposes it into lines (with the newline characters stripped), and returns\nthe list of lines.\n\n    say lines(\"a\\nb\\n\").join('|');          # OUTPUT: «a|b␤»\n    say \"some\\nmore\\nlines\".lines.elems;    # OUTPUT: «3␤»\n\n\nThis method can be used as part of an L«C<IO::Path>|/type/IO::Path»\nto process a file line-by-line, since L<C<IO::Path>|/type/IO::Path> objects inherit from\nC<Cool>, e.g.:\n\n=begin code\nfor 'huge-csv'.IO.lines -> $line {\n    # Do something with $line\n}\n\n# or if you'll be processing later\nmy @lines = 'huge-csv'.IO.lines;\n=end code\n\nWithout any arguments, sub C<lines> operates on\nL«C<$*ARGFILES>|/language/variables#$*ARGFILES».\n\nTo modify values in place use L«C<is\ncopy>|/language/signatures#Parameter_traits_and_modifiers» to force a writable\ncontainer.\n\n=for code\nfor $*IN.lines -> $_ is copy { s/(\\w+)/{$0 ~ $0}/; .say }\n\n=head2 method words\n\n    method words(Cool:D: |c)\n\nCoerces the invocant (or first argument, if it is called as a subroutine) to\nL<C<Str>|/type/Str>, and returns a list of words that make up the string. Check\nL<C<Str.words>|/type/Str#routine_words> for additional arguments and its\nmeaning.\n\n=for code\nsay <The quick brown fox>.words.join('|');     # OUTPUT: «The|quick|brown|fox␤»\nsay <The quick brown fox>.words(2).join('|');  # OUTPUT: «The|quick␤»\n\nC<Cool> is the base class for many other classes, and some of them, like\nL<C<Match>|/type/Match>, can be converted to a string. This is what happens in this case:\n\n    say ( \"easy come, easy goes\" ~~ m:g/(ea\\w+)/).words(Inf);\n    # OUTPUT: «(easy easy)␤»\n    say words( \"easy come, easy goes\" ~~ m:g/(ea\\w+)/ , ∞);\n    # OUTPUT: «(easy easy)␤»\n\nThe example above illustrates two of the ways C<words> can be invoked, with the\nfirst argument turned into invocant by its signature. C<Inf> is the\ndefault value of the second argument, so in both cases (and forms) it can be\nsimply omitted.\n\nOnly whitespace (including no-break space) counts as word boundaries\n\n    say <Flying on a Boeing 747>.words.join('|');  # OUTPUT: «Flying|on|a|Boeing|747␤»\n\nIn this case, \"Boeing 747\" includes a (visible only in the source) no-break space;\nC<words> still splits the (resulting) L<C<Str>|/type/Str> on it, even if the original array\nonly had 4 elements:\n\n    say <Flying on a Boeing 747>.join('|');        # OUTPUT: «Flying|on|a|Boeing 747␤»\n\nPlease see L<C<Str.words>|/type/Str#routine_words> for more examples and ways to\ninvoke it.\n\n=head2 routine comb\n\n    multi        comb(Regex $matcher, Cool $input, $limit = *)\n    multi        comb(Str $matcher, Cool $input, $limit = *)\n    multi        comb(Int:D $size, Cool $input, $limit = *)\n    multi method comb(|c)\n\nReturns a L<C<Seq>|/type/Seq> of all (or if supplied, at most C<$limit>) matches of the\ninvocant (method form) or the second argument (sub form) against the\nL<C<Regex>|/type/Regex>, string or defined number.\n\n    say \"6 or 12\".comb(/\\d+/).join(\", \");           # OUTPUT: «6, 12␤»\n    say comb(/\\d <[1..9]> /,(11..30)).join(\"--\");\n    # OUTPUT:\n    # «11--12--13--14--15--16--17--18--19--21--22--23--24--25--26--27--28--29␤»\n\nThe second statement exemplifies the first form of C<comb>, with a L<C<Regex>|/type/Regex> that\nexcludes multiples of ten, and a L<C<Range>|/type/Range> (which is C<Cool>) as C<$input>.\nC<comb> stringifies the L<C<Range>|/type/Range> before applying C<.comb> on the resulting\nstring. Check L<C<Str.comb>|/type/Str#routine_comb> for its effect on different\nkind of input strings. When the first argument is an integer, it indicates the\n(maximum) size of the chunks the input is going to be divided in\n\n    say comb(3,[3,33,333,3333]).join(\"*\");  # OUTPUT: «3 3*3 3*33 *333*3␤»\n\nIn this case the input is a list, which after transformation to L<C<Str>|/type/Str> (which\nincludes the spaces) is divided in chunks of size 3.\n\n=head2 method contains\n\n    method contains(Cool:D: |c)\n\nCoerces the invocant to a L<C<Str>|/type/Str>, and calls\nL<C<Str.contains>|/type/Str#method_contains> on it. Please refer to\nthat version of the method for arguments and general syntax.\n\n    say 123.contains(\"2\")# OUTPUT: «True␤»\n\nSince L<C<Int>|/type/Int> is a subclass of C<Cool>, C<123> is coerced to a L<C<Str>|/type/Str> and\nthen C<contains> is called on it.\n\n    say (1,1, * + * … * > 250).contains(233)# OUTPUT: «True␤»\n\nL<C<Seq>|/type/Seq>s are also subclasses of C<Cool>, and they are stringified to a\ncomma-separated form. In this case we are also using an L<C<Int>|/type/Int>, which is\ngoing to be stringified also; C<\"233\"> is included in that sequence, so\nit returns C<True>. Please note that this sequence is not lazy; the\nstringification of lazy sequences does not include each and every one of\ntheir components for obvious reasons.\n\n=head2 routine index\n\n    multi        index(Cool:D $s, Cool:D $needle, :i(:$ignorecase), :m(:$ignoremark) --> Int:D)\n    multi        index(Cool:D $s, Cool:D $needle, Cool:D $pos, :i(:$ignorecase), :m(:$ignoremark) --> Int:D)\n    multi method index(Cool:D: Cool:D $needle --> Int:D)\n    multi method index(Cool:D: Cool:D $needle, :m(:$ignoremark)! --> Int:D)\n    multi method index(Cool:D: Cool:D $needle, :i(:$ignorecase)!, :m(:$ignoremark) --> Int:D)\n    multi method index(Cool:D: Cool:D $needle, Cool:D $pos --> Int:D)\n    multi method index(Cool:D: Cool:D $needle, Cool:D $pos, :m(:$ignoremark)!  --> Int:D)\n    multi method index(Cool:D: Cool:D $needle, Cool:D $pos, :i(:$ignorecase)!, :m(:$ignoremark) --> Int:D)\n\nCoerces the first two arguments (in method form, also counting the invocant) to\na L<C<Str>|/type/Str>, and searches for C<$needle> in the string C<$s> starting\nfrom C<$pos>. It returns the offset into the string where C<$needle> was\nfound, and L<C<Nil>|/type/Nil> if it was not found.\n\nSee L<the documentation in type Str|/type/Str#method_index> for examples.\n\n=head2 routine rindex\n\n    multi        rindex(Cool:D $s, Cool:D $needle --> Int:D)\n    multi        rindex(Cool:D $s, Cool:D $needle, Cool:D $pos --> Int:D)\n    multi method rindex(Cool:D: Cool:D $needle --> Int:D)\n    multi method rindex(Cool:D: Cool:D $needle, Cool:D $pos --> Int:D)\n\nCoerces the first two arguments (including the invocant in method form) to\nL<C<Str>|/type/Str> and C<$pos> to L<C<Int>|/type/Int>, and returns the last\nposition of C<$needle> in the string not after C<$pos>. Returns L<C<Nil>|/type/Nil>\nif C<$needle> wasn't found.\n\nSee L<the documentation in type Str|/type/Str#routine_rindex> for examples.\n\n=head2 method match\n\n    method match(Cool:D: $target, *%adverbs)\n\nCoerces the invocant to L<C<Stringy>|/type/Stringy> and calls the method\nL<match|/type/Str#method_match> on it.\n\n=head2 routine roots\n\n    multi        roots(Numeric(Cool) $x, Int(Cool) $n)\n    multi method roots(Int(Cool) $n)\n\nCoerces the first argument (and in method form, the invocant) to\nL<C<Numeric>|/type/Numeric> and the second (C<$n>) to L<C<Int>|/type/Int>, and\nproduces a list of C<$n> L<C<Complex>|/type/Complex> C<$n>-roots, which means\nnumbers that, raised to the C<$n>th power, approximately produce the original\nnumber.\n\nFor example\n\n=begin code\nmy $original = 16;\nmy @roots = $original.roots(4);\nsay @roots;\n\nfor @roots -> $r {\n    say abs($r ** 4 - $original);\n}\n\n# OUTPUT:«2+0i 1.22464679914735e-16+2i -2+2.44929359829471e-16i -3.67394039744206e-16-2i␤»\n# OUTPUT:«1.77635683940025e-15␤»\n# OUTPUT:«4.30267170434156e-15␤»\n# OUTPUT:«8.03651692704705e-15␤»\n# OUTPUT:«1.04441561648202e-14␤»\n=end code\n\n=head2 method subst\n\n    method subst(|)\n\nCoerces the invocant to L<C<Stringy>|/type/Stringy> and calls L<Str.subst|/type/Str#method_subst>.\n\n=head2 method trans\n\n    method trans(|)\n\nCoerces the invocant to L<C<Str>|/type/Str> and calls L<Str.trans|/type/Str#method_trans>\n\n=head2 method IO\n\n    method IO(--> IO::Path:D)\n\nCoerces the invocant to L<C<IO::Path>|/type/IO::Path>.\n\n=for code\n.say for '.'.IO.dir;        # gives a directory listing\n\n=head2 method sprintf\n\n    method sprintf(*@args)\n\nReturns a string according to a series of L<format\ndirectives|/type/independent-routines#Directives> that are common in many languages;\nthe object will be the format string, while the supplied arguments will be\nwhat's going to be formatted according to it.\n\n=for code\n\"% 6s\".sprintf('Þor').say; # OUTPUT: «   Þor␤»\n\n=head2 method printf\n\n    method printf(*@args)\n\nUses the object, as long as it is a L<format\nstring|/type/independent-routines#Directives>, to format and print the arguments\n\n=for code\n\"%.8f\".printf(now - now ); # OUTPUT: «-0.00004118»\n\n=head2 method Complex\n\n    multi method Complex()\n\nCoerces the invocant to a L«C<Numeric>|/type/Numeric» and calls its\nL«C<.Complex>|/routine/Complex» method. L<Fails|/routine/fail> if the\ncoercion to a L<C<Numeric>|/type/Numeric> cannot be done.\n\n    say 1+1i.Complex;         # OUTPUT: «1+1i␤»\n    say π.Complex;            # OUTPUT: «3.141592653589793+0i␤»\n    say <1.3>.Complex;        # OUTPUT: «1.3+0i␤»\n    say (-4/3).Complex;       # OUTPUT: «-1.3333333333333333+0i␤»\n    say \"foo\".Complex.^name;  # OUTPUT: «Failure␤»\n\n=head2 method FatRat\n\n    multi method FatRat()\n\nCoerces the invocant to a L«C<Numeric>|/type/Numeric» and calls its\nL«C<.FatRat>|/routine/FatRat» method. L<Fails|/routine/fail> if the\ncoercion to a L<C<Numeric>|/type/Numeric> cannot be done.\n\n    say 1+0i.FatRat;          # OUTPUT: «1␤»\n    say 2e1.FatRat;           # OUTPUT: «20␤»\n    say 1.3.FatRat;           # OUTPUT: «1.3␤»\n    say (-4/3).FatRat;        # OUTPUT: «-1.333333␤»\n    say \"foo\".FatRat.^name;   # OUTPUT: «Failure␤»\n\n=head2 method Int\n\n    multi method Int()\n\nCoerces the invocant to a L«C<Numeric>|/type/Numeric» and calls its\nL«C<.Int>|/routine/Int» method. L<Fails|/routine/fail> if the\ncoercion to a L<C<Numeric>|/type/Numeric> cannot be done.\n\n    say 1+0i.Int;             # OUTPUT: «1␤»\n    say <2e1>.Int;            # OUTPUT: «20␤»\n    say 1.3.Int;              # OUTPUT: «1␤»\n    say (-4/3).Int;           # OUTPUT: «-1␤»\n    say \"foo\".Int.^name;      # OUTPUT: «Failure␤»\n\n=head2 method Num\n\n    multi method Num()\n\nCoerces the invocant to a L«C<Numeric>|/type/Numeric» and calls its\nL«C<.Num>|/routine/Num» method. L<Fails|/routine/fail> if the\ncoercion to a L<C<Numeric>|/type/Numeric> cannot be done.\n\n    say 1+0i.Num;             # OUTPUT: «1␤»\n    say 2e1.Num;              # OUTPUT: «20␤»\n    say (16/9)².Num;          # OUTPUT: «3.1604938271604937␤»\n    say (-4/3).Num;           # OUTPUT: «-1.3333333333333333␤»\n    say \"foo\".Num.^name;      # OUTPUT: «Failure␤»\n\n=head2 method Rat\n\n    multi method Rat()\n\nCoerces the invocant to a L«C<Numeric>|/type/Numeric» and calls its\nL«C<.Rat>|/routine/Rat» method. L<Fails|/routine/fail> if the\ncoercion to a L<C<Numeric>|/type/Numeric> cannot be done.\n\n    say 1+0i.Rat;                             # OUTPUT: «1␤»\n    say 2e1.Rat;                              # OUTPUT: «20␤»\n    say (-4/3).Rat;                           # OUTPUT: «-1.333333␤»\n    say \"foo\".Rat.^name;                      # OUTPUT: «Failure␤»\n    say (.numerator, .denominator) for π.Rat; # OUTPUT: «(355 113)␤»\n\n=head2 method Real\n\n    multi method Real()\n\nCoerces the invocant to a L«C<Numeric>|/type/Numeric» and calls its\nL«C<.Real>|/routine/Real» method. L<Fails|/routine/fail> if the\ncoercion to a L<C<Numeric>|/type/Numeric> cannot be done.\n\n    say 1+0i.Real;            # OUTPUT: «1␤»\n    say 2e1.Real;             # OUTPUT: «20␤»\n    say 1.3.Real;             # OUTPUT: «1.3␤»\n    say (-4/3).Real;          # OUTPUT: «-1.333333␤»\n    say \"foo\".Real.^name;     # OUTPUT: «Failure␤»\n\n=head2 method UInt\n\n    multi method UInt()\n\nCoerces the invocant to an L«C<Int>|/type/Int».  L<Fails|/routine/fail>\nif the coercion to an L<C<Int>|/type/Int> cannot be done or if the L<C<Int>|/type/Int> the invocant\nhad been coerced to is negative.\n\n    say 1+0i.UInt;            # OUTPUT: «1␤»\n    say 2e1.UInt;             # OUTPUT: «20␤»\n    say 1.3.UInt;             # OUTPUT: «1␤»\n    say (-4/3).UInt.^name;    # OUTPUT: «Failure␤»\n    say \"foo\".UInt.^name;     # OUTPUT: «Failure␤»\n\n=head2 method uniparse\n\n    method uniparse(Cool:D: --> Str:D)\n\nAvailable as of the 2021.04 release of the Rakudo compiler.\n\nCoerces the invocant to a L<C<Str>|/type/Str> and then calls the\nL<uniparse|/type/Str#routine_uniparse> on that.  This mostly only\nmakes sense for L<C<Match>|/type/Match> objects.\n\n=head2 method Order\n\n    method Order(Cool:D: --> Order:D)\n\nAvailable as of the 2022.02 release of the Rakudo compiler.\n\nCoerces the invocant to an L<C<Int>|/type/Int>, and then returns one of the\nL<C<Order>|/type/Order> enums: C<Less> if negative, C<Same> if\nB<0>, C<More> if positive.\n\n=head2 method Failure\n\n    method Failure(Cool:D: --> Failure:D)\n\nAvailable as of the 2022.06 release of the Rakudo compiler.\n\nCreates an L<C<X::AdHoc>|/type/X::AdHoc> exception with the stringification of the\ninvocant, and coerces that into a L<C<Failure>|/type/Failure> object.\nMainly intended to reduce the bytecode for error branches in code,\nto increase the chances of hot code getting inlined.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/CurrentThreadScheduler.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class CurrentThreadScheduler\n\n=SUBTITLE Scheduler that synchronously executes code on the current thread\n\n=for code :skip-test<compile time error>\nclass CurrentThreadScheduler does Scheduler {}\n\nC<CurrentThreadScheduler> executes tasks on the current threads. This means\nthat L<method cue|/type/Scheduler#method_cue> blocks until the code has\nfinished executing.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Date.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Date\n\n=SUBTITLE Calendar date\n\n    class Date { }\n\nA C<Date> is an immutable object identifying a day in the Gregorian calendar.\n\nC<Date> objects support addition and subtraction of integers, where an\ninteger is interpreted as the number of days. You can compare C<Date> objects\nwith the numeric comparison operators C«==, <, <=, >, >=, !=».\nTheir stringification in C<YYYY-MM-DD> format means that comparing them\nwith the string operators C<eq, lt, le> etc. also gives the right result.\n\nC<Date.today> creates\nan object the current day according to the system clock.\n\n    my $d = Date.new(2015, 12, 24); # Christmas Eve!\n    say $d;                         # OUTPUT: «2015-12-24␤»\n    say $d.year;                    # OUTPUT: «2015␤»\n    say $d.month;                   # OUTPUT: «12␤»\n    say $d.day;                     # OUTPUT: «24␤»\n    say $d.day-of-week;             # OUTPUT: «4␤» (Thursday)\n    say $d.later(days => 20);       # OUTPUT: «2016-01-13␤»\n    my $n = Date.new('2015-12-31'); # New Year's Eve\n    say $n - $d;                    # OUTPUT: «7␤», 7 days between New Years/Christmas Eve\n    say $n + 1;                     # OUTPUT: «2016-01-01␤»\n\nB<Note> since version 6.d, .raku can be called on C<Date>.\n\n=head1 Methods\n\n=head2 method new\n\n    multi method new($year, $month, $day, :&formatter --> Date:D)\n    multi method new(:$year!, :$month = 1, :$day = 1  --> Date:D)\n    multi method new(Str $date                        --> Date:D)\n    multi method new(Instant:D $dt                    --> Date:D)\n    multi method new(DateTime:D $dt                   --> Date:D)\n\nCreates a new C<Date> object, either from a triple of (year, month, day)\nthat can be coerced to integers, or from a string of the form C<YYYY-MM-DD>\n(L<ISO 8601|https://en.wikipedia.org/wiki/ISO_8601>), or from an Instant\nor DateTime object.  Optionally accepts a formatter as a named parameter.\n\n    my $date = Date.new(2042, 1, 1);\n    $date = Date.new(year => 2042, month => 1, day => 1);\n    $date = Date.new(\"2042-01-01\");\n    $date = Date.new(Instant.from-posix: 1482155532);\n    $date = Date.new(DateTime.now);\n\nSince Rakudo 2022.03, the \"day\" argument can also be a callable, with C<*>\nrepresenting the last day in a month, and the possibility of getting to the\nday counting from the last one:\n\n    say Date.new(2042, 2, *); # OUTPUT: «2042-02-28␤»\n    say Date.new(2044, 2, *); # OUTPUT: «2044-02-29␤»\n\n=head2 method new-from-daycount\n\n    method new-from-daycount($daycount,:&formatter --> Date:D)\n\nCreates a new C<Date> object given C<$daycount> which is the number\nof days from epoch Nov. 17, 1858, i.e. the\nL<Modified Julian Day|https://en.wikipedia.org/wiki/Julian_day>.\nOptionally accepts a formatter as a named parameter.\n\n    say Date.new-from-daycount(49987);          # OUTPUT: «1995-09-27␤»\n\n=head2 method daycount\n\n    method daycount(Date:D: --> Int:D)\n\nReturns the number of days from epoch Nov. 17, 1858, i.e. the\nL<Modified Julian Day|https://en.wikipedia.org/wiki/Julian_day>.\n\n=head2 method last-date-in-month\n\n    method last-date-in-month(Date:D: --> Date:D)\n\nReturns the last date in the month of the C«Date» object. Otherwise, returns\nthe invocant if the day value is already the last day of the month.\n\n    say Date.new('2015-11-24').last-date-in-month; # OUTPUT: «2015-11-30␤»\n\nThis should allow for much easier ranges like\n\n=for code :preamble<my $date>\n$date .. $date.last-date-in-month\n\nfor all remaining dates in the month.\n\n=head2 method first-date-in-month\n\n    method first-date-in-month(Date:D: --> Date:D)\n\nReturns the first date in the month of the C«Date» object. Otherwise, returns\nthe invocant if the day value is already the first day of the month.\n\n    say Date.new('2015-11-24').first-date-in-month; # OUTPUT: «2015-11-01␤»\n\n=head2 method clone\n\n    method clone(Date:D: :$year, :$month, :$day, :&formatter)\n\nCreates a new C<Date> object based on the invocant, but with the given\narguments overriding the values from the invocant.\n\n    say Date.new('2015-11-24').clone(month => 12);    # OUTPUT: «2015-12-24␤»\n\n=head2 method today\n\n    method today(:&formatter --> Date:D)\n\nReturns a C<Date> object for the current day.  Optionally accepts a\nformatter named parameter.\n\n    say Date.today;\n\n=head2 method truncated-to\n\n    method truncated-to(Date:D: Cool $unit)\n\nReturns a C<Date> truncated to the first day of its year, month or week.\nFor example\n\n    my $c = Date.new('2012-12-24');\n    say $c.truncated-to('year');     # OUTPUT: «2012-01-01␤»\n    say $c.truncated-to('month');    # OUTPUT: «2012-12-01␤»\n    say $c.truncated-to('week');     # OUTPUT: «2012-12-24␤», because it's Monday already\n\n=head2 method succ\n\n    method succ(Date:D: --> Date:D)\n\nReturns a C<Date> of the following day. \"succ\" is short for \"successor\".\n\n    say Date.new(\"2016-02-28\").succ;   # OUTPUT: «2016-02-29␤»\n\n=head2 method pred\n\n    method pred(Date:D: --> Date:D)\n\nReturns a C<Date> of the previous day. \"pred\" is short for \"predecessor\".\n\n    say Date.new(\"2016-01-01\").pred;   # OUTPUT: «2015-12-31␤»\n\n=head2 method Str\n\n    multi method Str(Date:D: --> Str:D)\n\nReturns a string representation of the invocant, as specified by\nL<the formatter|/type/Dateish#method_formatter>. If no formatter was\nspecified, an (L<ISO 8601|https://en.wikipedia.org/wiki/ISO_8601>) date\nwill be returned.\n\n    say Date.new('2015-12-24').Str;                     # OUTPUT: «2015-12-24␤»\n\n    my $fmt = { sprintf \"%02d/%02d/%04d\", .month, .day, .year };\n    say Date.new('2015-12-24', formatter => $fmt).Str;  # OUTPUT: «12/24/2015␤»\n\n=head2 method gist\n\n    multi method gist(Date:D: --> Str:D)\n\nReturns the date in C<YYYY-MM-DD> format (L<ISO 8601|https://en.wikipedia.org/wiki/ISO_8601>)\n\n    say Date.new('2015-12-24').gist;                    # OUTPUT: «2015-12-24␤»\n\n=head2 method Date\n\n    method Date(--> Date)\n\nReturns the invocant.\n\n    say Date.new('2015-12-24').Date;  # OUTPUT: «2015-12-24␤»\n    say Date.Date;                    # OUTPUT: «(Date)␤»\n\n=head2 method DateTime\n\n    multi method DateTime(Date:U: --> DateTime:U)\n    multi method DateTime(Date:D: --> DateTime:D)\n\nConverts the invocant to L«C<DateTime>|/type/DateTime»\n\n    say Date.new('2015-12-24').DateTime; # OUTPUT: «2015-12-24T00:00:00Z␤»\n    say Date.DateTime;                   # OUTPUT: «(DateTime)␤»\n\n=head2 method Int\n\n    multi method Int(Date:D: --> Int:D)\n\nConverts the invocant to L«C<Int>|/type/Int».  The same value can be\nobtained with the C<daycount> method.\n\nAvailable as of release 2023.02 of the Rakudo compiler.\n\n=head2 method Real\n\n    multi method Real(Date:D: --> Int:D)\n\nConverts the invocant to L«C<Int>|/type/Int».  The same value can be\nobtained with the C<daycount> method.\n\nAvailable as of release 2023.02 of the Rakudo compiler.\n\n=head2 method Numeric\n\n    multi method Numeric(Date:D: --> Int:D)\n\nConverts the invocant to L«C<Int>|/type/Int».  The same value can be\nobtained with the C<daycount> method.  This allows C<Date> objects to\nbe used directly in arithmetic operations.\n\nAvailable as of release 2023.02 of the Rakudo compiler.\n\n=head1 Functions\n\n=head2 sub infix:<->\n\n    multi infix:<-> (Date:D, Int:D --> Date:D)\n    multi infix:<-> (Date:D, Date:D --> Int:D)\n\nTakes a date to subtract from and either an L«C<Int>|/type/Int», representing\nthe number of days to subtract, or another C<Date> object.\nReturns a new C<Date> object or the number of days between the\ntwo dates, respectively.\n\n    say Date.new('2016-12-25') - Date.new('2016-12-24'); # OUTPUT: «1␤»\n    say Date.new('2015-12-25') - Date.new('2016-11-21'); # OUTPUT: «-332␤»\n    say Date.new('2016-11-21') - 332;                    # OUTPUT: «2015-12-25␤»\n\n=head2 sub infix:<+>\n\n    multi infix:<+> (Date:D, Int:D --> Date:D)\n    multi infix:<+> (Int:D, Date:D --> Date:D)\n\nTakes an L«C<Int>|/type/Int» and adds that many days to the given\nC<Date> object.\n\n    say Date.new('2015-12-25') + 332; # OUTPUT: «2016-11-21␤»\n    say 1 + Date.new('2015-12-25');   # OUTPUT: «2015-12-26␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/DateTime.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class DateTime\n\n=SUBTITLE Calendar date with time\n\n    class DateTime does Dateish {}\n\nFor handling points in civil time, a C<DateTime> object stores year, month,\nday, hour, minute (all L<C<Int>|/type/Int>), second (potentially fractional) and\na timezone.\n\nIt provides methods for calculating with date (for the Gregorian calendar) and time.\n\nC<DateTime> methods are immutable; if you are tempted to modify one, create a\nmodified copy instead.\n\nTimezones are handled as L<C<Int>|/type/Int>s in B<seconds> offset from UTC,\nnot by timezone name.\n\n=begin code\nmy $dt = DateTime.new(\n    year    => 2015,\n    month   => 11,\n    day     => 21,\n    hour    => 16,\n    minute  => 1,\n);\n\nsay $dt;                            # OUTPUT: «2015-11-21T16:01:00Z␤»\nsay $dt.later(days => 20);          # OUTPUT: «2015-12-11T16:01:00Z␤»\nsay $dt.truncated-to('hour');       # OUTPUT: «2015-11-21T16:00:00Z␤»\nsay $dt.in-timezone(-8 * 3600);     # OUTPUT: «2015-11-21T08:01:00-0800␤»\n\nmy $now = DateTime.now(formatter => { sprintf \"%02d:%02d\", .hour, .minute });\nsay $now;                           # 12:45 (or something like that)\n=end code\n\nSince version 6.d, using synthetic codepoints such as 7̈ will result in an\nerror.\n\n=head1 Methods\n\n=head2 method new\n\n=for code\nmulti method new(Int :$year!, Int :$month = 1, Int :$day = 1,\n                 Int :$hour = 0, Int :$minute = 0, :$second = 0,\n                 Int :$timezone = 0, :&formatter)\nmulti method new(Date :$date!,\n                 Int :$hour = 0, Int :$minute = 0, :$second = 0,\n                 Int :$timezone = 0, :&formatter)\nmulti method new(Int() $year, Int() $month, Int() $day,\n                 Int() $hour, Int $minute, $second,\n                 Int() :$timezone = 0, :&formatter)\nmulti method new(Instant:D $i,  :$timezone=0, :&formatter)\nmulti method new(Numeric:D $posix,  :$timezone=0, :&formatter)\nmulti method new(Str:D $format, :$timezone=0, :&formatter)\n\nCreates a new C<DateTime> object. One option for creating a new C<DateTime> object\nis from the components (year, month, day, hour, ...) separately. Another is to\npass a L<C<Date>|/type/Date> object for the date component, and specify the time\ncomponent-wise. Yet another is to obtain the time from an\nL<C<Instant>|/type/Instant>, and only supply the timezone and formatter. Or\ninstead of an L<C<Instant>|/type/Instant> you can supply a L<C<Numeric>|/type/Numeric> as a Unix timestamp\n(but note that this last method provides no way to disambiguate leap seconds,\nunlike using L<C<Instant>|/type/Instant>).\n\nYou can also supply a L<C<Str>|/type/Str> formatted in ISO 8601 timestamp\nnotation or as a full L<RFC 3339|https://tools.ietf.org/html/rfc3339>\ndate and time.  Strings should be formatted as C<yyyy-mm-ddThh:mm:ssZ>\nor C<yyyy-mm-ddThh:mm:ss+0100>.  We are somewhat less restrictive than the\nISO 8601 standard, as we allow Unicode digits and mixing of condensed\nand extended time formats.\n\nAn invalid input string throws an exception of type\nL<C<X::Temporal::InvalidFormat>|/type/X::Temporal::InvalidFormat>. If you supply a string that includes a\ntimezone and supply the C<timezone> named argument, an exception of type\nL<C<X::DateTime::TimezoneClash>|/type/X::DateTime::TimezoneClash> is thrown.\n\n    my $datetime = DateTime.new(year => 2015,\n                                month => 1,\n                                day => 1,\n                                hour => 1,\n                                minute => 1,\n                                second => 1,\n                                timezone => 1);\n    $datetime = DateTime.new(date => Date.new('2015-12-24'),\n                             hour => 1,\n                             minute => 1,\n                             second => 1,\n                             timezone => 1);\n    $datetime = DateTime.new(2015, 1, 1, # First January of 2015\n                             1, 1, 1);   # Hour, minute, second with default timezone\n    $datetime = DateTime.new(now);                       # Instant.\n    # from a Unix timestamp\n    say $datetime = DateTime.new(1470853583.3);          # OUTPUT: «2016-08-10T18:26:23.300000Z␤»\n    $datetime = DateTime.new(\"2015-01-01T03:17:30+0500\") # Formatted string\n\nSince Rakudo release 2022.03, the C<day> parameter can be a L<C<Callable>|/type/Callable>, with\nC<*> returning the last day in the month, and C<*-n> returning the last but\nC<n>.\n\nSince Rakudo release 2022.07, it is also possible to just specify a\n\"YYYY-MM-DD\" string to indicate midnight on the given date.\n\n    say DateTime.new(\"2023-03-04\");  # OUTPUT: «2023-03-04T00:00:00Z␤»\n\n=head2 method now\n\n    method now(:$timezone = $*TZ, :&formatter --> DateTime:D)\n\nCreates a new C<DateTime> object from the current system time. A custom\nL<formatter|/routine/formatter> and L<timezone|/routine/timezone> can be provided. The C<:$timezone> is\nthe offset B<in seconds> from L<GMT|https://en.wikipedia.org/wiki/Greenwich_Mean_Time>\nand defaults to the value of L«C<$*TZ> variable|/language/variables#index-entry-%24*TZ».\n\n    say DateTime.now; # OUTPUT: «2018-01-08T13:05:32.703292-06:00␤»\n\nNote that one may use the methods shown below chained to the C<.now> to easily express current\nvalues, e.g.,\n\n    say DateTime.now.year; # OUTPUT: «2018␤»\n\n=head2 method clone\n\n    method clone(DateTime:D: :$year, :$month, :$day, :$hour, :$minute, :$second, :$timezone, :&formatter)\n\nCreates a new C<DateTime> object based on the invocant, but with the given\narguments overriding the values from the invocant.\n\n    say DateTime.new('2015-12-24T12:23:00Z').clone(hour => 0);\n    # OUTPUT: «2015-12-24T00:23:00Z␤»\n\nNote that this can lead to invalid dates in some circumstances:\n\n    say DateTime.new(\"2012-02-29T12:34:56Z\").clone(year => 2015);\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::OutOfRange: Day out of range. Is: 29, should be in 1..28␤»\n\n=head2 method hh-mm-ss\n\n    method hh-mm-ss(DateTime:D: --> Str:D)\n\nReturns the time represented by the object as a string in 24-hour HH:MM:SS format:\n\n    say DateTime.new(\"2052-02-29T22:34:56Z\").hh-mm-ss;\n    # OUTPUT: «22:34:56␤»\n\n=head2 method hour\n\n    method hour(DateTime:D: --> Int:D)\n\nReturns the hour component.\n\n    say DateTime.new('2012-02-29T12:34:56Z').hour;      # OUTPUT: «12␤»\n\n=head2 method minute\n\n    method minute(DateTime:D: --> Int:D)\n\nReturns the minute component.\n\n    say DateTime.new('2012-02-29T12:34:56Z').minute;     # OUTPUT: «34␤»\n\n=head2 method second\n\n    method second(DateTime:D:)\n\nReturns the second component, including potentially fractional seconds.\n\n    say DateTime.new('2012-02-29T12:34:56Z').second;     # OUTPUT: «56␤»\n    say DateTime.new('2012-02-29T12:34:56.789Z').second; # OUTPUT: «56.789␤»\n    say DateTime.new('2012-02-29T12:34:56,789Z').second; # comma also ok\n\n=head2 method whole-second\n\n    method whole-second(DateTime:D:)\n\nReturns the second component, rounded down to an L<C<Int>|/type/Int>.\n\n    say DateTime.new('2012-02-29T12:34:56.789Z').whole-second;      # OUTPUT: «56␤»\n\n=head2 method timezone\n\n    method timezone(DateTime:D: --> Int:D)\n\nReturns the timezone B<in seconds> as an offset from UTC.\n\n    say DateTime.new('2015-12-24T12:23:00+0200').timezone;          # OUTPUT: «7200␤»\n\n=head2 method offset\n\n    method offset(DateTime:D: --> Int:D)\n\nReturns the timezone B<in seconds> as an offset from UTC. This is an alias for\nL<method timezone|#method timezone>.\n\n    say DateTime.new('2015-12-24T12:23:00+0200').offset;            # OUTPUT: «7200␤»\n\n=head2 method offset-in-minutes\n\n    method offset-in-minutes(DateTime:D: --> Real:D)\n\nReturns the timezone in minutes as an offset from UTC.\n\n    say DateTime.new('2015-12-24T12:23:00+0200').offset-in-minutes; # OUTPUT: «120␤»\n\n=head2 method offset-in-hours\n\n    method offset-in-hours(DateTime:D: --> Real:D)\n\nReturns the timezone in hours as an offset from UTC.\n\n=for code\nsay DateTime.new('2015-12-24T12:23:00+0200').offset-in-hours;   # OUTPUT: «2␤»\n\n=head2 method Str\n\n    method Str(DateTime:D: --> Str:D)\n\nReturns a string representation of the invocant, as done by\nL<the formatter|/type/Dateish#method_formatter>.\nIf no formatter was specified, an ISO 8601 timestamp will be returned.\n\n=for code\nsay DateTime.new('2015-12-24T12:23:00+0200').Str;\n# OUTPUT: «2015-12-24T12:23:00+02:00␤»\n\n=head2 method Instant\n\n    method Instant(DateTime:D: --> Instant:D)\n\nReturns an L<C<Instant>|/type/Instant> object based on the invocant.\n\n    say DateTime.new('2015-12-24T12:23:00+0200').Instant; # OUTPUT: «Instant:1450952616␤»\n\n=head2 method Real\n\n    multi method Real(DateTime:D: --> Instant:D)\n\nConverts the invocant to L«C<Instant>|/type/Instant».  The same value can be\nobtained with the L<C<Instant>|/type/Instant> method.\n\nAvailable as of release 2023.02 of the Rakudo compiler.\n\n=head2 method Numeric\n\n    multi method Numeric(DateTime:D: --> Instant:D)\n\nAvailable as of the 2021.09 release of the Rakudo compiler.\n\nConverts the invocant to L«C<Instant>|/type/Instant».  The same value can\nbe obtained with the L<C<Instant>|/type/Instant> method.  This allows C<DateTime> objects\nto be used directly in arithmetic operations.\n\n=head2 method day-fraction\n\n    method day-fraction(DateTime:D: --> Real:D)\n\nReturns the instant's time as a fraction of a 24-hour day.\n\n    say DateTime.new('2021-12-24T12:23:00.43Z').day-fraction; # OUTPUT: «0.5159772␤»\n\nNotice the C<day-fraction> value is the same as the fractional part of\nthe C<modified-julian-date> for the same instant.\n\nAlso note that leap seconds may cause some variations from expected values:\n\n    for 30, 31 { say DateTime.new(2016,12,$_,12,0,0).day-fraction }\n    # OUTPUT: «0.5␤0.499994␤»\n\nAvailable as of the 2021.04 Rakudo compiler release.\n\n=head2 method julian-date\n\n    method julian-date(DateTime:D: --> Real:D)\n\nReturns the L<Julian date|https://en.wikipedia.org/wiki/Julian_day> (JD) for the UTC date and time.\n\n    say DateTime.new('2021-12-24T12:23:00.43Z').julian-date; # OUTPUT: «2459573.0159772␤»\n\nThe C<julian-date> starts at zero at the epoch of noon UTC on\nI<November 24, 4714 B.C.> on the L<proleptic|https://en.m.wiktionary.org/wiki/proleptic> Gregorian calendar (the calendar\nin use in much of the world and in international commerce and travel). The JD\nis used in astronomy to define times of celestial objects transiting the\nEarth's Prime Meridian. For any instant, it is the sum of the number of whole days and\nthe fraction of a day from that epoch to that instant.\n\nBefore Rakudo release 2025.08, the C<julian-date> method does B<not>\nuse any timezone information, and silently ignores it in the\nC<DateTime> object.\n\nAvailable as of the 2021.04 Rakudo compiler release.\n\n=head2 method modified-julian-date\n\n    method modified-julian-date(DateTime:D: --> Real:D)\n\nReturns the L<Modified Julian Date|https://en.wikipedia.org/wiki/Julian_day> (MJD) for the UTC date and time.\n\n    say DateTime.new('2021-12-24T12:23:00.43Z').modified-julian-date; # OUTPUT: «59572.5159772␤»\n\nNotice the fractional part of the C<modified-julian-date> is same value as the\nL<C<day-fraction>|/type/DateTime#method_day-fraction> for the same instant, and\nis similarly affected by leap seconds.\nLikewise, the integral part of the I<MJD> is the same value as the C<daycount> for the same instant since they\nreference the same epoch (November 17, 1858).\nThe MJD is obtained by subtracting the constant C<2_400_000.5> from the I<Julian Date> and is used to simplify\ntransformations between civil and astronomical time systems.\n\nBefore Rakudo release 2025.08, the C<modified-julian-date> method\ndoes B<not> use any timezone information, and silently ignores it in\nthe C<DateTime> object.\n\nAvailable as of the 2021.04 Rakudo compiler release.\n\n=head2 method posix\n\n    method posix(Bool:D: $ignore-timezone = False --> Int:D)\n\nReturns the date and time as a POSIX/Unix timestamp (non-leap seconds since the POSIX epoch,\n1970-01-01T00:00:00Z).\n\nIf C<$ignore-timezone> is C<True>, the C<DateTime> object will be treated as if\nthe timezone offset is zero.\n\n    method posix(Bool:D: $ignore-timezone = False, :$real --> Num:D)\n\nNote that this will collapse both a leap second and the second immediately\nfollowing it into the same timestamp, because POSIX time ignores leap seconds.\nIf you need better than this, see L<C<Instant>|/type/Instant> for the relevant\nmethods.\n\nAs of release 2022.06 of the Rakudo compiler, it is also possible to specify a\nC<:real> named argument.  If specified with a true value, a L<C<Num>|/type/Num> will be\nreturned, allowing for sub-second accuracy of the number of seconds since the\nPOSIX epoch.\n\n=for code\nsay DateTime.new('2015-12-24T12:23:00Z').posix;           # OUTPUT: «1450959780␤»\nsay DateTime.new('2022-06-21T12:23:00.5Z').posix;         # OUTPUT: «1655814180␤»\nsay DateTime.new('2022-06-21T12:23:00.5Z').posix(:real);  # OUTPUT: «1655814180.5␤»\n\n=head2 method truncated-to\n\n    method truncated-to(DateTime:D: Cool $unit)\n\nReturns a copy of the invocant, with everything smaller than the specified\nunit truncated to the smallest possible value.\n\n    my $d = DateTime.new(\"2012-02-29T12:34:56.946314Z\");\n    say $d.truncated-to('second');      # OUTPUT: «2012-02-29T12:34:56Z␤»\n    say $d.truncated-to('minute');      # OUTPUT: «2012-02-29T12:34:00Z␤»\n    say $d.truncated-to('hour');        # OUTPUT: «2012-02-29T12:00:00Z␤»\n    say $d.truncated-to('day');         # OUTPUT: «2012-02-29T00:00:00Z␤»\n    say $d.truncated-to('month');       # OUTPUT: «2012-02-01T00:00:00Z␤»\n    say $d.truncated-to('year');        # OUTPUT: «2012-01-01T00:00:00Z␤»\n\nDateTimes with fractional seconds can be truncated to whole seconds with\nC<.truncated-to('second')>.\n\n=head2 method Date\n\n    multi method Date(DateTime:U --> Date:U)\n    multi method Date(DateTime:D --> Date:D)\n\nConverts the invocant to L«C<Date>|/type/Date».\n\n=for code\nsay DateTime.new(\"2012-02-29T12:34:56.946314Z\").Date; # OUTPUT: «2012-02-29␤»\nsay DateTime.Date;                                    # OUTPUT: «(Date)␤»\n\n=head2 method DateTime\n\n    method DateTime(--> DateTime)\n\nReturns the invocant.\n\n    say DateTime.new(\"2012-02-29T12:34:56.946314Z\").DateTime;\n    # OUTPUT: «2012-02-29T12:34:56.946314Z␤»\n    say DateTime.DateTime;\n    # OUTPUT: «(DateTime)␤»\n\n=head2 method utc\n\n    method utc(DateTime:D: --> DateTime:D)\n\nReturns a DateTime object for the same time, but in timezone UTC.\n\n    say DateTime.new('2015-12-24T12:23:00+0200').utc;\n    # OUTPUT: «2015-12-24T10:23:00Z␤»\n\n=head2 method in-timezone\n\n    method in-timezone(DateTime:D: Int(Cool) $timezone = 0 --> DateTime:D)\n\nReturns a DateTime object for the same time, but in the specified C<$timezone>,\nwhich is the offset B<in seconds> from\nL<GMT|https://en.wikipedia.org/wiki/Greenwich_Mean_Time>.\n\n    say DateTime.new('2015-12-24T12:23:00Z').in-timezone(3600 + 1800); # OUTPUT: «2015-12-24T13:53:00+0130␤»\n\nPer L<RFC 7164|https://tools.ietf.org/html/rfc7164#section-3>, leap seconds do\nnot respect local time and always occur at the end of the I<UTC> day:\n\n    say DateTime.new: '2017-01-01T00:59:60+01:00'\n    # OUTPUT: «2017-01-01T00:59:60+01:00␤»\n\n=head2 method local\n\n    method local(DateTime:D: --> DateTime:D)\n\nReturns a DateTime object for the same time, but in the local timezone\n(L«C<$*TZ>|/language/variables#index-entry-%24*TZ»).\n\n    my $*TZ = -3600;\n    say DateTime.new('2015-12-24T12:23:00+0200').local; # OUTPUT: «2015-12-24T09:23:00-0100␤»\n\n=head2 sub infix:<->\n\n    multi infix:<-> (DateTime:D, Duration:D --> DateTime:D)\n    multi infix:<-> (DateTime:D, DateTime:D --> Duration:D)\n\nTakes a C<DateTime> to subtract from and either a\nL«C<Duration>|/type/Duration» or another C<DateTime> object. Returns a new\nC<DateTime> object or the L<C<Duration>|/type/Duration> between the two dates, respectively. When\nsubtracting L<C<Duration>|/type/Duration>, timezone of the original C<DateTime> is preserved\nin the returned C<DateTime> object.\n\n    say raku DateTime.new(:2016year) - DateTime.new(:2015year):;\n    # OUTPUT: «Duration.new(31536001.0)␤»\n    say DateTime.new(:2016year, :3600timezone) - Duration.new(31536001.0);\n    # OUTPUT: «2015-01-01T00:00:00+01:00␤»\n\n=head2 sub infix:<+>\n\n    multi infix:<+> (DateTime:D, Duration:D --> DateTime:D)\n    multi infix:<+> (Duration:D, DateTime:D --> DateTime:D)\n\nTakes a C<DateTime> and increases it by the given\nL«C<Duration>|/type/Duration», preserving the timezone.\n\n    say DateTime.new(:2015year) + Duration.new(31536001.0);\n    # OUTPUT: «2016-01-01T00:00:00Z␤»\n    say Duration.new(42) + DateTime.new(:2015year, :3600timezone);\n    # OUTPUT: «2015-01-01T00:00:42+01:00␤»\n\n=head2 sub infix:<cmp>\n\n    multi infix:<cmp>(DateTime:D \\a, DateTime:D \\b --> Order:D)\n\nCompares the equivalent instant, returns the Order.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Dateish.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"basic\")\n\n=TITLE role Dateish\n\n=SUBTITLE Object that can be treated as a date\n\n    role Dateish { ... }\n\nBoth L<C<Date>|/type/Date> and L<C<DateTime>|/type/DateTime> support accessing of the\nyear, month and day-of-month represented in the object, as well as related\nfunctionality such as calculating the day of the week.\n\n=head1 Methods\n\n=head2 method year\n\n    method year(Date:D: --> Int:D)\n\nReturns the year of the date.\n\n    say Date.new('2015-12-31').year;                                  # OUTPUT: «2015␤»\n    say DateTime.new(date => Date.new('2015-12-24'), hour => 1).year; # OUTPUT: «2015␤»\n\n=head2 method month\n\n    method month(Date:D: --> Int:D)\n\nReturns the month of the date (1..12).\n\n    say Date.new('2015-12-31').month;                                  # OUTPUT: «12␤»\n    say DateTime.new(date => Date.new('2015-12-24'), hour => 1).month; # OUTPUT: «12␤»\n\n=head2 method day\n\n    method day(Date:D: --> Int:D)\n\nReturns the day of the month of the date (1..31).\n\n    say Date.new('2015-12-31').day;                                  # OUTPUT: «31␤»\n    say DateTime.new(date => Date.new('2015-12-24'), hour => 1).day; # OUTPUT: «24␤»\n\n=head2 method formatter\n\n    method formatter(Dateish:D:)\n\nReturns the formatting function which is used for conversion to\nL<C<Str>|/type/Str>. If none was provided at object construction, a\ndefault formatter is used.  In that case the method will return a\nCallable type object.\n\nThe formatting function is called by\nL<DateTime method Str|/type/DateTime#method_Str> with the\ninvocant as its only argument.\n\n    my $dt = Date.new('2015-12-31');  # (no formatter specified)\n    say $dt.formatter.^name;          # OUTPUT: «Callable␤»\n    my $us-format = sub ($self) { sprintf \"%02d/%02d/%04d\", .month, .day, .year given $self; };\n    $dt = Date.new('2015-12-31', formatter => $us-format);\n    say $dt.formatter.^name;           # OUTPUT: «Sub␤»\n    say $dt;                          # OUTPUT: «12/31/2015␤»\n\n=head2 method is-leap-year\n\n    method is-leap-year(Dateish:D: --> Bool:D)\n\nReturns C<True> if the year of the Dateish object is a leap year.\n\n    say DateTime.new(:year<2016>).is-leap-year; # OUTPUT: «True␤»\n    say Date.new(\"1900-01-01\").is-leap-year;    # OUTPUT: «False␤»\n\n=head2 method day-of-month\n\n    method day-of-month(Date:D: --> Int:D)\n\nReturns the day of the month of the date (1..31). Synonymous to the C<day>\nmethod.\n\n    say Date.new('2015-12-31').day-of-month;                                  # OUTPUT: «31␤»\n    say DateTime.new(date => Date.new('2015-12-24'), hour => 1).day-of-month; # OUTPUT: «24␤»\n\n=head2 method day-of-week\n\n    method day-of-week(Date:D: --> Int:D)\n\nReturns the day of the week, where 1 is Monday, 2 is Tuesday and Sunday is 7.\n\n    say Date.new('2015-12-31').day-of-week;                                  # OUTPUT: «4␤»\n    say DateTime.new(date => Date.new('2015-12-24'), hour => 1).day-of-week; # OUTPUT: «4␤»\n\n=head2 method day-of-year\n\n    method day-of-year(Date:D: --> Int:D)\n\nReturns the day of the year (1..366).\n\n    say Date.new('2015-12-31').day-of-year;                                  # OUTPUT: «365␤»\n    say DateTime.new(date => Date.new('2015-03-24'), hour => 1).day-of-year; # OUTPUT: «83␤»\n\n=head2 method days-in-year\n\n    method days-in-year(Dateish:D: --> Int:D)\n\nReturns the number of days in the year represented by the Dateish object:\n\n    say Date.new(\"2016-01-02\").days-in-year;               # OUTPUT: «366␤»\n    say DateTime.new(:year<2100>, :month<2>).days-in-year; # OUTPUT: «365␤»\n\nAvailable as of the 2022.12 release of the Rakudo compiler.\n\n=head2 method days-in-month\n\n    method days-in-month(Dateish:D: --> Int:D)\n\nReturns the number of days in the month represented by the Dateish object:\n\n    say Date.new(\"2016-01-02\").days-in-month;                # OUTPUT: «31␤»\n    say DateTime.new(:year<10000>, :month<2>).days-in-month; # OUTPUT: «29␤»\n\n=head2 method week\n\n    method week()\n\nReturns a list of two integers: the year, and the week number. This is because\nat the start or end of a year, the week may actually belong to the other year.\n\n    my ($year, $week) = Date.new(\"2014-12-31\").week;\n    say $year;                       # OUTPUT: «2015␤»\n    say $week;                       # OUTPUT: «1␤»\n    say Date.new('2015-01-31').week; # OUTPUT: «(2015 5)␤»\n\n=head2 method week-number\n\n    method week-number(Date:D: --> Int:D)\n\nReturns the week number (1..53) of the date specified by the invocant. The first\nweek of the year is defined by ISO as the one which contains the fourth day of\nJanuary. Thus, dates early in January often end up in the last week of the prior\nyear, and similarly, the final few days of December may be placed in the first\nweek of the next year.\n\n    say Date.new(\"2014-12-31\").week-number;   # OUTPUT: «1␤»  (first week of 2015)\n    say Date.new(\"2016-01-02\").week-number;   # OUTPUT: «53␤» (last week of 2015)\n\n=head2 method week-year\n\n    method week-year(Date:D: --> Int:D)\n\nReturns the week year of the date specified by the invocant. Normally C<week-year>\nis equal to C<Date.year>. Note however that dates early in January often end up in\nthe last week of the prior year, and similarly, the final few days of December\nmay be placed in the first week of the next year.\n\n    say Date.new(\"2015-11-15\").week-year;   # OUTPUT: «2015␤»\n    say Date.new(\"2014-12-31\").week-year;   # OUTPUT: «2015␤» (date belongs to the first week of 2015)\n    say Date.new(\"2016-01-02\").week-year;   # OUTPUT: «2015␤» (date belongs to the last week of 2015)\n\n=head2 method weekday-of-month\n\n    method weekday-of-month(Date:D: --> Int:D)\n\nReturns a number (1..5) indicating the number of times a particular day-of-week\nhas occurred so far during that month, the day itself included.\n\n    say Date.new(\"2003-06-09\").weekday-of-month;  # OUTPUT: «2␤»  (second Monday of the month)\n\n=head2 method yyyy-mm-dd\n\n=for code :ok-test<dd>\nmethod yyyy-mm-dd(str $sep = \"-\" --> Str:D)\n\nReturns the date in C<YYYY-MM-DD> format (L<ISO 8601|https://en.wikipedia.org/wiki/ISO_8601>).\nThe optional positional argument C<$sep>, which defaults to C«-», is a one-character\nseparator placed between the different parts of the date.\n\n=begin code :ok-test<dd>\nsay Date.new(\"2015-11-15\").yyyy-mm-dd;   # OUTPUT: «2015-11-15␤»\nsay DateTime.new(1470853583).yyyy-mm-dd; # OUTPUT: «2016-08-10␤»\nsay Date.today.yyyy-mm-dd(\"/\");          # OUTPUT: «2020/03/14␤»\n=end code\n\n=head2 method mm-dd-yyyy\n\n=for code :ok-test<dd>\nmethod mm-dd-yyyy(str $sep = \"-\" --> Str:D)\n\nReturns the date in C<MM-DD-YYYY> format (L<Gregorian, month-day-year (MDY)|https://en.wikipedia.org/wiki/Calendar_date>).\nThe optional positional argument C<$sep>, which defaults to C«-», is a one-character\nseparator placed between the different parts of the date.\n\n=begin code :ok-test<dd>\nsay Date.new(\"2015-11-15\").mm-dd-yyyy;   # OUTPUT: «11-15-2015␤»\nsay DateTime.new(1470853583).mm-dd-yyyy; # OUTPUT: «08-10-2016␤»\nsay Date.today.mm-dd-yyyy(\"/\");          # OUTPUT: «03/14/2020␤»\n=end code\n\n=head2 method dd-mm-yyyy\n\n=for code :ok-test<dd>\nmethod dd-mm-yyyy(str $sep = \"-\" --> Str:D)\n\nReturns the date in C<DD-MM-YYYY> format (L<Gregorian, day-month-year (DMY)|https://en.wikipedia.org/wiki/Calendar_date>).\nThe optional positional argument C<$sep>, which defaults to C«-», is a one-character\nseparator placed between the different parts of the date.\n\n=begin code :ok-test<dd>\nsay Date.new(\"2015-11-15\").dd-mm-yyyy;    # OUTPUT: «15-11-2015␤»\nsay DateTime.new(1470853583).dd-mm-yyyy;  # OUTPUT: «10-08-2016␤»\nsay Date.today.dd-mm-yyyy(\"/\");           # OUTPUT: «14/03/2020␤»\n=end code\n\n=head2 method daycount\n\n    method daycount(Dateish:D: --> Int:D)\n\nReturns the number of days from the epoch Nov. 17, 1858, to the\nday of the invocant. The daycount returned by this method is the\nintegral part of the L<Modified Julian Day|https://en.wikipedia.org/wiki/Julian_day> (MJD)\nwhich is used routinely by astronomers, geodesists, scientists,\nand others. The MJD convention is designed to facilitate simplified\nchronological calculations. The fractional part of the MJD\nconsists of the hours, minutes, and seconds of the using DateTime\nobject converted to the equivalent fraction of 24 hours.\nThose two values added define the MJD of that instant.\n\n\n    say Date.new('1995-09-27').daycount;    # OUTPUT: «49987␤»\n\n=head2 method IO\n\n    method IO(Dateish:D: --> IO::Path:D)\n\nReturns an L<C<IO::Path>|/type/IO::Path> object representing the stringified\nvalue of the Dateish object:\n\n    Date.today.IO.say;   # OUTPUT: «\"2016-10-03\".IO␤»\n    DateTime.now.IO.say; # OUTPUT: «\"2016-10-03T11:14:47.977994-04:00\".IO␤»\n\nB<PORTABILITY NOTE:> some operating systems (e.g. Windows) do not permit\ncolons (C<:>) in filenames, which would be present in L<C<IO::Path>|/type/IO::Path> created from a\nL<C<DateTime>|/type/DateTime> object.\n\n=head2 method earlier\n\n    multi method earlier(Dateish:D: *%unit)\n    multi method earlier(Dateish:D: @pairs)\n\nReturns an object based on the current one, but with a date delta\ntowards the past applied. Unless the given unit is C<second> or C<seconds>, the\ngiven value will be converted to an L<C<Int>|/type/Int>. See L<C<.later>|/type/Dateish#method_later> for\nusage. It will generally be used through classes that implement this role,\nL<C<Date>|/type/Date> or L<C<DateTime>|/type/DateTime>\n\n    my $d = Date.new('2015-02-27');\n    say $d.earlier(month => 5).earlier(:2days);  # OUTPUT: «2014-09-25␤»\n    my $d = DateTime.new(date => Date.new('2015-02-27'));\n    say $d.earlier(month => 1).earlier(:2days);  # OUTPUT: «2015-01-25T00:00:00Z␤»\n\nIf the resultant time has value C<60> for seconds, yet no leap second\nactually exists for that time, seconds will be set to C<59>:\n\n    say DateTime.new('2008-12-31T23:59:60Z').earlier: :1day;\n    # OUTPUT: «2008-12-30T23:59:59Z␤»\n\nNegative offsets are allowed, though L<later|/routine/later> is more idiomatic for that.\n\nIf you need to use more than one unit, you will need to build them into a\nL<C<List>|/type/List> of L<C<Pair>|/type/Pair>s to use the second form of the method:\n\n=for code\nsay Date.new('2021-03-31').earlier(  ( year => 3, month => 2, day => 8 ) ); # OUTPUT: «2018-01-23␤»\n\nThis feature was introduced in release 2021.02 of the Rakudo compiler.\n\n=head2 method later\n\n    multi method later(DateTime:D: *%unit)\n\nReturns an object based on the current one (belonging to any class that mixes\nthis role in), but with a\ntime delta\napplied. The time delta can be passed as a named argument where the argument\nname is the unit.\n\nUnless the given unit is C<second> or C<seconds>, the given value will be\nconverted to an L<C<Int>|/type/Int>.\n\nAllowed units are C<second>, C<seconds>, C<minute>, C<minutes>, C<hour>,\nC<hours>, C<day>, C<days>, C<week>, C<weeks>, C<month>, C<months>, C<year>,\nC<years>. Please note that the plural forms can only be used with\nthe C<later> and C<earlier> methods.\n\nThe C<:2nd> form of colonpairs can be used as a compact and self-documenting\nway of specifying the delta:\n\n    say DateTime.new('2015-12-24T12:23:00Z').later(:2years);\n    # OUTPUT: «2017-12-24T12:23:00Z␤»\n\nSince addition of several different time units is not commutative, only one\nunit may be passed (and the first multi will be used).\n\n    my $d = DateTime.new(date => Date.new('2015-02-27'));\n    say $d.later(month => 1).later(:2days);  # OUTPUT: «2015-03-29T00:00:00Z␤»\n    say $d.later(days => 2).later(:1month);  # OUTPUT: «2015-04-01T00:00:00Z␤»\n    say $d.later(days => 2).later(:month);   # same, as +True === 1\n\nYou can also (since release 2021.02 of the Rakudo compiler) pass several units\nat the same time, but you will have to join them in a L<C<List>|/type/List> to activate the\nsecond form:\n\n=for code\nsay DateTime.new(date => Date.new('2015-02-27')).later( (:1month, :2days) )\n# OUTPUT: «2015-03-29T00:00:00Z␤»\n\nIf the resultant time has value C<60> for seconds, yet no leap second\nactually exists for that time, seconds will be set to C<59>:\n\n    say DateTime.new('2008-12-31T23:59:60Z').later: :1day;\n    # OUTPUT: «2009-01-01T23:59:59Z␤»\n\nNegative offsets are allowed, though L<earlier|/routine/earlier> is more\nidiomatic for that.\n\nObjects of type L<C<Date>|/type/Date> will behave in the same way:\n\n=begin code\nmy $d = Date.new('2015-02-27');\nsay $d.later(month => 1).later(:2days);  # OUTPUT: «2015-03-29␤»\nsay $d.later(days => 2).later(:1month);  # OUTPUT: «2015-04-01␤»\nsay $d.later(days => 2).later(:month);   # same, as +True === 1\n=end code\n\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Distribution/Hash.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Distribution::Hash\n\n=SUBTITLE Distribution::Hash\n\n=for code :preamble<role Distribution::Locally {}>\nclass Distribution::Hash does Distribution::Locally { }\n\nA L<C<Distribution>|/type/Distribution> implementation backed by the filesystem. It\ndoes not require a C<META6.json> file, essentially providing a lower level\nL<C<Distribution::Path>|/type/Distribution::Path>.\n\n=head1 Methods\n\n=head2 method new\n\n    method new($hash, :$prefix)\n\nCreates a new C<Distribution::Hash> instance from the metadata contained in\nC<$hash>. All paths in the metadata will be prefixed with C<:$prefix>.\n\n=head2 method meta\n\n    method meta()\n\nReturns a Hash with the representation of the metadata.\n\n=head2 method content\n\nPlease check\nL<the C<content> method in Distribution::Locally|/type/Distribution::Locally#method_content>.\n\nReturns an L<C<IO::Handle>|/type/IO::Handle> to the file represented by C<$name-path>. C<$name-path>\nis a relative path as it would be found in the metadata such as C<lib/Foo.rakumod>\nor C<resources/foo.txt>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Distribution/Locally.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Distribution::Locally\n\n=SUBTITLE Distribution::Locally\n\n    role Distribution::Locally does Distribution { }\n\nProvides read access to specific files pointed at by a distributions metadata,\nproviding the L<Distribution#method_content|/type/Distribution#method_content>\nmethod for L<C<Distribution::Path>|/type/Distribution::Path> and\nL<C<Distribution::Hash>|/type/Distribution::Hash>.\n\n=head1 Methods\n\n=head2 method prefix\n\nA prefix path to be used in conjuncture with the paths found in the metadata.\n\n=head2 method content\n\nProvides L<Distribution#method_content|/type/Distribution#method_content>\n\nReturns an L<C<IO::Handle>|/type/IO::Handle> to the file represented by C<$name-path>. C<$name-path>\nis a relative path as it would be found in the metadata such as C<lib/Foo.rakumod>\nor C<resources/foo.txt>, and these paths will be prefixed with\nL<Distribution#method_prefix|#method_prefix>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Distribution/Path.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Distribution::Path\n\n=SUBTITLE Distribution::Path\n\n=for code :preamble<role Distribution::Locally {}>\nclass Distribution::Path does Distribution::Locally { }\n\nA L<C<Distribution>|/type/Distribution> implementation backed by the filesystem. It requires a\nC<META6.json> file at its root.\n\n=head1 Methods\n\n=head2 method new\n\n    method new(IO::Path $prefix, IO::Path :$meta-file = IO::Path)\n\nCreates a new C<Distribution::Path> instance from the C<META6.json> file found\nat the given C<$prefix>, and from which all paths in the metadata will be\nprefixed with. C<:$meta-file> may optionally be passed if a filename other than\nC<META6.json> needs to be used.\n\n=head2 method meta\n\n    method meta(Distribution::Path:D:)\n\nReturns a Hash with the representation of the metadata.\n\n=head2 method content\n\nL<Distribution::Locally#method_content|/type/Distribution#method_content>\n\nReturns an L<C<IO::Handle>|/type/IO::Handle> to the file represented by C<$name-path>. C<$name-path>\nis a relative path as it would be found in the metadata such as C<lib/Foo.rakumod>\nor C<resources/foo.txt>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Distribution/Resource.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Distribution::Resource\n\n=SUBTITLE Every one of the resources installed with a distribution\n\n    class Distribution::Resource { }\n\nA C<Distribution::Resource> is every one of the individual resources (files\nor libraries) that are returned as values of the\nL<C<%?RESOURCES>|/language/variables#%?RESOURCES> dynamic variable (which,\nitself, is an instance of C<Distribution::Resources>. These resources are\ninstalled as part of the standard distribution installation process; please\ncheck the definition of C<%?RESOURCES> above for more context.\n\nExternally, every one of these resources behaves as an L<C<IO::Path>|/type/IO::Path>, and it\nshares many of the same methods; however, it's really I<not> an L<C<IO::Path>|/type/IO::Path>\nand thus cannot be smartmatched to it.\n\nThis variable will work with the current repository chain structure, and will\ngive you the right way to get to the resource independently of it being\ninstalled or not; however, you shouldn't rely on these values maintaining\nconsistency across implementations. You will be able to access the resource\nvia its handle no matter what. in this example:\n\n=begin code :solo\nunit class Resourceable;\n\nmethod gimme(::?CLASS:U: ) {\n    %?RESOURCES;\n}\n=end code\n\nwith this C<META6.json>:\n\n=begin code :lang<json>\n{\n  \"provides\": {\n    \"Resourceable\": \"lib/Resourceable.rakumod\"\n  },\n  \"license\": \"Artistic-2.0\",\n  \"description\": \"Testing how Distribution::Resource(s) work\",\n  \"perl\": \"6.*\",\n  \"auth\": \"zef:jj\",\n  \"version\": \"1.2\",\n  \"resources\": [\n    \"libraries/whatever\",\n    \"data/swim.csv\"\n  ],\n  \"meta-version\": \"0\",\n  \"name\": \"Resourceable\"\n}\n=end code\n\nyou see that there are the two kinds of resources available: regular ones,\nand those starting with C<libraries>, whose actual value (and handle)\nreturned will depend on the operating system. For example\non Windows this might find a C<.dll>, on Linux a C<.so>, and on MacOS\na C<.dylib>.\n\nIf we access it through this script (placed in C<bin/>):\n\n=begin code :skip-test<Needs Resourceable>\nuse Resourceable;\n\nfor <libraries/whatever data/swim.csv> -> $resource {\n    with Resourceable.gimme{$resource} {\n       .say;\n       say \"-\" x 10, \">\";\n       ( .repo-name, .repo, .dist-id, .key )».say;\n    }\n}\n=end code\n\nrun directly from the source directory, like this:\n\n=for code :lang<text>\n# raku -Ilib bin/show-resources.raku\n\"/home/jmerelo/progs/raku/my-raku-examples/test-resources/resources/libraries/libwhatever.so\".IO\n---------->\n(Str)\nfile#/home/jmerelo/progs/raku/my-raku-examples/test-resources/lib\n/home/jmerelo/progs/raku/my-raku-examples/test-resources/lib:ver<*>:auth<>:api<*>\nlibraries/whatever\n\"/home/jmerelo/progs/raku/my-raku-examples/test-resources/resources/data/swim.csv\".IO\n---------->\n(Str)\nfile#/home/jmerelo/progs/raku/my-raku-examples/test-resources/lib\n/home/jmerelo/progs/raku/my-raku-examples/test-resources/lib:ver<*>:auth<>:api<*>\ndata/swim.csv\n\nHowever, if we install the distribution and run the installed script, instead we\nget something like:\n\n=for code :lang<text>\n\"/home/jmerelo/.rakubrew/versions/moar-2020.05/install/share/perl6/site/resources/7127AA0E7F43E87DF309570E813E46A6E2C4D0B2.so\".IO\n---------->\nsite\n(Str)\n1F8F9C004D7E952B297F30420DA07B354B3F2AA7\nlibraries/whatever\n\"/home/jmerelo/.rakubrew/versions/moar-2020.05/install/share/perl6/site/resources/D357F3E46256CB0DACD8975033D1CC7A17B4CF9F.csv\".IO\n---------->\nsite\n(Str)\n1F8F9C004D7E952B297F30420DA07B354B3F2AA7\ndata/swim.csv\n\nThe main difference, as it can be observed, is that \"local\" distributions\nhave a defined value for C<repo>, while \"installed\" distributions have a\ndefined value for C<repo-name>. C<dist-id> is going to be different depending\non the type of distribution, and in any case C<.key> will return the name of\nthe resources pseudo-hash key.\n\nPlease note also that accessing the resource via its key will return a handle\non the resource, which gists to an L<C<IO::Path>|/type/IO::Path> but is, in fact, a\nC<Distribution::Resource> object. Looking again at the \"regular\" resources,\nthe path it translates to will be the same as the one declared in\nC<resources> in META6.json, but it will change for \"library\" resources\nconverting it to the canonical library name corresponding to the value, in\nthe first case C<libwhatever.so>, in the second, a hashed name with the\ncanonical Linux extension, C<.so>.\n\nA C<Distribution::Resource> is designed to be used directly as the resource\nit represents, such as a file, for instance\n\n=for code\nmy @data = %?RESOURCES<data/swim.csv>.lines.split(\",\");\n\nHowever, this is I<not> because it returns an L<C<IO::Path>|/type/IO::Path>, but because it\nshares some methods with it: C<open,\nslurp, lines, comb, split, words, copy>; above we use C<.lines>, for\ninstance.\n\nNote that it is essential for C<Resource>s that .IO and related methods be\ndetermined at runtime, and not done at the compilation stage (specifically,\nthat they not make their way into a precomp file).  The reason for this is\nthat the file path can and sometimes does change between the two stages.\nThus, it's important to avoid all methods that reference the file path,\n(such as C<absolute> or C<dirname>) and instead access the file using the\nC<open> method.\n\nIn the case of resources placed in the C<libraries/> folder, its main use\ncase is as an argument for L<C<is native>|/language/nativecall>, as in this\nexample:\n\n=for code :skip-test<Illustrates a use case>\nuse NativeCall;\nsub foo() is native(%?RESOURCES<libraries/whatever>)\n\nThe C<Distribution::Resource> returned will have the correct name and\nextension for the specific architecture the distribution is being run.\n\nIn general and in any case, the guiding principle is that resources\nshould be used directly for its intended purpose, be it shared libraries or\nregular resource files.\n\n=head1 Methods\n\n=head2 method IO\n\n     method IO()\n\nReturns the corresponding resource as an L<C<IO::Path>|/type/IO::Path>, which can effectively\nbe used as such.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Distribution.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"basic\")\n\n=TITLE role Distribution\n\n=SUBTITLE Distribution\n\n    role Distribution { }\n\nThis role is an interface for objects that provide API access mapping META6 data\nto the files it represents. Objects that fulfill the C<Distribution> role can be\nread by e.g.\nL<C<CompUnit::Repository::Installation>|/type/CompUnit::Repository::Installation>.\nGenerally a C<Distribution> provides read access to a set of modules and\nmetadata. These may be backed by the filesystem\n(L<C<Distribution::Path>|/type/Distribution::Path>,\nL<C<Distribution::Hash>|/type/Distribution::Hash>) but could also read from an e.g.\ntar file or socket.\n\n=head1 Required Methods\n\n=head2 method meta\n\n    method meta(--> Hash:D) { ... }\n\nReturns a Hash with the representation of the metadata. Please note that an\nactual C<META6.json> file does not need to exist, just a representation in that\nformat.\n\n=head2 method content\n\n    method content($name-path --> IO::Handle:D) { ... }\n\nReturns an L<C<IO::Handle>|/type/IO::Handle> to the file represented by C<$name-path>. C<$name-path>\nis a relative path as it would be found in the metadata such as C<lib/Foo.rakumod>\nor C<resources/foo.txt>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Distro.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Distro\n\n=SUBTITLE Distribution related information\n\n    class Distro does Systemic { }\n\nBuilt-in class for providing distribution related information.  Usually accessed\nthrough the L<$*DISTRO|/language/variables#index-entry-%24*DISTRO> dynamic\nvariable.\n\n=head1 Methods\n\n=head2 method is-win\n\nInstance method returning a L<C<Bool>|/type/Bool> indicating whether the distribution is a\nversion of the Windows operating system.\n\n=head2 method path-sep\n\nInstance method returning the string that can be used to delimit elements in\na path specification.\n\n=head2 method release\n\nInstance method returning the release information of the Distro object.  Dies if\nthe release information could not be established.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Duration.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Duration\n\n=SUBTITLE Length of time\n\n    class Duration is Cool does Real { }\n\nA C<Duration> represents a length of time in atomic seconds, with\nfractions. Like an L<C<Instant>|/type/Instant>, it is epoch-agnostic.\n\nC<Duration>s can be subtracted from or added to L<C<Instant>|/type/Instant>s to yield another,\nnew L<C<Instant>|/type/Instant>. Subtracting one L<C<Instant>|/type/Instant> from another yields a C<Duration>. A\nC<Duration> can also result from mathematical operations between two\nC<Duration>s when it makes sense (namely, the addition, subtraction, or modulus\nof two C<Duration>s). It can also be added, subtracted or divided modulo L<C<Real>|/type/Real>\nnumbers.\n\nThe type of object returned for other numeric operations is currently\nunspecified.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Encoding/Registry.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Encoding::Registry\n\n=SUBTITLE Management of available encodings\n\n    class Encoding::Registry {}\n\nC<Encoding::Registry> is initialized with a list of encoding that is\navailable for any Raku application, namely:\n\n=item C<utf8>\n=item C<utf8-c8>\n=item C<utf16>\n=item C<utf16le>\n=item C<utf16be>\n=item C<utf32>, C<utf-32>\n=item C<ascii>\n=item C<iso-8859-1>, C<iso_8859-1:1987>, C<iso_8859-1>, C<iso-ir-100>, C<latin1>, C<latin-1>, C<csisolatin1>, C<l1>, C<ibm819>, C<cp819>\n=item C<windows-1251>\n=item C<windows-1252>\n=item C<windows-932>\n\n=head1 Methods\n\n=head2 method name\n\n    method register(Encoding $enc --> Nil)\n\nRegister a new L<C<Encoding>|/type/Encoding>.\n\nX<|Types,Encoding::Encoder>\nX<|Types,Encoding::Decoder>\n=head2 method find\n\n    method find(Str() $name)\n\nFinds an encoding by its name. Returns an C<Encoding::Encoder> or\nC<Encoding::Decoder>, depending on what had been registered.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Encoding.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"basic\")\n\n=TITLE role Encoding\n\n=SUBTITLE Support for character encodings.\n\n    role Encoding { ... }\n\nThe C<Encoding> role is implemented by classes that provide a character\nencoding, such as ASCII or UTF-8. Besides being used by the built-in character\nencodings, it may also be implemented by users to provide new encodings.\nInstances of objects doing this role are typically obtained using\nL<C<Encoding::Registry>|/type/Encoding::Registry>. For a list of supported encodings, see\nL<IO::Handle|/type/IO::Handle#method_encoding>.\n\nAll methods provided by this role are stubs; they should be implemented by\nconsumers of the role.\n\n=head1 Methods\n\n=head2 method name\n\n    method name(--> Str)\n\nAbstract method that would return the primary name of the encoding.\n\n=head2 method alternative-names\n\n    method alternative-names()\n\nAbstract methods that should get a list of alternative names for the encoding.\n\n=head2 method decoder\n\n    method decoder(*%options --> Encoding::Decoder)\n\nShould get a character decoder instance for this encoding, configured with the\nprovided options. Options vary by encoding. The built-in encodings all\nsupport C<translate-nl>, which if C<True> will translate C<\\r\\n> into\nC<\\n> while decoding.\n\n=head2 method encoder\n\n    method encoder(*%options --> Encoding::Encoder)\n\nGets a character encoder instance for this encoding, configured with the\nprovided options. Options vary by encoding. The built-in encodings all support\nboth C<replacement> (either a L<C<Str>|/type/Str> replacement sequence or C<True> to use a\ndefault replacement sequence for unencodable characters) and C<translate-nl>\n(when set to C<True>, turns C<\\n> into C<\\r\\n> if the current platform is\nWindows).\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Endian.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"enum\") :category(\"basic\")\n\n=TITLE enum Endian\n\n=SUBTITLE Indicate endianness (6.d, 2018.12 and later)\n\n    enum Endian <NativeEndian LittleEndian BigEndian>;\n\nX<|Reference,NativeEndian>\nX<|Reference,LittleEndian>\nX<|Reference,BigEndian>\nX<|Reference,Endian>\nAn enum for indicating endianness, specifically with methods on C<blob8> and\nC<buf8>.  Consists of C<NativeEndian>, C<LittleEndian> and C<BigEndian>.\n\n=head1 Methods\n\n=head2 routine Numeric\n\n    multi method Numeric(Endian:D --> Int:D)\n\nReturns the value part of the C<enum> pair.\n\n    say NativeEndian.Numeric;    # OUTPUT: «0␤»\n    say LittleEndian.Numeric;    # OUTPUT: «1␤»\n    say BigEndian.Numeric;       # OUTPUT: «2␤»\n\nNote that the actual numeric values are subject to change.  So please use\nthe named values instead.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Enumeration.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"composite\")\n\n=TITLE role Enumeration\n\n=SUBTITLE Working with the role behind the enum type\n\n    role Enumeration { }\n\nThis is the role implemented by the enum-pairs in the\nL<C<enum> type|/language/typesystem#enum>. In general, it is used to create\nconstant sets,\nthe elements of which become also constant symbols in the current namespace and\nto establish a relationship between the symbols belonging to the same set. In\ngeneral, you will find C<Enumeration> in L<enum|/language/typesystem#enum>\ntypes:\n\n    enum norse-gods <Þor Oðin Loki>;\n    my $one-of-them = norse-gods.pick;\n    say $one-of-them.^name; # OUTPUT: «(norse-gods)␤»\n    say $one-of-them ~~ Enumeration; # OUTPUT: «True␤»\n\nbut nothing prevents you from using it in your own programs if you want to\nrestrict somehow the relationship between the key and the value:\n\n=begin code\nclass DNA does Enumeration {\n    my %pairings = %( A => \"T\",\n                      T => \"A\",\n                      C => \"G\",\n                      G => \"C\" );\n\n    method new( $base-pair where \"A\" | \"C\" | \"G\" | \"T\" )  {\n        self.bless( key => $base-pair,\n                    value => %pairings{$base-pair});\n    }\n\n    multi method gist(::?CLASS:D:) {\n        return \"$!key → $!value\";\n    }\n\n}\n\nenum Chain ();\nconstant length = 16;\nfor <A C G T>.roll( length ) -> $letter {\n    my DNA $base = DNA.new( $letter );\n    Chain.HOW.add_enum_value( Chain, $base );\n}\n\nfor ^length {\n    my $base = Chain.pick;\n    say \"{$base.key} and {$base.value}\";\n}\n=end code\n\nIn this code, C<DNA> consumes the C<Enumeration> role, which is from this point\nof view a pair of key and value; we can use the generated C<DNA> objects to\ncompose an C<enum> type from which elements can be picked one by one, with the\noutput shown below.\n\n=begin code :lang<text>\nT and A\nC and G\nT and A\n# and so on...\n=end code\n\nAn item would smartmatch the enum class, but not the other way round:\n\n=for code\nenum Foo <bar baz>;\nsay baz ~~ Foo;  # OUTPUT: «True␤»\nsay Foo ~~ bar;  # OUTPUT: «False␤»\n\n=head1 Methods that work on the enum class\n\nAs of release 2021.04 of the Rakudo compiler, an enum class can be\nconsidered as an instantiated L<C<Map>|/type/Map> object.  This means\nyou can use the\nL<keys|/type/Map#method_keys>,\nL<values|/type/Map#method_values>,\nL<kv|/type/Map#method_kv>,\nL<pairs|/type/Map#method_pairs>,\nL<antipairs|/type/Map#method_antipairs>,\nL<invert|/type/Map#method_invert>\non an enum class and get the expected result.\n\n    enum Norse-gods <Þor Oðin Freija>;\n    say Norse-gods.keys; # OUTPUT: «(Þor Oðin Freija)␤»\n\n=head2 method enums\n\n    method enums()\n\nReturns a L<C<Map>|/type/Map> of enum values. Works both on the enum type\nand any key.\n\n    enum Mass ( mg => 1/1000, g => 1/1, kg => 1000/1 );\n    say Mass.enums; # OUTPUT: «Map.new((g => 1, kg => 1000, mg => 0.001))␤»\n    say g.enums;    # OUTPUT: «Map.new((g => 1, kg => 1000, mg => 0.001))␤»\n\n=head1 Methods that work on the enum keys\n\n=head2 method key\n\nAn C<Enumeration> property.\n\n    enum Norse-gods <Þor Oðin Freija>;\n    say Freija.key; # OUTPUT: «Freija␤»\n\n=head2 method value\n\nThese are C<Enumeration> properties.\n\n    enum Norse-gods <Þor Oðin Freija>;\n    say Oðin.value; # OUTPUT: «1␤»\n\nThe C<value> is assigned automatically by the C<enum> type starting at 0.\nC<Oðin> gets 1 since it is the second in the C<enum>.\n\n=head2 method kv\n\n    multi method kv(::?CLASS:D:)\n\nReturns a list with key and value of the enum-pair.\n\n=for code :preamble<<enum Mass<g> >>\nsay g.kv; # OUTPUT: «(g 1)␤»\n\n=head2 method pair\n\n    method pair(::?CLASS:D:)\n\nReturns it as a L<C<Pair>|/type/Pair>.\n\n=for code :preamble<<enum Mass<g> >>\nsay g.pair; # OUTPUT: «g => 1␤»\n\n=head2 method CALL-ME\n\n    multi method CALL-ME(|)\n\nReturns an C<Enumeration> instance given an enum value.\n\n    enum Mass ( mg => 1/1000, g => 1/1, kg => 1000/1 );\n    say Mass(1/1000); # OUTPUT: mg\n\n=head2 method pick\n\n    multi method pick(::?CLASS:U:)\n    multi method pick(::?CLASS:U: \\n)\n    multi method pick(::?CLASS:D: *@pos)\n\nIt works on the defined class, selecting one element and eliminating it.\n\n=for code :preamble«enum Norse-gods <Þor Oðin Freija>;»\nsay Norse-gods.pick() for ^3;  # OUTPUT: «Þor␤Freija␤Oðin␤»\n\n=head2 method roll\n\n    multi method roll(::?CLASS:U:)\n    multi method roll(::?CLASS:U: \\n)\n    multi method roll(::?CLASS:D: *@pos)\n\nThey work on the defined class selecting one or C<n> elements without\neliminating them.\n\n=for code :preamble«enum Norse-gods <Þor Oðin Freija>;»\nsay Norse-gods.roll() for ^3;  # OUTPUT: «Freija␤Freija␤Oðin␤»\n\n=head2 method pred\n\n    method pred(::?CLASS:D:)\n\n=for code :preamble«enum Norse-gods <Þor Oðin Freija>;»\nsay Freija.pred;  # OUTPUT: «Oðin␤»\n\n=head2 method succ\n\n    method succ(::?CLASS:D:)\n\n=for code :preamble«enum Norse-gods <Þor Oðin Freija>;»\nsay Oðin.succ;  # OUTPUT: «Freija␤»\n\n=head2 method Numeric\n\n    multi method Numeric(::?CLASS:D:)\n\nTakes a value of an enum and returns it after coercion to L<C<Numeric>|/type/Numeric>:\n\n    enum Numbers ( cool => '42', almost-pi => '3.14', sqrt-n-one => 'i' );\n    say cool.Numeric;       # OUTPUT: «42␤»\n    say almost-pi.Numeric;  # OUTPUT: «3.14␤»\n    say sqrt-n-one.Numeric; # OUTPUT: «0+1i␤»\n\nNote that if the value cannot be coerced to L<C<Numeric>|/type/Numeric>, an exception\nwill be thrown.\n\n=head2 method Int\n\n    multi method Int(::?CLASS:D:)\n\nTakes a value of an enum and returns it after coercion to L<C<Int>|/type/Int>:\n\n    enum Numbers ( cool => '42', almost-pi => '3.14', sqrt-n-one => 'i' );\n    say cool.Int;           # OUTPUT: «42␤»\n    say almost-pi.Int;      # OUTPUT: «3␤»\n    try say sqrt-n-one.Int;\n    say $!.message if $!;   # OUTPUT: «Cannot convert 0+1i to Int: imaginary part not zero␤»\n\nNote that if the value cannot be coerced to L<C<Int>|/type/Int>, an exception will\nbe thrown.\n\n=head2 method Real\n\n    multi method Real(::?CLASS:D:)\n\nTakes a value of an enum and returns it after coercion to L<C<Real>|/type/Real>:\n\n    enum Numbers ( cool => '42', almost-pi => '3.14', sqrt-n-one => 'i' );\n    say cool.Real;           # OUTPUT: «42␤»\n    say almost-pi.Real;      # OUTPUT: «3.14␤»\n    try say sqrt-n-one.Real;\n    say $!.message if $!;    # OUTPUT: «Cannot convert 0+1i to Real: imaginary part not zero␤»\n\nNote that if the value cannot be coerced to L<C<Real>|/type/Real>, an exception will\nbe thrown.\n\n=head2 method C<===>\n\n    multi infix:<===> (Enumeration:D \\a, Enumeration:D \\b)\n\nEquality of C<Enumeration> symbols:\n\n=for code :preamble«enum Norse-gods <Þor Oðin Freija>;»\nsay Norse-gods.pick() === Freija for ^3; # OUTPUT: «False␤False␤True␤»\n\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Exception.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class Exception\n\n=SUBTITLE Anomalous event capable of interrupting normal control-flow\n\n    class Exception {}\n\nAll exceptions that are placed into the C<$!> variable (or into C<$_>\nin C<CATCH> blocks) inherit from C<Exception>. When you call C<die>\nor C<fail> with a non-Exception argument, it is wrapped into an\nL<C<X::AdHoc>|/type/X::AdHoc> object, which also inherits from C<Exception>.\n\nUser-defined exception classes should inherit from C<Exception> too, and\ndefine at least a method C<message>.\n\n    class X::YourApp::SomeError is Exception {\n        method message() {\n            \"A YourApp-Specific error occurred: out of coffee!\";\n        }\n    }\n\n=head1 Methods\n\n=head2 method message\n\n    method message(Exception:D: --> Str:D)\n\nThis is a stub that must be overwritten by subclasses, and should\nreturn the exception message.\n\nSpecial care should be taken that this method does not produce\nan exception itself.\n\n    try die \"Something bad happened\";\n    if ($!) {\n        say $!.message; # OUTPUT: «Something bad happened.␤»\n    }\n\n=head2 method backtrace\n\n    method backtrace(Exception:D:)\n\nReturns the backtrace associated with the exception in a\nL<C<Backtrace>|/type/Backtrace> object or an empty string if there is none. Only\nmakes sense on exceptions that have been thrown at least once.\n\n    try die \"Something bad happened\";\n    with $! { .backtrace.print ; }\n\n=head2 method throw\n\n    method throw(Exception:D:)\n\nThrows the exception.\n\n    my $exception = X::AdHoc.new;    # Totally fine\n    try $exception.throw;            # Throws\n    if ($!) { #`( some handling ) }; # Suppress the exception\n\n=head2 method resume\n\n    method resume(Exception:D:)\n\nResumes control flow where C<.throw> left it when handled in a C<CATCH> block.\n\n    # For example, resume control flow for any exception\n    CATCH { default { .resume } }\n\n=head2 method rethrow\n\n    method rethrow(Exception:D:)\n\nRethrows an exception that has already been thrown at least once.\nThis is different from C<throw> in that it preserves the original\nbacktrace.\n\n    sub f() { die 'Bad' };\n    sub g() { f; CATCH { default { .rethrow } } };\n    g;\n    CATCH { default { say .backtrace.full } };\n\n=head2 routine fail\n\n    multi  fail(Exception $e)\n    method fail(Exception:D:)\n\nExits the calling L<C<Routine>|/type/Routine> and returns a L<C<Failure>|/type/Failure> object wrapping the\nexception.\n\n=begin code\n# A custom exception defined\nclass ForbiddenWord is Exception {\n    has Str $.word;\n    method message { \"This word is forbidden: «$!word»\" }\n}\n\nsub say-word ( $word ) {\n    ForbiddenWord.new(:word($word)).fail if $word eq 'foo';\n    $word.say;\n}\n\nmy $result = say-word(\"foo\");\nsay $result.exception;\n=end code\n\nThe routine form works in the same way, with an alternative syntax:\nC<fail ForbiddenWord.new(:word($word))>.\n\n=head2 method gist\n\n    multi method gist(Exception:D:)\n\nReturns whatever the exception printer should produce for this exception.\nThe default implementation returns message and backtrace separated by\na newline.\n\n    my $e = X::AdHoc.new(payload => \"This exception is pretty bad\");\n    try $e.throw;\n    if ($!) { say $!.gist; };\n    # OUTPUT: «This exception is pretty bad\n    #   in block <unit> at <unknown file> line 1␤»\n\n=head2 method Failure\n\n    method Failure(Exception:D: --> Failure:D)\n\nAvailable as of the 2022.06 release of the Rakudo compiler.\n\nCoerces the C<Exception> into a L<C<Failure>|/type/Failure> object.\n\n=head2 routine die\n\n    multi  die()\n    multi  die(*@message)\n    multi  die(Exception:D $e)\n    method die(Exception:D:)\n\nThrows a fatal C<Exception>. The default exception handler prints each\nelement of the list to\nL«C<$*ERR>|/language/variables#index-entry-%24%2AERR» (STDERR).\n\n=for code\ndie \"Important reason\";\n\nIf the subroutine form is called without arguments, the value of\nL«C<$!> variable|/syntax/$!» is checked. If it is set to a\nL«C<.DEFINITE>|/language/mop#DEFINITE»\nvalue, its value will be used as the C<Exception> to throw if it's of\ntype C<Exception>, otherwise, it will be used as payload of\nL<C<X::AdHoc>|/type/X::AdHoc> exception. If C<$!> is not C<.DEFINITE>,\nL<C<X::AdHoc>|/type/X::AdHoc> with string C<\"Died\"> as payload will be thrown.\n\nC<die> will print by default the line number where it happens\n\n=begin code\ndie \"Dead\";\n# OUTPUT: «(exit code 1) Dead␤\n# in block <unit> at /tmp/dead.raku line 1␤␤»\n=end code\n\nHowever, that default behavior is governed at the C<Exception> level and\nthus can be changed to anything we want by capturing the exception using\nC<CATCH>. This can be used, for instance, to suppress line numbers.\n\n=begin code\nCATCH {\n  default {\n    .payload.say\n  }\n};\ndie \"Dead\" # OUTPUT: «Dead␤»\n=end code\n\n=head2 sub warn\n\n    multi warn(*@message)\n\nThrows a resumable warning exception, which is considered a control\nexception, and hence is invisible to most normal exception handlers.  The\noutermost control handler will print the warning to C<$*ERR>. After printing\nthe warning, the exception is resumed where it was thrown.  To override this\nbehavior, catch the exception in a C<CONTROL> block.  A C<quietly {...}>\nblock is the opposite of a C<try {...}> block in that it will suppress any\nwarnings but pass fatal exceptions through.\n\nTo simply print to C<$*ERR>, please use C<note> instead.  C<warn> should be\nreserved for use in threatening situations when you don't quite want to\nthrow an exception.\n\n    warn \"Warning message\";\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Failure.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class Failure\n\n=SUBTITLE Delayed exception\n\n    class Failure is Nil { }\n\nA C<Failure> is a I<soft> or I<unthrown> L<C<Exception>|/type/Exception>,\nusually generated by calling C<&fail>. It acts as a wrapper around an\nL<C<Exception>|/type/Exception> object.\n\nSink (void) context causes a C<Failure> to throw, i.e. turn into a regular\nexception. The L<C<use fatal> pragma|/language/pragmas#fatal>\ncauses this to happen in all contexts within the pragma's\nscope. Inside L<C<try>\nblocks|/language/exceptions#try_blocks>, C<use fatal>\nis automatically set, and you can I<disable> it with C<no fatal>.\n\nThat means that Failures are generally only useful in cases of\ncode that normally would produce an rvalue; Failures are more or less\nequivalent to Exceptions in code that will frequently be called in sink\ncontext (i.e., for its side-effects, such as with C<say>).\n\nSimilarly, you should generally use C<&fail> only inside code that is\nnormally expected to return something.\n\nChecking a Failure for truth (with the C<Bool> method) or definedness (with\nthe C<defined> method) marks the failure as handled, and causes it not to\nthrow in sink context anymore.\n\nYou can call the C<handled> method to check if a failure has been handled.\n\nCalling methods on unhandled failures propagates the failure. The\nspecification says the result is another C<Failure>; in Rakudo it causes the\nfailure to throw.\n\nBecause a Failure is L<C<Nil>|/type/Nil>, which is undefined, a common idiom\nfor safely executing code that may fail uses a\nL<C<with/else>|/language/control#with_orwith_without> statement:\n\n=begin code\nsub may_fail( --> Numeric:D ) {\n  my $value = (^10).pick || fail \"Zero is unacceptable\";\n  fail \"Odd is also not okay\" if $value % 2;\n  return $value;\n}\n\nwith may_fail() -> $value { # defined, so didn't fail\n  say \"I know $value isn't zero or odd.\"\n} else { # undefined, so failed, and the Failure is the topic\n  say \"Uh-oh: {.exception.message}.\"\n}\n=end code\n\n=head1 Methods\n\n=head2 method new\n\n    multi method new(Failure:D:)\n    multi method new(Failure:U:)\n    multi method new(Failure:U: Exception:D \\exception)\n    multi method new(Failure:U: $payload)\n    multi method new(Failure:U: |cap (*@msg))\n\nReturns a new C<Failure> instance with payload given as argument. If called\nwithout arguments on a C<Failure> object, it will throw; on a type value, it\nwill create an empty C<Failure> with no payload. The latter can be either an\nL<C<Exception>|/type/Exception> or a payload for an L<C<Exception>|/type/Exception>. A typical payload\nwould be a L<C<Str>|/type/Str> with an error message. A list of payloads is also accepted.\n\n    my $e = Failure.new(now.DateTime, 'WELP‼');\n    say $e;\n    CATCH{ default { say .^name, ': ', .Str } }\n    # OUTPUT: «X::AdHoc: 2017-09-10T11:56:05.477237ZWELP‼␤»\n\n=head2 method handled\n\n    method handled(Failure:D: --> Bool:D) is rw\n\nReturns C<True> for handled failures, C<False> otherwise.\n\n    sub f() { fail }; my $v = f; say $v.handled; # OUTPUT: «False␤»\n\nThe C<handled> method is an\nL<lvalue|/language/glossary#lvalue>, see L«routine trait\nC<is rw>|/type/Routine#trait_is_rw», which means you can also use it\nto set the handled state:\n\n    sub f() { fail }\n    my $v = f;\n    $v.handled = True;\n    say $v.handled; # OUTPUT: «True␤»\n\n=head2 method exception\n\n    method exception(Failure:D: --> Exception)\n\nReturns the L<C<Exception>|/type/Exception> object that the failure wraps.\n\n    sub failer() { fail };\n    my $failure = failer;\n    my $ex = $failure.exception;\n    put \"$ex.^name(): $ex\";\n    # OUTPUT: «X::AdHoc: Failed␤»\n\n=head2 method self\n\n    method self(Failure:D: --> Failure:D)\n\nIf the invocant is a L<handled|/routine/handled> C<Failure>, returns it as is.\nIf not handled, throws its L<C<Exception>|/type/Exception>. Since\nL<C<Mu>|/type/Mu> type L«provides C<.self>|/type/Mu#method_self» for every\nclass, calling this method is a handy way to explosively\nfilter out Failures:\n\n    my $num1 = '♥'.Int;\n    # $num1 now contains a Failure object, which may not be desirable\n\n    my $num2 = '♥'.Int.self;\n    # .self method call on Failure causes an exception to be thrown\n\n    my $num3 = '42'.Int.self;\n    # Int type has a .self method, so here $num3 has `42` in it\n\n    (my $stuff = '♥'.Int).so;\n    say $stuff.self; # OUTPUT: «(HANDLED) Cannot convert string to number…»\n    # Here, Failure is handled, so .self just returns it as is\n\n=head2 method Bool\n\n    multi method Bool(Failure:D: --> Bool:D)\n\nReturns C<False>, and marks the failure as handled.\n\n    sub f() { fail };\n    my $v = f;\n    say $v.handled; # OUTPUT: «False␤»\n    say $v.Bool;    # OUTPUT: «False␤»\n    say $v.handled; # OUTPUT: «True␤»\n\n=head2 method Capture\n\n    method Capture()\n\nThrows C<X::Cannot::Capture> if the invocant is a type object or a\nL<handled|/routine/handled> C<Failure>. Otherwise, throws the\ninvocant's L<exception|/routine/exception>.\n\n=head2 method defined\n\n    multi method defined(Failure:D: --> Bool:D)\n\nReturns C<False> (failures are officially undefined), and marks\nthe failure as handled.\n\n    sub f() { fail };\n    my $v = f;\n    say $v.handled; # OUTPUT: «False␤»\n    say $v.defined; # OUTPUT: «False␤»\n    say $v.handled; # OUTPUT: «True␤»\n\n=head2 method list\n\n    multi method list(Failure:D:)\n\nMarks the failure as handled and throws the invocant's\nL<exception|/type/Failure#method_exception>.\n\n=head2 sub fail\n\n    multi fail(--> Nil)\n    multi fail(*@text)\n    multi fail(Exception:U $e  --> Nil )\n    multi fail($payload --> Nil)\n    multi fail(|cap (*@msg) --> Nil)\n    multi fail(Failure:U $f --> Nil)\n    multi fail(Failure:D $fail --> Nil)\n\nExits the calling L<C<Routine>|/type/Routine> and returns a C<Failure> object wrapping the\nexception C<$e> - or, for the C<cap> or C<$payload> form, an\nL<C<X::AdHoc>|/type/X::AdHoc> exception\nconstructed from the concatenation of C<@text>. If the caller\nactivated fatal exceptions via the pragma C<use fatal;>, the exception is\nthrown instead of being returned as a C<Failure>.\n\n    # A custom exception defined\n    class ForbiddenDirectory is Exception {\n        has Str $.name;\n\n        method message { \"This directory is forbidden: '$!name'\" }\n    }\n\n    sub copy-directory-tree ($dir) {\n        # We don't allow for non-directories to be copied\n        fail \"$dir is not a directory\" if !$dir.IO.d;\n        # We don't allow 'foo' directory to be copied too\n        fail ForbiddenDirectory.new(:name($dir)) if $dir eq 'foo';\n        # or above can be written in method form as:\n        # ForbiddenDirectory.new(:name($dir)).fail if $dir eq 'foo';\n        # Do some actual copying here\n        ...\n    }\n\n    # A Failure with X::AdHoc exception object is returned and\n    # assigned, so no throwing Would be thrown without an assignment\n    my $result = copy-directory-tree(\"cat.jpg\");\n    say $result.exception; # OUTPUT: «cat.jpg is not a directory␤»\n\n    # A Failure with a custom Exception object is returned\n    $result = copy-directory-tree('foo');\n    say $result.exception; # OUTPUT: «This directory is forbidden: 'foo'␤»\n\nIf it's called with a generic C<Failure>, an ad-hoc undefined failure is\nthrown; if it's a defined C<Failure>, it will be marked as unhandled.\n\n=begin code\nsub re-fail {\n    my $x = +\"a\";\n    unless $x.defined {\n        $x.handled = True;\n        say \"Something has failed in \\$x \", $x.^name;\n        # OUTPUT: «Something has failed in $x Failure␤»\n        fail($x);\n        return $x;\n    }\n}\n\nmy $x = re-fail;\nsay $x.handled; # OUTPUT: «False␤»\n=end code\n\n=end pod\n"
  },
  {
    "path": "doc/Type/FatRat.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class FatRat\n\n=SUBTITLE Rational number (arbitrary-precision)\n\n    class FatRat is Cool does Rational[Int, Int] {}\n\nA C<FatRat> is a rational number stored with arbitrary size numerator and\ndenominator. Arithmetic operations involving a C<FatRat> and optionally L<C<Int>|/type/Int>\nor L<C<Rat>|/type/Rat> objects return a C<FatRat>, avoiding loss of precision.\n\nSince, unlike L<C<Rat>|/type/Rat>, FatRat arithmetics do not fall back L<C<Num>|/type/Num> at some\npoint, there is a risk that repeated arithmetic operations generate\npathologically large numerators and denominators.\n\nThere are two common ways to generate C<FatRat> objects: through the\nC<FatRat.new(Int, Int)> constructor, which generates them from numerator and\ndenominator, or by calling the C<.FatRat> method on an L<C<Int>|/type/Int> or L<C<Rat>|/type/Rat>\nobject.\n\n=head1 Methods\n\n=head2 method raku\n\n    multi method raku(FatRat:D: --> Str:D)\n\nReturns an implementation-specific string that produces an L<equivalent|/routine/eqv> object\nwhen given to L<EVAL|/routine/EVAL>.\n\n=for code\nsay FatRat.new(1, 2).raku; # OUTPUT: «FatRat.new(1, 2)␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/ForeignCode.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class ForeignCode\n\n=SUBTITLE Rakudo-specific class that wraps around code in other languages (generally NQP)\n\n    class ForeignCode does Callable {}\n\nN<This is a Rakudo specific class, and as such it is advisable not to use it in\nyour own code, since its interface might change or even disappear in the future.\nThis is provided here only as a reference>\n\nC<ForeignCode> is a Raku wrapper around code that is not written originally in\nthat language; its intention is to use these blocks of code in L<C<Callable>|/type/Callable>\ncontexts easily. For instance, subs have some anonymous functions that are\nactually C<ForeignCode>.\n\n=for code\nsub does-nothing(){};\nsay $_.name ~ ' → ' ~ $_.^name for &does-nothing.^methods;\n# OUTPUT: «<anon> → ForeignCode␤<anon> → ForeignCode␤soft → Method␤…»\n\nThis script will map method names to their class, and it shows that routines, in\nparticular, have several methods that are actually C<ForeignCode> instead of\nL<C<Method>|/type/Method>s.\n\n\n=head1 Methods\n\n=head2 method arity\n\n    method arity()\n\nReturns the arity of the enclosed code.\n\n=head2 method count\n\n    method count()\n\nReturns the number of arguments the enclosed code needs.\n\n=head2 method signature\n\n    method signature( ForeignCode:D: )\n\nReturns the signature of the enclosed code.\n\n=head2 method name\n\n    method name()\n\nReturns the name of the enclosed code, or C«<anon>» if it has not received any.\n\n=head2 method gist\n\n    method gist( ForeignCode:D: )\n\nReturns the name of the code by calling C<name>.\n\n=head2 method Str\n\n    method Str( ForeignCode:D: )\n\nReturns the name of the code by calling C<name>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Format.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Format\n\n=SUBTITLE Convert values to a string given a format specification\n\n    class Format { }\n\nA C<Format> is an immutable object containing the logic for\nconverting a set of values to a string given a C<sprintf>\ncompatible format specification.  Acts as a standard string\nin every way, except that it can also be called as a L<C<Callable>|/type/Callable>\nwith arguments to produce a string, just as C<sprintf>.\n\nAvailable as of the 2023.06 release of the Rakudo compiler.\nRequires language level C<6.e>.\n\n=begin code :solo\nuse v6.e.PREVIEW;\nmy $f = Format.new(\"'%5s'\");\nsay $f;                         # OUTPUT: «'%5s'␤»\nsay $f(\"foo\");                  # OUTPUT: «'  foo'␤»\n=end code\n\n=head1 Methods\n\n=head2 method new\n\n=begin code :skip-test<difficult to use v6e.PREVIEW here>\nmethod new($format --> Format:D)\n=end code\n\nCreates a new C<Format> object from a C<sprintf> compatible format\nstring.\n\n=begin code :solo\nuse v6.e.PREVIEW;\nmy $d = Format.new(\"%05d\");\nsay $d;                         # OUTPUT: «%05d␤»\nsay $d(42);                     # OUTPUT: «00042␤»\n=end code\n\n=head2 method Callable\n\n    method Callable(--> Callable:D)\n\nReturns the L<C<Callable>|/type/Callable> that was created from the given format.\nIntended for introspection purposes only, as one can call the\nC<Format> object directly.\n\n=head2 method directives\n\n    method directives(--> List:D)\n\nReturns a list of the directives seen in the given format.\nIntended for introspection purposes.\n\n=begin code :solo\nuse v6.e.PREVIEW;\nmy $d = Format.new(\"%05d%3x:%s\");\nsay $d.directives;              # OUTPUT: «(d x s)␤»\n=end code\n\n=head2 method arity\n\n    method arity(--> List:D)\n\nReturns the B<minimal> number of positional arguments that is\nneeded for this format.  Intended for introspection purposes.\n\n=begin code :solo\nuse v6.e.PREVIEW;\nmy $d = Format.new(\"%05d%3x:%s\");\nsay $d.arity;                   # OUTPUT: «3␤»\n=end code\n\n=head2 method count\n\n    method count(--> List:D)\n\nReturns the B<maximal> number of positional arguments that is\nneeded for this format.  Intended for introspection purposes.\n\n=begin code :solo\nuse v6.e.PREVIEW;\nmy $d = Format.new(\"%05d%3x:%s\");\nsay $d.count;                   # OUTPUT: «3␤»\n=end code\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Formatter.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Formatter\n\n=SUBTITLE Produce Callable for given format specification\n\n    class Formatter { }\n\nThe C<Formatter> class does not produce any instances of itself,\nbut instead serves as an access point to the \"change a 'sprintf'\ncompatible format specification into Callable\" functionality.\n\nAvailable as of the 2023.06 release of the Rakudo compiler.\nRequires language level C<6.e>.\n\n=begin code :solo\nuse v6.e.PREVIEW;\nmy &handle = Formatter.new(\"'%5s'\");\nsay handle(\"foo\");              # OUTPUT: «'  foo'␤»\n=end code\n\n=head1 Methods\n\n=head2 method new\n\n    method new($format --> Callable:D)\n\nReturns a cached L<C<Callable>|/type/Callable> object from a C<sprintf> compatible\nformat string.  Will create a new L<C<Callable>|/type/Callable> object if the\ngiven format string had not been seen before.\n\n=begin code :solo\nuse v6.e.PREVIEW;\nmy &zero5 = Formatter.new(\"%05d\");\nsay zero5(42);                  # OUTPUT: «00042␤»\n=end code\n\n=head2 method CODE\n\n    method CODE(--> Callable:D)\n\nReturns an uncached L<C<Callable>|/type/Callable> object from a C<sprintf>\ncompatible format string.  Intended to be used in compile-time\nsituations where caching is neither important nor wanted.\n\n=head2 method AST\n\n=for code :preamble<use experimental :rakuast>\nmethod AST(--> RakuAST::Node:D)\n\nReturns a L<C<RakuAST>|/type/RakuAST> representation of the L<C<Callable>|/type/Callable> for\nthe given C<sprintf> compatible format string.  Intended to\nbe used for debugging.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Grammar.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Grammar\n\n=SUBTITLE Formal grammar made up of named regexes\n\n    class Grammar is Match {}\n\nEvery type declared with C<grammar>, and not explicitly stating its superclass,\nbecomes a subclass of C<Grammar>.\n\n    grammar Identifier {\n        token TOP       { <initial> <rest>* }\n        token initial   { <+myletter +[_]> }\n        token rest      { <+myletter +mynumber +[_]> }\n        token myletter  { <[A..Za..z]> }\n        token mynumber  { <[0..9]> }\n    }\n\n    say Identifier.isa(Grammar);                # OUTPUT: «True␤»\n    my $match = Identifier.parse('W4anD0eR96');\n    say ~$match;                                # OUTPUT: «W4anD0eR96␤»\n\nMore L<documentation on grammars|/language/grammars> is available.\n\n=head1 Methods\n\n=head2 method parse\n\n    method parse($target, :$rule = 'TOP',  Capture() :$args = \\(), Mu :$actions = Mu, *%opt)\n\nParses the C<$target>, which will be coerced to L<C<Str>|/type/Str> if it isn't\none, using C<$rule> as the starting rule. Additional C<$args> will be passed\nto the starting rule if provided.\n\n    grammar RepeatChar {\n        token start($character) { $character+ }\n    }\n\n    say RepeatChar.parse('aaaaaa', :rule('start'), :args(\\('a')));\n    say RepeatChar.parse('bbbbbb', :rule('start'), :args(\\('b')));\n\n    # OUTPUT:\n    # ｢aaaaaa｣\n    # ｢bbbbbb｣\n\nIf the C<actions> named argument is provided, it will be used as an actions\nobject, that is, for each successful regex match, a method of the same name,\nif it exists, is called on the actions object, passing the match object as the\nsole positional argument.\n\n    my $actions = class { method TOP($/) { say \"7\" } };\n    grammar { token TOP { a { say \"42\" } b } }.parse('ab', :$actions);\n    # OUTPUT: «42␤7␤»\n\nAdditional named arguments are used as options for matching, so you can for example specify\nthings like C<:pos(4)> to start parsing from the fifth (:pos is zero-based) character.\nAll L<matching adverbs|/language/regexes#Adverbs> are allowed, but not all of\nthem take effect. There are several types of adverbs that a regex can have,\nsome of which apply at compile time, like C<:s> and C<:i>. You cannot pass those\nto C<.parse>, because the regexes have already been compiled. But, you can pass\nthose adverbs that affect the runtime behavior, such as C<:pos> and C<:continue>.\n\n=for code :preamble<grammar RepeatChar {}>\nsay RepeatChar.parse('bbbbbb', :rule('start'), :args(\\('b')), :pos(4)).Str;\n# OUTPUT: «bb␤»\n\nMethod C<parse> only succeeds if the cursor has arrived at the end of the\ntarget string when the match is over. Use L<method subparse|/routine/subparse>\nif you want to be able to stop in the middle.\n\nThe top regex in the grammar will be allowed to backtrack.\n\nReturns a L<C<Match>|/type/Match> on success, and L<C<Nil>|/type/Nil> on\nfailure.\n\n=head2 method subparse\n\n    method subparse($target, :$rule = 'TOP', Capture() :$args = \\(),  Mu :$actions = Mu, *%opt)\n\nDoes exactly the same as L<method parse|/routine/parse>, except that cursor\ndoesn't have to reach the end of the string to succeed. That is, it doesn't\nhave to match the whole string.\n\nNote that unlike L<method parse|/routine/parse>, C<subparse> I<always> returns\na L<C<Match>|/type/Match>, which will be a failed match (and thus falsy),\nif the grammar failed to match.\n\n    grammar RepeatChar {\n        token start($character) { $character+ }\n    }\n\n    say RepeatChar.subparse('bbbabb', :rule('start'), :args(\\('b')));\n    say RepeatChar.parse(   'bbbabb', :rule('start'), :args(\\('b')));\n    say RepeatChar.subparse('bbbabb', :rule('start'), :args(\\('a')));\n    say RepeatChar.subparse('bbbabb', :rule('start'), :args(\\('a')), :pos(3));\n\n\n    # OUTPUT:\n    # ｢bbb｣\n    # Nil\n    # #<failed match>\n    # ｢a｣\n\n=head2 method parsefile\n\n    method parsefile(Str(Cool) $filename, :$enc, *%opts)\n\nReads file C<$filename> encoding by C<$enc>, and parses it. All named arguments\nare passed on to L<method parse|/routine/parse>.\n\n    grammar Identifiers {\n        token TOP        { [<identifier><.ws>]+ }\n        token identifier { <initial> <rest>* }\n        token initial    { <+myletter +[_]> }\n        token rest       { <+myletter +mynumber +[_]> }\n        token myletter   { <[A..Za..z]> }\n        token mynumber   { <[0..9]> }\n    }\n\n    say Identifiers.parsefile('users.txt', :enc('UTF-8'))\n        .Str.trim.subst(/\\n/, ',', :g);\n\n    # users.txt :\n    # TimToady\n    # lizmat\n    # jnthn\n    # moritz\n    # zoffixznet\n    # MasterDuke17\n\n    # OUTPUT: «TimToady,lizmat,jnthn,moritz,zoffixznet,MasterDuke17␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Hash.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class Hash\n\n=SUBTITLE Mapping from strings to itemized values\n\n    class Hash is Map { }\n\nA C<Hash> is a mutable L<C<Map>|/type/Map>; it implements L<C<Associative>|/type/Associative> through\nits inheritance of L<C<Map>|/type/Map> and as such provides support for looking up values\nusing keys, providing support for L<associative\nsubscripting|/language/subscripts#Methods_to_implement_for_associative_subscripting>.\n\nC<Hash> is the default type for variables with the C<%> sigil.\n\nHashes are mutable mappings from keys to values, known in other programming languages\nas I<dict>s (Python), I<object>s (Javascript) or I<Hash Map>s (Java).\n\nBasic usage:\n\n    # initialization with pairs:\n    my %capitals = Spain => 'Madrid', 'United States' => 'Washington DC';\n\n    # adding another pair:\n    %capitals{'Zimbabwe'} = 'Harare';\n\n    # accessing a value by key:\n    my $country = 'Spain';\n    say \"The capital of $country is %capitals{$country}\";\n\n    # getting all keys:\n    say \"I know the capitals of these countries: \", %capitals.keys.sort.join(', ');\n\n    # check if a key is in a hash:\n    if %capitals{'Europe'}:exists {\n        # not executed\n    }\n\n    # iterating over keys and values (unordered):\n    for %capitals.kv -> $country, $capital {\n        say \"$capital is the capital of $country\";\n    }\n\nAlthough the order of the hashes is guaranteed to be random in every single\ncall, still successive calls to C<.keys> and C<.values> are guaranteed to return\nthem in the same order:\n\n    my %orig = :1a, :2b; my %new = :5b, :6c;\n    %orig{ %new.keys } = %new.values;\n    say %orig.raku; # OUTPUT: «{:a(1), :b(5), :c(6)}␤»\n\nIn this case, C<b> will always be associated to 5 and C<c> to 6; even if two\nsuccessive calls to C<keys> will return them in different order. Successive\ncalls to any of them separately and repeatedly will always return the same order\nin any program invocation.\n\nPlease see the section on L<hash literals|/language/syntax#Hash_literals> for\ndifferent ways to declare a hash. Additionally, they can be declared using curly\nbraces as long as these rules are followed:\n\n=item Empty curly braces will always declare an empty hash.\n=item A reference to $_ (even implicit) will instead declare a block.\n=item A L<C<Pair>|/type/Pair> or variable with C<%> as the first element will declare a hash.\n\n=for code\ngiven 3 { say WHAT {3 => 4, :b}  };     # OUTPUT: «(Hash)␤»\ngiven 3 { say WHAT {3 => 4, :b($_)} };  # OUTPUT: «(Block)␤»\ngiven 3 { say WHAT {3 => 4, :b(.Num)} };# OUTPUT: «(Block)␤»\nsay { 'a',:b(3), 'c' }.^name;           # OUTPUT: «Block␤»\n\nThe next-to-last two cases are examples of the generation of L<C<Block>|/type/Block>s in the\npresence of the topic variable C<$_>. The last case does not meet the third\ncriterion for generating a hash, and thus generates a L<C<Block>|/type/Block>.\n\nA % in front of parentheses or square brackets will generate a C<Hash> as long as\nthe elements can be paired.\n\n    say %( 'a', 3, :b(3), 'c', 3 ).^name; # OUTPUT: «Hash␤»\n\nElements in this hash can be paired both sides of the Pair C<:b(3)>.\n\n    say %(«a b c 1 2 3»).^name;           # OUTPUT: «Hash␤»\n\nAn empty hash can be initialized either with empty curly braces or, since 6.d, C<%()>.\n\n    say %().^name; # OUTPUT: «Hash␤»\n    say {}.^name;  # OUTPUT: «Hash␤»\n\nHashes can be parameterized with types. You can change the type of the keys like this:\n\n    my %next-prime{Int} = 2 => 3, 3 => 5, 5 => 7, 7 => 11, 11 => 13;\n\nThe type of the values defaults to L<C<Mu>|/type/Mu>, but you can constrain it to other types:\n\n    my Array %lists;\n\nYou can combine these two features:\n\n    my Array %next-primes{Int} = 2 => [3, 5], 11 => [13, 17];\n\n=head1 Methods\n\n=head2 method classify-list\n\n    multi method classify-list(&mapper, *@list, :&as --> Hash:D)\n    multi method classify-list(%mapper, *@list, :&as --> Hash:D)\n    multi method classify-list(@mapper, *@list, :&as --> Hash:D)\n\nPopulates a C<Hash> by classifying the possibly-empty C<@list> of\nvalues using the given C<mapper>, optionally altering the values using the\nC<:&as> L«C<Callable>|/type/Callable». The C<@list> cannot be lazy.\n\nThe mapper can be a L«C<Callable>|/type/Callable» that takes a single argument,\nan L«C<Associative>|/type/Associative», or an L«C<Iterable>|/type/Iterable»;\nthis L<C<Callable>|/type/Callable> is guaranteed to be called only once per item.\nWith L«C<Associative>|/type/Associative» and an L«C<Iterable>|/type/Iterable»\nmappers, the values in the C<@list> represent the key and index of the mapper's\nvalue respectively. A L«C<Callable>|/type/Callable» mapper will be executed\nonce per each item in the C<@list>, with that item as the argument and its\nreturn value will be used as the mapper's value.\n\n=head3 Simple classification\n\nIn simple classification mode, each mapper's value is any non-L<C<Iterable>|/type/Iterable> and\nrepresents a key to classify C<@list>'s item under:\n\n=begin code\nsay % .classify-list: { $_ %% 2 ?? 'even' !! 'odd' }, ^10;\n# OUTPUT: «{even => [0 2 4 6 8], odd => [1 3 5 7 9]}␤»\n\nmy @mapper = <zero one two three four five>;\nmy %hash = foo => 'bar';\nsay %hash.classify-list: @mapper, 1, 2, 3, 4, 4;\n# OUTPUT: «{foo => bar, four => [4 4], one => [1], three => [3], two => [2]}␤»\n=end code\n\nThe mapper's value is used as the key of the C<Hash> to\nwhich the C<@list>'s item will be L«C<push>ed|/routine/push». See\nL«C<.categorize-list>|/routine/categorize-list» if you wish to classify an item\ninto multiple categories at once.\n\n=head3 Multi-level classification\n\nIn multi-level classification mode, each mapper's value is an\nL«C<Iterable>|/type/Iterable» that represents a tree of hash keys to classify\nC<@list>'s item under:\n\n    say % .classify-list: {\n        [\n            (.is-prime ?? 'prime' !! 'non-prime'),\n            ($_ %% 2   ?? 'even'  !! 'odd'      ),\n        ]\n    }, ^10;\n    # OUTPUT:\n    # {\n    #     non-prime => {\n    #         even => [0 4 6 8],\n    #         odd  => [1 9]\n    #     },\n    #     prime => {\n    #         even => [2],\n    #         odd  => [3 5 7]\n    #     }\n    # }\n\nIn the case we are using L<C<Iterable>|/type/Iterable>s and not L<C<Callable>|/type/Callable>s, each of those\nL«C<Iterable>|/type/Iterable»s must\nhave the same number\nof elements, or the method will throw an exception. This restriction exists to\navoid conflicts when the same key is a leaf of one value's classification but a\nnode of another value's classification.\n\n=for code\nmy @mapper = [['1a','1b','1c'],['2a','2b','2c'],['3a','3b','3c']];\nsay % .classify-list: @mapper, 1,2,1,1,2,0;\n# OUTPUT: «{1a => {1b => {1c => [0]}}, 2a => {2b => {2c => [1 1 1]}}, 3a => {3b => {3c => [2 2]}}}␤»\n\nEvery element of the array represents a different level in the tree, with the\nelements of the list that is being mapped used as index, and the elements of\nthe mapper array used as keys to the different levels. So C<0> selects the\nfirst sub-array and then the subsequent levels are built by running over the\nrest of the elements of that sub-array.\n\n=for code\nmy @mapper = [['1a','1b'],['2a','2b'],['3a','3b']];\nsay % .classify-list: @mapper, 1,0,1,1,1,0,2;\n# OUTPUT: «{1a => {1b => [0 0]}, 2a => {2b => [1 1 1 1]}, 3a => {3b => [2]}}␤»\n\nFrom version 6.d, trying to use L<C<Iterable>|/type/Iterable>s of different size will throw an\nerror:\n\n=for code\nmy @mapper = [<1a 1b>, <2a 2b 2fail>];\nsay % .classify-list: @mapper, 1,0,1,1,1,0;\n# OUTPUT: «mapper on classify-list computed to an item with different number\n# of elements in it than previous items, which cannot be used because all\n# values need to have the same number of elements. Mixed-level classification\n# is not supported.␤  in block <unit>…»\n\n=head3 C<:&as> value modifier\n\nIf C<:&as> L«C<Callable>|/type/Callable» argument is specified, it will be\ncalled once per each item of C<@list>, with the value as the argument, and\nits return value will be used instead of the original C<@list>'s item:\n\n    say % .classify-list: :as{\"Value is $_\"}, { $_ %% 2 ?? 'even' !! 'odd' }, ^5;\n    # OUTPUT (slightly altered manually, for clarity):\n    # {\n    #     even => ['Value is 0', 'Value is 2', 'Value is 4'],\n    #     odd  => ['Value is 1', 'Value is 3']\n    # }\n\n=head2 method categorize-list\n\n    multi method categorize-list(&mapper, *@list, :&as --> Hash:D)\n    multi method categorize-list(%mapper, *@list, :&as --> Hash:D)\n    multi method categorize-list(@mapper, *@list, :&as --> Hash:D)\n\nPopulates a C<Hash> by classifying the\npossibly-empty C<@list> of values using the given C<mapper>, optionally\naltering the values using the C<:&as> L«C<Callable>|/type/Callable». The\nC<@list> cannot be lazy.\n\nThe mapper can be a L«C<Callable>|/type/Callable» that takes a single argument,\nan L«C<Associative>|/type/Associative», or an L«C<Iterable>|/type/Iterable».\nWith L«C<Associative>|/type/Associative» and an L«C<Iterable>|/type/Iterable»\nmappers, the values in the C<@list> represent the key and index of the mapper's\nvalue respectively. A L«C<Callable>|/type/Callable» mapper will be executed\nonce per each item in the C<@list>, with that item as the argument and its\nreturn value will be used as the mapper's value.\n\n=head3 Simple categorization\n\nThe mapper's value is expected to be a possibly empty list of\nnon-L«C<Iterable>|/type/Iterable»s that represent categories to place the value\ninto:\n\n    say % .categorize-list: {\n        gather {\n            take 'prime'   if .is-prime;\n            take 'largish' if $_ > 5;\n            take $_ %% 2 ?? 'even' !! 'odd';\n        }\n    }, ^10;\n\n    # OUTPUT:\n    # {\n    #     prime   => [2 3 5 7]\n    #     even    => [0 2 4 6 8],\n    #     odd     => [1 3 5 7 9],\n    #     largish => [6 7 8 9],\n    # }\n\nNotice how some items, e.g. C<6> and C<7>, are present in several categories.\n\n=head3 Multi-level categorization\n\nIn multi-level categorization, the categories produced by the mapper are\nL<Iterables|/type/Iterable> and categorization combines features\nof L<classify|/routine/classify>, by producing nested hashes of classifications\nfor each category.\n\n    say % .categorize-list: {\n        [\n            $_ > 5    ?? 'largish' !! 'smallish',\n            .is-prime ?? 'prime'   !! 'non-prime',\n        ],\n    }, ^10;\n\n    # OUTPUT:\n    # {\n    #     largish => {\n    #         non-prime => [6 8 9],\n    #         prime     => [7]\n    #     },\n    #     smallish => {\n    #         non-prime => [0 1 4],\n    #         prime     => [2 3 5]\n    #     }\n    # }\n\nThe mapper in the snippet above produces a single-item list (note the\nsignificant\ntrailing comma) with a two-item L<C<Array>|/type/Array> in it. The first item in that array\nindicates the first level of classification: the C<largish>/C<smallish>\ncategories the routine produces. The second item in that array indicates\nfurther levels of classification, in our case the classification into\nC<prime>/C<non-prime> inside of each category.\n\nB<NOTE:> every L«C<Iterable>|/type/Iterable»s category\nmust have the same number of elements, or the method will throw an exception.\nThis restriction exists to avoid conflicts when the same key is a\nleaf of one value's classification but a node of another value's classification.\n\n=head3 C<:&as> value modifier\n\nIf C<:&as> L«C<Callable>|/type/Callable» argument is specified, it will be\ncalled once per each item of C<@list>, with the value as the argument, and\nits return value will be used instead of the original C<@list>'s item:\n\n    say % .categorize-list: :as{\"Value is $_\"}, { $_ %% 2 ?? 'even' !! 'odd' }, ^5;\n    # OUTPUT (slightly altered manually, for clarity):\n    # {\n    #     even => ['Value is 0', 'Value is 2', 'Value is 4'],\n    #     odd  => ['Value is 1', 'Value is 3']\n    # }\n\n=head2 method push\n\n    method push(Hash:D: +new)\n\nAdds the C<new> elements to the hash with the same semantics as hash\nassignment, but with three exceptions:\n\n=item The hash isn't emptied first, i.e. old pairs are not deleted.\n\n=item If a key already exists in the hash, and the corresponding value is an\nL<C<Array>|/type/Array>, the new value is pushed onto the array (instead of replacing it).\n\n=item If a key already exists in the hash, and the corresponding value is not\nan L<C<Array>|/type/Array>, old and new value are both placed into an array in the place\nof the old value.\n\nExample:\n\n    my %h  = a => 1;\n    %h.push: (a => 1);              # a => [1,1]\n    %h.push: (a => 1) xx 3 ;        # a => [1,1,1,1,1]\n    %h.push: (b => 3);              # a => [1,1,1,1,1], b => 3\n    %h.push('c' => 4);              # a => [1,1,1,1,1], b => 3, c => 4\n    push %h, 'd' => 5;              # a => [1,1,1,1,1], b => 3, c => 4, d => 5\n\nPlease note that literal pairs in the argument list may be interpreted as\nL<named arguments|/type/Capture> and as such won't end up in the C<Hash>:\n\n    my %h .= push(e => 6);\n    say %h.raku; # OUTPUT: «{}␤»\n\nUse the corresponding L<subroutine|/type/independent-routines#sub_push> to\ncatch this kind of mistake:\n\n    push my %h, f => 7;\n    CATCH { default { put .message } };\n    # OUTPUT: «Unexpected named argument 'f' passed␤»\n\nAlso note that push can be used as a replacement for assignment during hash\ninitialization very useful ways. Take for instance the case of an inverted\nindex:\n\n    my %wc = 'hash' => 323, 'pair' => 322, 'pipe' => 323;\n    (my %inv).push: %wc.invert;\n    say %inv;                     # OUTPUT: «{322 => pair, 323 => [pipe hash]}␤»\n\nNote that such an initialization could also be written as\n\n    my %wc = 'hash' => 323, 'pair' => 322, 'pipe' => 323;\n    my %inv .= push: %wc.invert;\n\nB<Note:> Compared to L«C<append>|/routine/append», C<push> will add the given\nvalue as is, whereas C<append> will L«C<slip>|/routine/slip» it in:\n\n    my %ha = :a[42, ]; %ha.push: \"a\" => <a b c a>;\n    say %ha; # OUTPUT: «{a => [42 (a b c a)]}␤»\n\n    my %hb = :a[42, ]; %hb.append: \"a\" => <a b c a>;\n    say %hb; # OUTPUT: «{a => [42 a b c a]}␤»\n\n=head2 method append\n\n    method append(+@values)\n\nAppend the provided Pairs or even sized list to the Hash. If a key already\nexists, turn the existing value into an L<C<Array>|/type/Array> and push new value\nonto that L<C<Array>|/type/Array>. Please note that you can't mix even sized lists and lists\nof Pairs. Also, bare L<C<Pair>|/type/Pair>s or colon pairs will be treated as L<named\narguments|/language/signatures#Positional_vs._named_arguments> to C<.append>.\n\n    my %h = a => 1;\n    %h.append('b', 2, 'c', 3);\n    %h.append( %(d => 4) );\n    say %h;\n    # OUTPUT: «{a => 1, b => 2, c => 3, d => 4}␤»\n    %h.append('a', 2);\n    # OUTPUT: «{a => [1 2], b => 2, c => 3, d => 4}␤»\n\nB<Note:> Compared to L«C<push>|/routine/push», C<append> will\nL«C<slip>|/routine/slip» in the given value, whereas C<push> will add it as\nis:\n\n    my %hb = :a[42, ]; %hb.append: \"a\" => <a b c a>;\n    say %hb; # OUTPUT: «{a => [42 a b c a]}␤»\n\n    my %ha = :a[42, ]; %ha.push: \"a\" => <a b c a>;\n    say %ha; # OUTPUT: «{a => [42 (a b c a)]}␤»\n\n=head2 method default\n\n    method default(Hash:D:)\n\nReturns the default value of the invocant, i.e. the value which is returned when\na non existing key is used to access an element in the C<Hash>. Unless the\nC<Hash> is declared as having a default value by using the\nL<is default|/type/Variable#trait_is_default> trait the method returns the type object\nC<(Any)>.\n\n    my %h1 = 'apples' => 3, 'oranges' => 7;\n    say %h1.default;                                       # OUTPUT: «(Any)␤»\n    say %h1{'bananas'};                                    # OUTPUT: «(Any)␤»\n\n    my %h2 is default(1) = 'apples' => 3, 'oranges' => 7;\n    say %h2.default;                                       # OUTPUT: «1␤»\n    say %h2{'apples'} + %h2{'bananas'};                    # OUTPUT: «4␤»\n\n=head2 method keyof\n\n    method keyof()\n\nReturns the type constraint for the keys of the invocant. For\nnormal hashes the method returns the coercion type C<(Str(Any))>\nwhile for L<non-string keys|/language/hashmap#Non-string_keys_(object_hash)>\nhashes the type used in the declaration of the C<Hash> is returned.\n\n    my %h1 = 'apples' => 3, 'oranges' => 7;  # (no key type specified)\n    say %h1.keyof;                           # OUTPUT: «(Str(Any))␤»\n\n    my %h2{Str} = 'oranges' => 7;            # (keys must be of type Str)\n    say %h2.keyof;                           # OUTPUT: «(Str)␤»\n    %h2{3} = 'apples';                       # throws exception\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::TypeCheck::Binding: Type check failed in binding to key; expected Str but got Int (3)␤»\n\n    my %h3{Int};                             # (this time, keys must be of type Int)\n    %h3{42} = 4096;\n    say %h3.keyof;                           # OUTPUT: «(Int)␤»\n\n=head2 method of\n\n    method of(Hash:D:)\n\nReturns the type constraint for the values of the invocant. By default,\ni.e., if no type constraint is given during declaration, the method\nreturns C<(Mu)>.\n\n    my %h1 = 'apples' => 3, 'oranges' => 7;  # (no type constraint specified)\n    say %h1.of;                              # OUTPUT: «(Mu)␤»\n\n    my Int %h2 = 'oranges' => 7;             # (values must be of type Int)\n    say %h2.of;                              # OUTPUT: «(Int)␤»\n\n=head2 routine dynamic\n\n    method dynamic(--> Bool:D)\n\nReturns C<True> if the invocant has been declared with the\nL<is dynamic|/routine/is dynamic> trait.\n\n    my %a;\n    say %a.dynamic;                          # OUTPUT: «False␤»\n\n    my %b is dynamic;\n    say %b.dynamic;                          # OUTPUT: «True␤»\n\nIf you declare a variable with the C<*> twigil C<is dynamic> is implied.\n\n    my %*b;\n    say %*b.dynamic;                         # OUTPUT: «True␤»\n\nNote that in the L<C<Scalar>|/type/Scalar> case you have to use the C<VAR> method\nin order to get correct information.\n\n    my $s is dynamic = %('apples' => 5);\n    say $s.dynamic;                   # OUTPUT: «False␤»  (wrong, don't do this)\n    say $s.VAR.dynamic;               # OUTPUT: «True␤»   (correct approach)\n\n=head1 Subscript Adverbs\n\nSome methods are implemented as adverbs on subscripts\n(consult the L<operators|/language/operators#postcircumfix_{_}> documentation\nfor more information).\n\n=head2 C<:exists>\n\nThe adverb C<:exists> returns C<Bool::True> if a key exists in the Hash. If more\nthan one key is supplied it returns a L<C<List>|/type/List> of L<C<Bool>|/type/Bool>.\n\n    my %h = a => 1, b => 2;\n    say %h<a>:exists;   # OUTPUT: «True␤»\n    say %h<a b>:exists; # OUTPUT: «(True True)␤»\n\n=head2 C<:delete>\n\nUse C<:delete> to remove a L<C<Pair>|/type/Pair> from the C<Hash>.  In addition, the value\nis always returned but the removal only happens if delete is true.\n\n    my %h = a => 1;\n    say %h;         # OUTPUT: «{a => 1}␤»\n    say %h.elems;   # OUTPUT: «1␤»\n\n    %h<a>:delete;\n    say %h;         # OUTPUT: «{}␤»\n    say %h.elems;   # OUTPUT: «0␤»\n\n=head2 C<:p>\n\nThe adverb C<:p> returns a L<C<Pair>|/type/Pair> or a List of L<C<Pair>|/type/Pair> instead of just the\nvalue.\n\n    my %h = a => 1, b => 2;\n    say %h<a>:p;    # OUTPUT: «a => 1␤»\n    say %h<a b>:p;  # OUTPUT: «(a => 1 b=> 2)␤»\n\n=head2 C<:v> and C<:k>\n\nThe adverbs C<:v> and C<:k> return the key or value or a list thereof.\n\n    my %h = a => 1, b => 2;\n    say %h<a>:k;    # OUTPUT: «a␤»\n    say %h<a b>:k;  # OUTPUT: «(a b)␤»\n\nThe adverb C<:kv> returns a list of keys and values.\n\n    my %h = a => 1, b => 2, c => 3;\n    say %h<a c>:kv;  # OUTPUT: «(a 1 c 3)␤»\n\nYou can also use the adverbs without knowing anything about the hash by using\nempty angle brackets in which case all the keys and values will be listed:\n\n    my %h1 = a => 1;\n    my %h2 = a => 1, b => 2;\n    say %h1<>:k; # OUTPUT: «(a)␤»\n    say %h1<>:v; # OUTPUT: «(1)␤»\n    say %h2<>:k; # OUTPUT: «(a b)␤»\n    say %h2<>:v; # OUTPUT: «(1 2)␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/HyperSeq.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class HyperSeq\n\n=SUBTITLE An object for performing batches of work in parallel with ordered\noutput\n\n    class HyperSeq does Iterable does Sequence { }\n\nA C<HyperSeq> is the intermediate object used when\nL<C<hyper>|/routine/hyper> is invoked on a L<C<Seq>|/type/Seq>. In general,\nit's not intended for direct consumption by the developer.\n\n=head1 Methods\n\n\n=head2 method iterator\n\n    method iterator(HyperSeq:D: --> Iterator:D)\n\nReturns the underlying iterator.\n\n=head2 method grep\n\n    method grep(HyperSeq:D: $matcher, *%options)\n\nApplies C<grep> to the C<HyperSeq> similarly to how it would do it on a L<C<Seq>|/type/Seq>.\n\n=for code\nmy @hyped = (^10000).map(*²).hyper;\n@hyped.grep( * %% 3 ).say;\n# OUTPUT: «(0 9 36 81 144 ...)␤»\n\nWhen you use C<hyper> on a L<C<Seq>|/type/Seq>, this is the method that is actually called.\n\n=head2 method map\n\n    method map(HyperSeq:D: $matcher, *%options)\n\nUses maps on the C<HyperSeq>, generally created by application of C<hyper> to\n a preexisting L<C<Seq>|/type/Seq>.\n\n=head2 method invert\n\n    method invert(HyperSeq:D:)\n\nInverts the C<HyperSeq> created from a L<C<Seq>|/type/Seq> by C<.hyper>.\n\n=head2 method hyper\n\n    method hyper(HyperSeq:D:)\n\nReturns the object.\n\n=head2 method race\n\n    method race(HyperSeq:D:)\n\nCreates a L<C<RaceSeq>|/type/RaceSeq> object out of the current one.\n\n=head2 method serial\n\n    multi method serial(HyperSeq:D:)\n\nConverts the object to a L<C<Seq>|/type/Seq> and returns it.\n\n=head2 method is-lazy\n\n    method is-lazy(--> False )\n\nReturns C<False>.\n\n\n=head2 method sink\n\n    method sink(--> Nil)\n\nSinks the underlying data structure, producing any side effects.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/HyperWhatever.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class HyperWhatever\n\n=SUBTITLE Placeholder for multiple unspecified values/arguments\n\n    class HyperWhatever { }\n\nC<HyperWhatever> is very similar in functionality to L<C<Whatever>|/type/Whatever>. The\ndifference lies in C<HyperWhatever> standing in for I<multiple> values, rather\nthan a single one.\n\n=head1 Standalone term\n\nJust like with L<C<Whatever>|/type/Whatever>, if a\nC<HyperWhatever> is used as a term on its own, no priming\nis done and the C<HyperWhatever> object will be used as-is:\n\n    sub foo ($arg) { say $arg.^name }\n    foo **; # OUTPUT: «HyperWhatever␤»\n\nYou can choose to interpret such a value as standing for multiple values in your\nown routines. In core, a C<HyperWhatever> can be used with\nthis meaning when smartmatching with L<C<List>|/type/List>s:\n\n    say (1, 8)                ~~ (1, **, 8); # OUTPUT: «True␤»\n    say (1, 2, 4, 5, 6, 7, 8) ~~ (1, **, 8); # OUTPUT: «True␤»\n    say (1, 2, 8, 9)          ~~ (1, **, 8); # OUTPUT: «False␤»\n\nWherever a C<HyperWhatever> appears in the list on the\nright-hand side means any number of elements can fill that space in the list\nbeing smartmatched.\n\n=head1 Priming\n\nWhen it comes to priming, the C<HyperWhatever> follows the\nsame rules as L<C<Whatever>|/type/Whatever>. The only difference is\nC<HyperWhatever> produces a L<C<Callable>|/type/Callable> with\na L«C<*@> slurpy|/language/signatures#Flattening_slurpy:_*@» as a signature:\n\n    say (**²)(1, 2, 3, 4, 5); # OUTPUT: «(1 4 9 16 25)␤»\n\nA C<HyperWhatever> closure can be imagined as a\nL«C<WhateverCode>|/type/WhateverCode» with B<another> sub wrapped around it\nthat simply maps each element in the arguments over:\n\n    my &hyper-whatever = sub (*@args) { map *², @args }\n    say hyper-whatever(1, 2, 3, 4, 5); # OUTPUT: «(1 4 9 16 25)␤»\n\nWhen priming, mixing C<HyperWhatever> with\nL<C<Whatever>|/type/Whatever> is not permitted.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/ArgFiles.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::ArgFiles\n\n=SUBTITLE Iterate over contents of files specified on command line\n\n   class IO::ArgFiles is IO::CatHandle { }\n\nThis class exists for backwards compatibility reasons and provides no additional\nmethods to L«C<IO::CatHandle>|/type/IO::CatHandle», so it can be used in the same way as it, for\ninstance, in this way:\n\n=for code\nmy $argfiles = IO::ArgFiles.new(@*ARGS);\n.say for $argfiles.lines;\n\nIf invoked with C<raku io-argfiles.raku *.raku> it will print the contents of all\nthe files with that extension in the directory. However, that is totally\nequivalent to:\n\n=for code\nmy $argfiles = IO::CatHandle.new(@*ARGS);\n.say for $argfiles.lines;\n\n=head1 Variables\n\n=head2 C<$*ARGFILES>\n\nThis class is the magic behind the C<$*ARGFILES> variable, which provides a way\nto iterate over files passed in to the program on the command line (i.e.\nelements of L<C«@*ARGS»|/language/variables#index-entry-%40%2AARGS>). Thus the\nexamples above can be simplified like so:\n\n    .say for $*ARGFILES.lines;\n\n    # or\n    while ! $*ARGFILES.eof {\n        say $*ARGFILES.get;\n    }\n\n    # or\n    say $*ARGFILES.slurp;\n\nSave one of the variations above in a file, say C<argfiles.raku>.  Then create\nanother file (named, say C<sonnet18.txt> with the contents:\n\n=for code :lang<text>\nShall I compare thee to a summer's day?\n\nRunning the command\n\n=for code :lang<text>\n$ raku argfiles.raku sonnet18.txt\n\nwill then give the output\n\n=for code :lang<text>\nShall I compare thee to a summer's day?\n\nAs of 6.d language, C<$*ARGFILES> I<inside>\nL<C«sub MAIN»|/language/functions#sub_MAIN> is always set to C<$*IN>, even\nwhen C<@*ARGS> is not empty. That means that\n\n=for code\nsub MAIN () {\n    .say for $*ARGFILES.lines;\n}\n\nwhich can be used as C<cat *.raku | raku argfiles-main.raku>, for instance, is\ntotally equivalent to:\n\n=for code\nsub MAIN () {\n    .say for $*IN.lines;\n}\n\nand, in fact, can't be used to process the arguments in the command line, since,\nin this case, it would result in a usage error.\n\nBear in mind that the object C<$*ARGFILES> is going to contain a handle for\nevery argument in a command line, even if that argument is not a valid file. You\ncan retrieve them via the C<.handles> method.\n\n=for code\nfor $*ARGFILES.handles -> $fh {\n    say $fh;\n}\n\nThat code will fail if any of the arguments is not the valid name of a file. You\nwill have to deal with that case at another level, checking that\nL<C<@*ARGS>|/language/variables#index-entry-%40*ARGS> contains valid file names,\nfor instance.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/CatHandle.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::CatHandle\n\n=SUBTITLE Use multiple IO handles as if they were one\n\n   class IO::CatHandle is IO::Handle { }\n\nThis class has been available in Rakudo since release 2017.06.\n\nThe C<IO::CatHandle> class provides a means to create an L<C<IO::Handle>|/type/IO::Handle> that\nseamlessly gathers input from multiple L<C<IO::Handle>|/type/IO::Handle> and L<C<IO::Pipe>|/type/IO::Pipe> sources.\n\nAll of the L<C<IO::Handle>|/type/IO::Handle>'s methods are implemented, and while attempt to use\nwrite methods will (currently) throw an exception; an C<IO::CatHandle> is\nusable anywhere a read-only L<C<IO::Handle>|/type/IO::Handle> can be used.\n\n=head1 Methods\n\n=head2 method new\n\n=for code :method\nmethod new(*@handles, :&on-switch, :$chomp = True,\n           :$nl-in = [\"\\n\", \"\\r\\n\"], Str :$encoding, Bool :$bin)\n\nCreates a new C<IO::CatHandle> object.\n\nThe C<@handles> positional argument indicates a source of handles for the\nC<IO::CatHandle> to read from and can deal with a mixed collection of\nL<C<Cool>|/type/Cool>, L<C<IO::Path>|/type/IO::Path>, and L<C<IO::Handle>|/type/IO::Handle> (including L<C<IO::Pipe>|/type/IO::Pipe>)\nobjects. As input from C<IO::CatHandle> is processed (so operations won't happen\nduring C<.new> call, but only when C<@handles>' data is needed), it will walk\nthrough the C<@handles> list, processing each argument as follows:\n\n=item the\nL<C<Cool>|/type/Cool> objects will be coerced to L<C<IO::Path>|/type/IO::Path>;\n\n=item L<C<IO::Path>|/type/IO::Path> objects\nwill be opened for reading using the C<IO::CatHandle>'s (invocant's) attributes\nfor L«C<open>|/routine/open» calls;\n\n=item un-opened L<C<IO::Handle>|/type/IO::Handle> objects will be\nopened in the same fashion as L<C<IO::Path>|/type/IO::Path> objects;\n\n=item and already opened\nL<C<IO::Handle>|/type/IO::Handle> objects will have all of their attributes set to the attributes of\nthe invocant C<IO::CatHandle>.\n\nIn short, all the C<@handles> end up as\nL<C<IO::Handle>|/type/IO::Handle> objects opened in the same mode and with the same attributes as\nthe invocant C<IO::CatHandle>.\n\nSee L«C<.on-switch> method|/type/IO::CatHandle#method_on-switch» for details\non the C<:&on-switch> named argument, which by default is not set.\n\nThe L«C<:$encoding>|/type/IO::CatHandle#method_encoding» named argument\nspecifies the handle's encoding and accepts the same values as\nL«C<IO::Handle.encoding>|/type/IO::Handle#method_encoding». Set C<:$bin> named\nargument to C<True> if you wish the handle to be in binary mode. Attempting to\nspecify both a defined C<:$encoding> and a C<True> C<:$bin> is a fatal error\nresulting in C<X::IO::BinaryAndEncoding> exception thrown. If neither\nC<:$encoding> is set nor C<:$bin> set to a true value, the handle will default\nto C<utf8> encoding.\n\nThe C<:$chomp> and C<:$nl-in> arguments have the same meaning as in\nL<C<IO::Handle>|/type/IO::Handle> and take and default to the same values.\n\n=head2 method chomp\n\n    method chomp(IO::CatHandle:D:) is rw\n\nSets the invocant's C<$.chomp> attribute to the assigned value. All source\nhandles, including the active one will use the provided C<$.chomp> value.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: \"A\\nB\\nC\\n\";\n(my $f2 = 'bar'.IO).spurt: \"D\\nE\\n\";\nwith IO::CatHandle.new: $f1, $f2 {\n    # .chomp is True by default:\n    (.get xx 2).raku.say; # OUTPUT: «(\"A\", \"B\").Seq␤»\n\n    .chomp = False;\n    (.get xx 3).raku.say; # OUTPUT: «(\"C\\n\", \"D\\n\", \"E\\n\").Seq␤»\n    .close\n}\n=end code\n\n=head2 method nl-in\n\n    method nl-in(IO::CatHandle:D:) is rw\n\nSets the invocant's C<$.nl-in> attribute to the assigned value, which can be a\nL<C<Str>|/type/Str> or a L<C<List>|/type/List> of L<C<Str>|/type/Str>, where each\nL<C<Str>|/type/Str> object represents the end-of-line string. All source handles,\nincluding the active one will use the provided C<$.nl-in> value. Note that\nsource handle boundary is always counted as a new line break.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: \"A\\nB\\nC\";\n(my $f2 = 'bar'.IO).spurt: \"DxEx\";\nwith IO::CatHandle.new: $f1, $f2 {\n    # .nl-in is [\"\\n\", \"\\r\\n\"] by default:\n    (.get xx 2).raku.say; # OUTPUT: «(\"A\", \"B\").Seq␤»\n\n    .nl-in = 'x';\n    (.get xx 3).raku.say; # OUTPUT: «(\"C\", \"D\", \"E\").Seq␤»\n    .close\n}\n=end code\n\n=head2 method close\n\n    method close(IO::CatHandle:D: --> True)\n\nCloses the currently active source handle, as well as any already-open source\nhandles, and empties the source handle queue. Unlike a regular\nL<C<IO::Handle>|/type/IO::Handle>, an explicit call to C<.close> is often not necessary on an C<IO::CatHandle>, as merely exhausting all the input closes all the handles that\nneed to be closed.\n\n=begin code :skip-test<compile time error>\nwith IO::CatHandle.new: @bunch-of-handles {\n    say .readchars: 42;\n    .close; # we are done; close all the open handles\n}\n=end code\n\n=head2 method comb\n\n    method comb(IO::CatHandle:D: |args --> Seq:D)\n\nRead the handle and processes its contents the same way\nL«C<Str.comb>|/type/Str#routine_comb» does, taking the same arguments.\nB<Implementations may slurp the contents of all the source handles> in their\nentirety when this method is called.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: 'foo';\n(my $f2 = 'bar'.IO).spurt: 'bar';\nIO::CatHandle.new($f1, $f2).comb(2).raku.say;\n# OUTPUT: «(\"fo\", \"ob\", \"ar\").Seq␤»\n=end code\n\n=head2 method DESTROY\n\n    method DESTROY(IO::CatHandle:D:)\n\nCalls L«C<.close>|/type/IO::CatHandle#method_close».\nThis method isn't to be used directly, but is something that's called during\ngarbage collection.\n\n=head2 method encoding\n\n    multi method encoding(IO::CatHandle:D:)\n    multi method encoding(IO::CatHandle:D: $new-encoding)\n\nSets the invocant's C<$.encoding> attribute to the provided value. Valid values\nare the same as those accepted by\nL«C<IO::Handle.encoding>|/type/IO::Handle#method_encoding» (use value\nL<C<Nil>|/type/Nil> to switch to binary mode). All source handles, including the active one\nwill use the provided C<$.encoding> value.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: 'I ♥ Raku';\n(my $f2 = 'bar'.IO).spurt: 'meow';\nwith IO::CatHandle.new: $f1, $f2 {\n    # .encoding is 'utf8' by default:\n    .readchars(5).say; # OUTPUT: «I ♥ R␤»\n\n    .encoding: Nil; # switch to binary mode\n    .slurp.say; # OUTPUT: «Buf[uint8]:0x<6B 75 6D 65 6F 77>␤»\n}\n=end code\n\n=head2 method eof\n\n    method eof(IO::CatHandle:D: --> Bool:D)\n\nReturns C<True> if the read operations have exhausted the source handle\nqueue, including the contents of the last handle. B<Note:> calling this\nmethod may cause one or more\nL«C<.on-switch>|/type/IO::CatHandle#method_on-switch» calls, while\nthe source handle queue is examined, and the L<source handle queue may get\nexhausted|/type/IO::CatHandle#method_next-handle>.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: 'foo';\n(my $f2 = 'bar'.IO).spurt: 'bar';\nwith IO::CatHandle.new: :on-switch{ print 'SWITCH! ' }, $f1, $f2 {\n                   # OUTPUT: «SWITCH! »\n    .eof.say;      # OUTPUT: «False␤»\n    .readchars(3);\n    .eof.say;      # OUTPUT: «SWITCH! False␤»\n\n    .slurp;        # OUTPUT: «SWITCH! »\n    .eof.say;      # OUTPUT: «True␤»\n}\n=end code\n\nThe same caveats for non-seekable handles and empty files that apply to\nL<IO::Handle.eof|/type/IO::Handle#method_eof> apply here.\n\n=head2 method get\n\n    method get(IO::CatHandle:D: --> Bool:D)\n\nReturns a single line of input from the handle, with the new line string\ndefined by the value(s) of\nL«C<$.nl-in> attribute|/type/IO::CatHandle#method_nl-in», which will be removed\nfrom the line if L«C<$.chomp> attribute|/type/IO::CatHandle#method_chomp»\nis set to C<True>. Returns L<C<Nil>|/type/Nil> when there is no more input.\nIt is an error to call this method when the handle is\nL<in binary mode|/type/IO::CatHandle#method_encoding>, resulting in\nL<C<X::IO::BinaryMode>|/type/X::IO::BinaryMode> exception being thrown.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: \"a\\nb\\nc\";\n(my $f2 = 'bar'.IO).spurt: \"d\\ne\";\nmy $cat = IO::CatHandle.new: $f1, $f2;\n.say while $_ = $cat.get; # OUTPUT: «a␤b␤c␤d␤e␤»\n=end code\n\n=head2 method getc\n\n    method getc(IO::CatHandle:D: --> Bool:D)\n\nReturns a single character of input from the handle. All\nthe caveats described in L«C<IO::Handle.getc>|/type/IO::Handle#routine_getc»\napply. Returns L<C<Nil>|/type/Nil> when there is no more input.\nIt is an error to call this method when the handle is\nL<in binary mode|/type/IO::CatHandle#method_encoding>, resulting in\nL<C<X::IO::BinaryMode>|/type/X::IO::BinaryMode> exception being thrown.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: 'I ♥ Raku';\n(my $f2 = 'bar'.IO).spurt: 'meow';\nmy $cat = IO::CatHandle.new: $f1, $f2;\n.say while $_ = $cat.getc; # OUTPUT: «I␤ ␤♥␤ ␤R␤a␤k␤u␤m␤e␤o␤w␤»\n=end code\n\n=head2 method handles\n\nDefines as:\n\n    method handles(IO::CatHandle:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> containing the currently-active handle, as well as all the\nremaining source handles produced by calling L<next-handle|/routine/next-handle>. If the invocant\nhas already been fully-consumed, returns an empty L<C<Seq>|/type/Seq>.\n\nThis method is especially handy when working with L<C<IO::ArgFiles>|/type/IO::ArgFiles>, where you\nwant to treat each filehandle separately:\n\n    # print at most the first 2 lines of each file in $*ARGFILES:\n    .say for flat $*ARGFILES.handles.map: *.lines: 2\n\nIt I<is> acceptable to call this method multiple times; C<.handles.head> is a\nvalid idiom for obtaining the currently-active handle. If, between\nL<reification|/language/glossary#Reify> of the elements of the\nreturned L<C<Seq>|/type/Seq> the handles get switched by some other means, the next\nelement produced by the L<C<Seq>|/type/Seq> would be the next handle of the\ninvocant, not the handle that would've been produced if no switching occurred:\n\n    (my $file1 := 'file1'.IO).spurt: \"1a\\n1b\\n1c\";\n    (my $file2 := 'file2'.IO).spurt: \"2a\\n2b\\n2c\";\n    (my $file3 := 'file3'.IO).spurt: \"3a\\n3b\\n3c\";\n    my $cat := IO::CatHandle.new: $file1, $file2, $file3;\n    for $cat.handles {\n        say .lines: 2;\n        $cat.next-handle;\n    }\n    # OUTPUT: «(1a 1b)␤(3a 3b)␤»\n\nLikewise, reifying the returned L<C<Seq>|/type/Seq> consumes the invocant's source\nhandles and once it is fully reified the invocant becomes fully-consumed.\n\n=head2 method IO\n\n    method IO(IO::CatHandle:D:)\n\nAlias for L«C<.path>|/type/IO::CatHandle#method_path»\n\n=head2 method lines\n\n    method lines(IO::CatHandle:D: $limit = Inf, :$close --> Seq:D)\n\nSame as L«C<IO::Handle.lines>|/type/IO::Handle#routine_lines». Note that\na boundary between source handles is considered to be a newline break.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: \"foo\\nbar\";\n(my $f2 = 'bar'.IO).spurt: 'meow';\nIO::CatHandle.new($f1, $f2).lines.raku.say;\n# OUTPUT: «(\"foo\", \"bar\", \"meow\").Seq␤»\n=end code\n\nNote: if C<:$close> is C<False>, fully-consumed handles are B<still> going\nto be closed.\n\n=head2 method lock\n\n    method lock(IO::CatHandle:D: Bool:D :$non-blocking = False, Bool:D :$shared = False --> True)\n\nSame as L«C<IO::Handle.lock>|/type/IO::Handle#method_lock». Returns\nL<C<Nil>|/type/Nil>\nif the\nL<source handle queue has been exhausted|/type/IO::CatHandle#method_next-handle>.\n\nLocks only the currently active source handle. The\nL«C<.on-switch>|/type/IO::CatHandle#method_on-switch» L<C<Callable>|/type/Callable> can be\nused to conveniently lock/unlock the handles as they're being processed\nby the CatHandle.\n\n=head2 method native-descriptor\n\n    method native-descriptor(IO::CatHandle:D: --> Int:D)\n\nReturns the L«native-descriptor|/type/IO::Handle#method_native-descriptor»\nof the currently active source handle or L<C<Nil>|/type/Nil> if the L<source handle queue has\nbeen exhausted|/type/IO::CatHandle#method_next-handle>.\n\nSince the C<CatHandle> closes a source handle, once it's done with it, it's\npossible for successive source handles to have the same native descriptor, if\nthey were passed to L<.new|/type/IO::CatHandle#method_new> as L<C<Cool>|/type/Cool>\nor L<C<IO::Path>|/type/IO::Path> objects.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: 'foo';\n(my $f2 = 'bar'.IO).spurt: 'bar';\nwith IO::CatHandle.new: $f1, $f2, $*IN {\n    repeat { .native-descriptor.say } while .next-handle;\n    # OUTPUT: «13␤13␤9␤»\n}\n=end code\n\n=head2 method next-handle\n\n    method next-handle(IO::CatHandle:D: --> IO::Handle:D)\n\nSwitches the active source handle to the next handle in the source handle\nqueue, which is the sources given in C<@handles> attribute to\nL«C<.new>|/type/IO::CatHandle#method_new». The return value is the currently\nactive source handle or L<C<Nil>|/type/Nil> if the source handle queue has been exhausted.\n\nCoerces L<C<Cool>|/type/Cool> source \"handles\" to L<C<IO::Path>|/type/IO::Path>; opens L<C<IO::Path>|/type/IO::Path> and unopened\nL<C<IO::Handle>|/type/IO::Handle> source handles for reading using the invocant's\nL«C<$.nl-in>|/type/IO::CatHandle#method_nl-in»,\nL«C<$.chomp>|/type/IO::CatHandle#method_chomp», and\nL«C<$.encoding>|/type/IO::CatHandle#method_encoding» attributes;\nthose same attributes of already-opened L<C<IO::Handle>|/type/IO::Handle> objects will be changed to\nthe values of the invocant's attributes.\n\nThis method is called automatically whenever CatHandle's methods require\na switch to the next source handle, triggers\nL«C<.on-switch>|/type/IO::CatHandle#method_on-switch» L<C<Callable>|/type/Callable> to be called,\nand is called once during L<.new|/type/IO::CatHandle#method_new> call. The\nC<.on-switch> will continue to be triggered each time this method is called,\neven after the source handle queue has been exhausted. Note\nthat generally reaching the EOF of the currently active source handle does not\ntrigger the C<.next-handle> call, but rather further read operations that\nneed more data do.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: \"a\\nb\";\n(my $f2 = 'bar'.IO).spurt: \"c\\nd\";\nwith IO::CatHandle.new: :on-switch{ say '▸ Switching' }, $f1, $f2 {\n    say 'one';\n    .next-handle.^name.say;\n    say 'two';\n    .next-handle.^name.say;\n    say 'three';\n    .next-handle.^name.say;\n    # OUTPUT:\n    # ▸ Switching\n    # one\n    # ▸ Switching\n    # IO::Handle\n    # two\n    # ▸ Switching\n    # Nil\n    # three\n    # ▸ Switching\n    # Nil\n}\n=end code\n\n=head2 method on-switch\n\n    has &.on-switch is rw\n\nOne of the attributes that can be set during\nL«C<.new>|/type/IO::CatHandle#method_new» call and changed later by assigning\nto. By default is not specified. Takes a L<C<Callable>|/type/Callable> with\nL«C<.count>|/type/Code#method_count» of C<0>, C<1>, C<2>, or C<Inf>. Gets called\nevery time L«C<.next-handle>|/type/IO::CatHandle#method_next-handle» is, which\nhappens once during L«C<.new>|/type/IO::CatHandle#method_new» call and then each\ntime a source handle is switched to the next one in the queue, or when the\nL«C<.next-handle>|/type/IO::CatHandle#method_next-handle» method is called\nmanually.\n\nIf the L«C<.count>|/type/Code#method_count» of C<&.on-switch> is C<0>, it\nreceives no arguments; if it's C<1>, it receives the currently active handle,\nand if it's C<2> or C<Inf>, it receives the currently active handle, and the\nlast active handle as positional arguments (in that order). On the very\nfirst C<&.on-switch> execution, the \"last active handle\" argument is\nL<C<Nil>|/type/Nil>. Upon source handle queue exhaustion the \"currently active handle\"\nargument is L<C<Nil>|/type/Nil>, and all the executions made afterwards have both arguments\nas L<C<Nil>|/type/Nil>.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: \"A\\nB\\nC\";\n(my $f2 = 'bar'.IO).spurt: \"D\\nE\";\n\nmy $line;\nmy $cat = IO::CatHandle.new: :on-switch{ $line = 1 }, $f1, $f2;\nsay \"{$cat.path}:{$line++} $_\" for $cat.lines;\n# OUTPUT:\n# foo:1 A\n# foo:2 B\n# foo:3 C\n# bar:1 D\n# bar:2 E\n=end code\n\n=begin code\nmy @old-stuff;\nsub on-switch ($new, $old) {\n    $new and $new.seek: 1, SeekFromBeginning;\n    $old and @old-stuff.push: $old.open.slurp: :close;\n}\n\n(my $f1 = 'foo'.IO).spurt: \"A\\nB\\nC\";\n(my $f2 = 'bar'.IO).spurt: \"D\\nE\";\nmy $cat = IO::CatHandle.new: :&on-switch, $f1, $f2;\n$cat.lines.raku.say; # OUTPUT: «(\"\", \"B\", \"C\", \"\", \"E\").Seq␤»\n@old-stuff.raku.say; # OUTPUT: «[\"A\\nB\\nC\", \"D\\nE\"]␤»\n=end code\n\n=head2 method open\n\n    method open(IO::CatHandle:D: --> IO::CatHandle:D)\n\nReturns the invocant. The intent of this method is to merely make CatHandle\nworkable with things that open L<C<IO::Handle>|/type/IO::Handle>. You never have to call this method\nintentionally.\n\n=head2 method opened\n\n    method opened(IO::CatHandle:D: --> Bool:D)\n\nReturns C<True> if the invocant has any source handles, C<False> otherwise.\n\n=begin code\nsay IO::CatHandle.new      .opened; # OUTPUT: «False␤»\nsay IO::CatHandle.new($*IN).opened; # OUTPUT: «True␤»\n\n(my $f1 = 'foo'.IO).spurt: \"A\\nB\\nC\";\nwith IO::CatHandle.new: $f1 {\n    .opened.say; # OUTPUT: «True␤»\n    .slurp;\n    .opened.say; # OUTPUT: «False␤»\n}\n=end code\n\n=head2 method path\n\n    method path(IO::CatHandle:D:)\n\nReturns the value of L«C<.path> attribute|/type/IO::Handle#method_path»\nof the currently active source handle, or L<C<Nil>|/type/Nil> if the L<source handle queue\nhas been exhausted|/type/IO::CatHandle#method_next-handle>. Basically, if your\nCatHandle is based on files, this is the way to get the path of the file the\nCatHandle is currently reading from.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: \"A\\nB\\nC\";\n(my $f2 = 'bar'.IO).spurt: \"D\\nE\";\n\nmy $line;\nmy $cat = IO::CatHandle.new: :on-switch{ $line = 1 }, $f1, $f2;\nsay \"{$cat.path}:{$line++} $_\" for $cat.lines;\n# OUTPUT:\n# foo:1 A\n# foo:2 B\n# foo:3 C\n# bar:1 D\n# bar:2 E\n=end code\n\n=head2 method read\n\n    method read(IO::CatHandle:D: Int(Cool:D) $bytes = 65536 --> Buf:D)\n\nReads up to C<$bytes> bytes from the handle and returns them in a L<C<Buf>|/type/Buf>.\nC<$bytes> defaults to an implementation-specific value (in Rakudo, the value of\nC<$*DEFAULT-READ-ELEMS>, which by default is set to C<65536>).\nIt is permitted to call this method on handles that are not in binary mode.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: 'meow';\n(my $f2 = 'bar'.IO).spurt: Blob.new: 4, 5, 6;\nwith IO::CatHandle.new: :bin, $f1, $f2 {\n    say .read: 2;    # OUTPUT: «Buf[uint8]:0x<6d 65>␤»\n    say .read: 2000; # OUTPUT: «Buf[uint8]:0x<6f 77 04 05 06>␤»\n}\n\n# Non-binary mode is OK too:\nwith IO::CatHandle.new: $f1, $f2 {\n    say .get;        # OUTPUT: «meow␤»\n    say .read: 2000; # OUTPUT: «Buf[uint8]:0x<04 05 06>␤»\n}\n=end code\n\n=head2 method readchars\n\n    method readchars(IO::CatHandle:D: Int(Cool:D) $chars = 65536 --> Str:D)\n\nReturns a L<C<Str>|/type/Str> of up to C<$chars> characters read from the handle.\nC<$chars> defaults to an implementation-specific value (in Rakudo, the value of\nC<$*DEFAULT-READ-ELEMS>, which by default is set to C<65536>).\nIt is B<NOT> permitted to call this method on handles opened in binary\nmode and doing so will result in L<C<X::IO::BinaryMode>|/type/X::IO::BinaryMode> exception being thrown.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: 'Raku loves to';\n(my $f2 = 'bar'.IO).spurt: ' meow';\n\nwith IO::CatHandle.new: $f1, $f2 {\n    say .readchars: 11;   # OUTPUT: «Raku loves ␤»\n    say .readchars: 1000; # OUTPUT: «to meow␤»\n}\n=end code\n\n=head2 method seek\n\n    method seek(IO::CatHandle:D: |c)\n\nCalls L«C<.seek>|/type/IO::Handle#method_seek» on the currently active source\nhandle, forwarding it all the arguments, and returns the result.\nReturns L<C<Nil>|/type/Nil> if the L<source handle\nqueue has been exhausted|/type/IO::CatHandle#method_next-handle>.\nB<NOTE:> this method does I<NOT> perform any source handle switching, so\nseeking past the end of the current source handle will I<NOT> seek to the next\nsource handle in the queue and seeking past the beginning of the current\nsource handle is a fatal error. Also see\nL«C<.next-handle>|/type/IO::CatHandle#method_next-handle», to learn the\ndetails on when source handles are switched.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: 'foo';\n(my $f2 = 'bar'.IO).spurt: 'bar';\n\nwith IO::CatHandle.new: $f1, $f2 {\n    .get.say;                     # OUTPUT: «foo␤»\n    .seek: -2, SeekFromCurrent;\n    .readchars(2).say;            # OUTPUT: «oo␤»\n    .seek: 1000, SeekFromCurrent; # this doesn't switch to second handle!\n    .readchars(3).say;            # OUTPUT: «bar␤»\n    try .seek: -4;                # this won't seek to previous handle!\n    say ~$!;                      # OUTPUT: «Failed to seek in filehandle: 22␤»\n}\n=end code\n\n=head2 method tell\n\n    method tell(IO::CatHandle:D: --> Int:D)\n\nCalls L«C<.tell>|/type/IO::Handle#method_tell» on the currently active source\nhandle and returns the result. Returns L<C<Nil>|/type/Nil> if the L<source handle\nqueue has been exhausted|/type/IO::CatHandle#method_next-handle>.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: 'foo';\n(my $f2 = 'bar'.IO).spurt: 'bar';\n\nwith IO::CatHandle.new: $f1, $f2 {\n    .get.say;                   # OUTPUT: «foo␤»\n    .tell.say;                  # OUTPUT: «3␤»\n    .seek: -2, SeekFromCurrent;\n    .tell.say;                  # OUTPUT: «1␤»\n    say .readchars: 3;          # OUTPUT: «oob␤»\n    .tell.say;                  # OUTPUT: «2␤»\n    }\n=end code\n\n=head2 method slurp\n\n    method slurp(IO::CatHandle:D:)\n\nReads all of the available input from all the source handles and returns it\nas a L<C<Buf>|/type/Buf> if the handle is in\nL<binary mode|/type/IO::CatHandle#method_encoding> or as a L<C<Str>|/type/Str> otherwise.\nReturns L<C<Nil>|/type/Nil> if the L<source handle\nqueue has been exhausted|/type/IO::CatHandle#method_next-handle>.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: 'foo';\n(my $f2 = 'bar'.IO).spurt: 'bar';\n\nIO::CatHandle.new(      $f1, $f2).slurp.say; # OUTPUT: «foobar␤»\nIO::CatHandle.new(:bin, $f1, $f2).slurp.say; # OUTPUT: «Buf[uint8]:0x<66 6f 6f 62 61 72>␤»\nIO::CatHandle.new                .slurp.say; # OUTPUT: «Nil␤»\n=end code\n\n=head2 method split\n\n    method split(IO::CatHandle:D: |args --> Seq:D)\n\nRead the handle and processes its contents the same way\nL«C<Str.split>|/type/Str#routine_split» does, taking the same arguments.\nB<Implementations may slurp the contents of all the source handles> in their\nentirety when this method is called.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: 'foo';\n(my $f2 = 'bar'.IO).spurt: 'bar';\nIO::CatHandle.new($f1, $f2).split(/o+/).raku.say;\n# OUTPUT: «(\"f\", \"bar\").Seq␤»\n=end code\n\n=head2 method Str\n\n    method Str(IO::CatHandle:D: --> Str:D)\n\nCalls L«C<.Str>|/type/IO::Handle#method_Str» on the currently active source\nhandle and returns the result. If the L<source handle\nqueue has been exhausted|/type/IO::CatHandle#method_next-handle>, returns\nan implementation-defined string (C«'<closed IO::CatHandle>'» in Rakudo).\n\n=head2 method Supply\n\n    method Supply(IO::CatHandle:D: :$size = 65536 --> Supply:D)\n\nReturns a L<C<Supply>|/type/Supply> fed with either\nL«C<.read>|/type/IO::CatHandle#method_read», if the handle is in\nL<binary mode|/type/IO::CatHandle#method_encoding>, or with\nL«C<.readchars>|/type/IO::CatHandle#method_readchars», if it isn't, with\nreads of C<:$size> bytes or characters. C<:$size> defaults to an implementation-specific value (in Rakudo, the value of\nC<$*DEFAULT-READ-ELEMS>, which by default is set to C<65536>).\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: 'foo';\n(my $f2 = 'bar'.IO).spurt: 'bar';\nreact whenever IO::CatHandle.new($f1, $f2).Supply: :2size {.say}\n# OUTPUT: «fo␤ob␤ar␤»\n\nreact whenever IO::CatHandle.new(:bin, $f1, $f2).Supply: :2size {.say}\n# OUTPUT: «Buf[uint8]:0x<66 6f>␤Buf[uint8]:0x<6f 62>␤Buf[uint8]:0x<61 72>␤»\n=end code\n\n=head2 method t\n\n    method t(IO::CatHandle:D: --> Bool:D)\n\nCalls L«C<.t>|/type/IO::Handle#method_t», which tells if the handle is a TTY,\non the currently active source handle and returns the result.\nIf the\nL<source handle queue has been exhausted|/type/IO::CatHandle#method_next-handle>,\nreturns C<False>.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: 'foo';\nwith IO::CatHandle.new: $f1, $*IN {\n    repeat { .t.say } while .next-handle; # OUTPUT: «False␤True␤»\n}\n=end code\n\n=head2 method unlock\n\n    method unlock(IO::CatHandle:D:)\n\nSame as L«C<IO::Handle.unlock>|/type/IO::Handle#method_unlock». Returns\nL<C<Nil>|/type/Nil> if the\nL<source handle queue has been exhausted|/type/IO::CatHandle#method_next-handle>.\n\nUnlocks only the currently active source handle. The\nL«C<.on-switch>|/type/IO::CatHandle#method_on-switch» L<C<Callable>|/type/Callable> can be\nused to conveniently lock/unlock the handles as they're being processed\nby the CatHandle.\n\n=head2 method words\n\n    method words(IO::CatHandle:D: $limit = Inf, :$close --> Seq:D)\n\nSame as L«C<IO::Handle.words>|/type/IO::Handle#routine_words» (including\nthe caveat about more data read than needed to make some number of words).\nNote that a boundary between source handles is considered to be word boundary.\n\n=begin code\n(my $f1 = 'foo'.IO).spurt: 'foo bar';\n(my $f2 = 'bar'.IO).spurt: 'meow';\nIO::CatHandle.new($f1, $f2).words.raku.say;\n# OUTPUT: «(\"foo\", \"bar\", \"meow\").Seq␤»\n=end code\n\nNote: if C<:$close> is C<False>, fully-consumed handles are B<still> going\nto be closed.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Handle.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::Handle\n\n=SUBTITLE Opened file or stream\n\n   class IO::Handle { }\n\n\nInstances of C<IO::Handle> encapsulate a I<handle> to manipulate input/output\nresources. Usually there is no need to create directly an C<IO::Handle>\ninstance, since it will be done by other roles and methods. For instance, an\nL<C<IO::Path>|/type/IO::Path> object provides an L<open|/routine/open> method that\nreturns an C<IO::Handle>:\n\n    my $fh = '/tmp/log.txt'.IO.open;\n    say $fh.^name; # OUTPUT: IO::Handle\n\nThe first line is pretty much equivalent to the following piece of code:\n\n    my $fh = IO::Handle.new( :path( '/tmp/log.txt'.IO.path ) ).open;\n\n\n=head1 Methods\n\n=head2 method open\n\n=for code :method :preamble<has $!chomp; has $nl-in; has $nl-out;>\nmethod open(IO::Handle:D:\n      :$r, :$w, :$x, :$a, :$update,\n      :$rw, :$rx, :$ra,\n      :$mode is copy,\n      :$create is copy,\n      :$append is copy,\n      :$truncate is copy,\n      :$exclusive is copy,\n      :$bin,\n      :$enc is copy,\n      :$chomp = $!chomp,\n      :$nl-in is copy = $!nl-in,\n      Str:D :$nl-out is copy = $!nl-out,\n      :$out-buffer is copy,\n    )\n\nOpens the handle in one of the modes. L<Fails|/routine/fail> with appropriate\nexception if the open fails.\n\nSee description of individual methods for the accepted values and behavior of\nL«C<:$chomp>|/type/IO::Handle#method_chomp»,\nL«C<:$nl-in>|/type/IO::Handle#method_nl-in»,\nL«C<:$nl-out>|/type/IO::Handle#method_nl-out», and\nL«C<:$enc>|/type/IO::Handle#method_encoding». The values for parameters default\nto the invocant's attributes and if any of them are provided, the attributes\nwill be updated to the new values. Specify C<:$bin> set to C<True> instead of\nC<:$enc> to indicate the handle should be opened in binary mode. Specifying\nundefined value as C<:$enc> is equivalent to not specifying C<:$enc> at all.\nSpecifying both a defined encoding as C<:$enc> and C<:$bin> set to true will\ncause C<X::IO::BinaryAndEncoding> exception to be thrown.\n\nThe open mode defaults to non-exclusive, read only (same as specifying\nC<:r>) and can be controlled by a mix of the following arguments:\n\n=begin code :lang<text>\n:r      same as specifying   :mode<ro>  same as specifying nothing\n\n:w      same as specifying   :mode<wo>, :create, :truncate\n:a      same as specifying   :mode<wo>, :create, :append\n:x      same as specifying   :mode<wo>, :create, :exclusive\n\n:update same as specifying   :mode<rw>\n:rw     same as specifying   :mode<rw>, :create\n:ra     same as specifying   :mode<rw>, :create, :append\n:rx     same as specifying   :mode<rw>, :create, :exclusive\n=end code\n\nArgument C<:r> along with C<:w>, C<:a>, C<:x> are exactly the same as the\ncombination of both letters, shown in the three last rows in the table above.\nSupport for combinations of modes I<other> than what is listed above\nis implementation-dependent and should be assumed unsupported. That is,\nspecifying, for example, C<.open(:r :create)> or\nC<.open(:mode<wo> :append :truncate)> might work or might cause the Universe\nto implode, depending on a particular implementation. This applies to reads/writes\nto a handle opened in such unsupported modes as well.\n\nThe mode details are:\n\n=begin code :lang<text>\n:mode<ro>  means \"read only\"\n:mode<wo>  means \"write only\"\n:mode<rw>  means \"read and write\"\n\n:create    means the file will be created, if it does not exist\n:truncate  means the file will be emptied, if it exists\n:exclusive means .open will fail if the file already exists\n:append    means writes will be done at the end of file's current contents\n=end code\n\nAttempts to open a directory, write to a handle opened in read-only mode\nor read from a handle opened in write-only mode,\nor using text-reading methods on a handle opened in binary mode will\nfail or throw.\n\nIn B<6.c> language, it's possible to open path C<'-'>, which will cause\nC<open> to open (if C<closed>) the C<$*IN> handle if opening in read-only\nmode or to open the C<$*OUT> handle if opening in write-only mode. All other\nmodes in this case will result in exception being thrown.\n\nAs of B<6.d> language version, the use of path C<'-'> is deprecated and it will\nbe removed in future language versions entirely.\n\nThe C<:out-buffer> controls output buffering and by default behaves as if\nit were L<C<Nil>|/type/Nil>. See method L<out-buffer|/routine/out-buffer> for details.\n\nB<Note (Rakudo versions before 2017.09): Filehandles are NOT flushed or closed\nwhen they go out of scope>. While they I<will> get closed when garbage\ncollected, garbage collection isn't guaranteed to get run. This means I<you\nshould> use an explicit C<close> on handles opened for writing, to avoid data\nloss, and an explicit C<close> is I<recommended> on handles opened for reading\nas well, so that your program does not open too many files at the same time,\ntriggering exceptions on further C<open> calls.\n\nB<Note (Rakudo versions 2017.09 and after):> Open filehandles are automatically\nclosed on program exit, but it is still highly recommended that you C<close>\nopened handles explicitly.\n\n=head2 method comb\n\n    method comb(IO::Handle:D: Bool :$close, |args --> Seq:D)\n\nRead the handle and processes its contents the same way\nL«C<Str.comb>|/type/Str#routine_comb» does, taking the same arguments, closing\nthe handle when done if C<$close> is set to a true value. Implementations may\nslurp the file in its entirety when this method is called.\n\nAttempting to call this method when the handle is\nL<in binary mode|/type/IO::Handle#method_encoding> will result in\nL<C<X::IO::BinaryMode>|/type/X::IO::BinaryMode> exception being thrown.\n\n=for code\nmy $fh = 'path/to/file'.IO.open;\nsay \"The file has {+$fh.comb: '♥', :close} ♥s in it\";\n\n=head2 method chomp\n\n    has $.chomp is rw = True\n\nOne of the attributes that can be set via C<.new> or L<open|/routine/open>. Defaults to\nC<True>. Takes a L<C<Bool>|/type/Bool> specifying whether the line separators (as defined by\nL«C<.nl-in>|/type/IO::Handle#method_nl-in») should be removed from content when\nusing L«C<.get>|/type/IO::Handle#routine_get» or\nL«C<.lines>|/type/IO::Handle#routine_lines» methods.\n\n=head2 routine get\n\n    method get(IO::Handle:D: --> Str:D)\n    multi  get (IO::Handle $fh = $*ARGFILES --> Str:D)\n\nReads a single line of input from the handle, removing the trailing newline\ncharacters (as set by L«C<.nl-in>|/routine/nl-in») if the handle's C<.chomp>\nattribute is set to C<True>. Returns L<C<Nil>|/type/Nil>, if no more input is available. The\nsubroutine form defaults to\nL«C<$*ARGFILES>|/language/variables#index-entry-%24%2AARGFILES» if no handle is\ngiven.\n\nAttempting to call this method when the handle is\nL<in binary mode|/type/IO::Handle#method_encoding> will result in\nL<C<X::IO::BinaryMode>|/type/X::IO::BinaryMode> exception being thrown.\n\n=begin code\n$*IN.get.say;              # Read one line from the standard input\n\nmy $fh = open 'filename';\n$fh.get.say;               # Read one line from a file\n$fh.close;\n\nsay get;                   # Read one line from $*ARGFILES\n=end code\n\n=head2 routine getc\n\n    method getc(IO::Handle:D: --> Str:D)\n    multi  getc (IO::Handle $fh = $*ARGFILES --> Str:D)\n\nReads a single character from the input stream. Attempting to call this method\nwhen the handle is L<in binary mode|/type/IO::Handle#method_encoding> will\nresult in L<C<X::IO::BinaryMode>|/type/X::IO::BinaryMode> exception being thrown. The subroutine form\ndefaults to L«C<$*ARGFILES>|/language/variables#index-entry-%24%2AARGFILES» if\nno handle is given. Returns L<C<Nil>|/type/Nil>, if no more input is available, otherwise\noperation will block, waiting for at least one character to be available; these\ncaveats apply:\n\n=head3 Buffering terminals\n\nUsing getc to get a single keypress from a terminal will only work properly if\nyou've set the terminal to \"unbuffered\". Otherwise the terminal will wait for\nthe return key to be struck or the buffer to be filled up before the compiler gets\neven a single byte of data.\n\n=head3 Waiting for potential combiners\n\nIf your handle's encoding allows combining characters to be read, raku will\nwait for more data to be available before it provides a character. This means\nthat inputting an \"e\" followed by a combining acute will give you an e with an\nacute rather than giving an \"e\" and letting the next reading function give you\na dangling combiner. However, it also means that when the user inputs just an\n\"e\" and has no intention to also input a combining acute, your program will be\nwaiting for another keypress before the initial \"e\" is returned.\n\n=head2 submethod DESTROY\n\n    submethod DESTROY(IO::Handle:D:)\n\nCloses the filehandle, unless its L<native-descriptor|/routine/native-descriptor> is C<2> or lower. This\nensures the standard filehandles do not get inadvertently closed.\n\nNote that garbage collection is not guaranteed to happen, so you must NOT rely\non C<DESTROY> for closing the handles you I<write to> and instead close them\nyourself. Programs that open a lot of files should close the handles explicitly\nas well, regardless of whether they were open for writing, since too many files\nmight get opened before garbage collection happens and the no longer used\nhandles get closed.\n\n=head2 method gist\n\n    method gist(IO::Handle:D: --> Str:D)\n\nReturns a string containing information which\nL«C<.path>|/type/IO::Handle#method_path», if any, the handle is created for\nand whether it is L«C<.opened>|/type/IO::Handle#method_opened».\n\n=begin code\nsay IO::Handle.new; # IO::Handle<(Any)>(closed)\nsay \"foo\".IO.open;  # IO::Handle<\"foo\".IO>(opened)\n=end code\n\n=head2 method eof\n\n    method eof(IO::Handle:D: --> Bool:D)\n\nNon-blocking. Returns C<True> if the read operations have exhausted the\ncontents of the handle. For L<seekable|/routine/seek> handles, this means\ncurrent position is at or beyond the end of file and L<seeking|/routine/seek>\nan exhausted handle back into the file's contents will result in\nL<eof|/routine/eof> returning C<False> again.\n\nOn L<non-seekable|/routine/seek> handles and handles opened to zero-size\nfiles (including special files in C</proc/>), EOF won't be set\nuntil a read operation fails to read any bytes. For example, in this code,\nthe first C<read> consumes all of the data, but it's only until the second\nC<read> that reads nothing would the EOF on a TTY handle be set:\n\n    =begin code :lang<shell>\n    $ echo \"x\" | raku -e 'with $*IN { .read: 10000; .eof.say; .read: 10; .eof.say }'\n    False\n    True\n    =end code\n\n=head2 method encoding\n\n    multi method encoding(IO::Handle:D: --> Str:D)\n    multi method encoding(IO::Handle:D: $enc --> Str:D)\n\nReturns a L<C<Str>|/type/Str> representing the encoding currently used by\nthe handle, defaulting to C<\"utf8\">. L<C<Nil>|/type/Nil> indicates the filehandle is\ncurrently in binary mode. Specifying an optional positional C<$enc> argument\nswitches the encoding used by the handle; specify L<C<Nil>|/type/Nil> as encoding to put the\nhandle into binary mode.\n\nThe accepted values for encoding are case-insensitive. The available encodings\nvary by implementation and backend. On Rakudo MoarVM the following are\nsupported:\n\nX<|Reference,windows-1252>X<|Reference,windows-1251>X<|Reference,windows-932>X<|Reference,iso-8859-1>X<|Reference,ascii>\n\n=for code :lang<text>\nutf8\nutf16\nutf16le\nutf16be\nutf8-c8\niso-8859-1\nwindows-1251\nwindows-1252\nwindows-932\nascii\n\nThe default encoding is utf8, which undergoes normalization into Unicode L<C<NFC>|/type/NFC>\n(normalization form canonical). In some cases you may want to ensure no\nnormalization is done; for this you can use C<utf8-c8>. Before using C<utf8-c8>\nplease read L<Unicode: Filehandles and I/O|/language/unicode#Filehandles_and_I/O>\nfor more information on C<utf8-c8> and L<C<NFC>|/type/NFC>.\n\nAs of Rakudo 2018.04 L<windows-932|https://en.wikipedia.org/wiki/Code_page_932_(Microsoft_Windows)>\nis also supported which is a variant of X<ShiftJIS|Reference,ShiftJIS>.\n\nImplementation may choose to also provide support for aliases, e.g. Rakudo\nallows aliases C<latin-1> for C<iso-8859-1> encoding and dashed utf versions:\nC<utf-8> and C<utf-16>.\n\n=head3 utf16, utf16le and utf16be\n\nX<|Reference,utf16-le>X<|Reference,utf16-be>X<|Reference,utf16>X<|Reference,utf-16>\n\nUnlike utf8, utf16 has an\nendianness — either big endian or little endian. This relates to the ordering of\nbytes. Computer CPUs also have an endianness. Raku's C<utf16> format specifier\nwill use the endianness of host system when encoding. When decoding it will look\nfor a byte order mark and if it is there use that to set the endianness. If there\nis no byte order mark it will assume the file uses the same endianness as the host\nsystem. A byte order mark is the codepoint U+FEFF which is ZERO WIDTH NO-BREAK\nSPACE. On C<utf16> encoded files the standard states if it exists at the start\nof a file it shall be interpreted as a byte order mark, not a U+FEFF codepoint.\n\nWhile writing will cause a different file to be written on different endian\nsystems, at the release of 2018.10 the byte order mark will be written out when\nwriting a file and files created with the utf16 encoding will be able to be\nread on either big or little endian systems.\n\nWhen using utf16be or utf16le encodings a byte order mark is B<not> used. The\nendianness used is not affected by the host cpu type and is either big endian for\nutf16be or little endian for utf16le.\n\nIn keeping with the standard, a 0xFEFF byte at the start of a file is interpreted\nas a ZERO WIDTH NO-BREAK SPACE and not as a byte order mark. No byte order mark\nis written to files that use the utf16be or utf16le encodings.\n\nAs of Rakudo 2018.09 on MoarVM, utf16,\nX<utf16le|Reference,utf16le> and X<utf16be|Reference,utf16be> are supported. In 2018.10, writing to a file with utf16 will\nproperly add a byte order mark (BOM).\n\n=head3 Examples\n\n=begin code\nwith 'foo'.IO {\n    .spurt: \"First line is text, then:\\nBinary\";\n    my $fh will leave {.close} = .open;\n    $fh.get.say;         # OUTPUT: «First line is text, then:␤»\n    $fh.encoding: Nil;\n    $fh.slurp.say;       # OUTPUT: «Buf[uint8]:0x<42 69 6e 61 72 79>␤»\n}\n=end code\n\n=head2 routine lines\n\n    sub          lines( $what = $*ARGFILES, |c)\n    multi method lines( IO::Handle:D: $limit, :$close )\n    multi method lines( IO::Handle:D:         :$close )\n\nThe sub form, which takes C<$*ARGFILES> by default, will apply the C<lines>\nmethod to the object that's the first argument, and pass it the rest of the\narguments.\n\nThe method will return a L<C<Seq>|/type/Seq> each element of which is a line from\nthe handle (that is\nchunks delineated by L«C<.nl-in>|/type/IO::Handle#method_nl-in»). If the\nhandle's L«C<.chomp>|/type/IO::Handle#method_chomp» attribute is set to C<True>,\nthen characters specified by L«C<.nl-in>|/type/IO::Handle#method_nl-in» will be\nstripped from each line.\n\nReads up to C<$limit> lines, where C<$limit> can be a non-negative L<C<Int>|/type/Int>,\nC<Inf>, or L<C<Whatever>|/type/Whatever> (which is interpreted to mean C<Inf>). If C<:$close> is\nset to C<True>, will close the handle when the file ends or C<$limit> is\nreached. Subroutine form defaults to\nL«C<$*ARGFILES>|/language/variables#index-entry-%24%2AARGFILES», if no\nhandle is provided.\n\nAttempting to call this method when the handle is\nL<in binary mode|/type/IO::Handle#method_encoding> will result in\nL<C<X::IO::BinaryMode>|/type/X::IO::BinaryMode> exception being thrown.\n\nB<NOTE:> the lines are read lazily, so ensure the returned L<C<Seq>|/type/Seq> is either\nL<fully reified|/language/glossary#Reify> or is no longer needed\nwhen you close the handle or attempt to use any other method that changes the\nfile position.\n\n=begin code\nsay \"The file contains \",\n  '50GB-file'.IO.open.lines.grep(*.contains: 'Raku').elems,\n  \" lines that mention Raku\";\n# OUTPUT: «The file contains 72 lines that mention Raku␤»\n=end code\n\nYou can use C<lines> in C</proc/*> files (from the 6.d version):\n\n=for code\nsay lines( \"/proc/$*PID/statm\".IO ); # OUTPUT: «(58455 31863 8304 2 0 29705 0)␤»\n\nX<|Reference,File locking>\n=head2 method lock\n\n=for code :method\nmethod lock(IO::Handle:D:\n            Bool:D :$non-blocking = False, Bool:D :$shared = False\n            --> True)\n\nPlaces an advisory lock on the file the filehandle if open for. If\nC<:$non-blocking> is C<True> will L«C<fail>|/routine/fail» with L<C<X::IO::Lock>|/type/X::IO::Lock>\nif lock could not be obtained, otherwise will block until the lock can be\nplaced. If C<:$shared> is C<True> will place a shared (read) lock, otherwise\nwill place an exclusive (write) lock. On success, returns C<True>;\nL«fails|/routine/fail» with L<C<X::IO::Lock>|/type/X::IO::Lock> if lock cannot be placed (e.g. when\ntrying to place a shared lock on a filehandle opened in write mode or trying to\nplace an exclusive lock on a filehandle opened in read mode).\n\nYou can use C<.lock> again to replace an existing lock with another one.\nTo remove a lock, L«C<close>|/routine/close» the filehandle or use\nL«C<unlock>|/routine/unlock».\n\n=begin code\n# One program writes, the other reads, and thanks to locks either\n# will wait for the other to finish before proceeding to read/write\n\n# Writer\ngiven \"foo\".IO.open(:w) {\n    .lock;\n    .spurt: \"I ♥ Raku!\";\n    .close; # closing the handle unlocks it; we could also use `unlock` for that\n}\n\n# Reader\ngiven \"foo\".IO.open {\n    .lock: :shared;\n    .slurp.say; # OUTPUT: «I ♥ Raku!␤»\n    .close;\n}\n=end code\n\n=head2 method unlock\n\n    method unlock(IO::Handle:D: --> True)\n\nRemoves a L«C<lock>|/routine/lock» from the filehandle. It will return\nC<True> or fail with an exception if it's not possible.\n\n=head2 routine words\n\n    multi        words(IO::Handle:D $fh = $*ARGFILES, $limit = Inf, :$close --> Seq:D)\n    multi method words(IO::Handle:D: $limit = Inf, :$close --> Seq:D)\n\nSimilar to L«C<Str.words>|/type/Str#routine_words», separates the handle's\nstream on contiguous chunks of whitespace (as defined\nby Unicode) and returns a L<C<Seq>|/type/Seq> of the resultant \"words.\" Takes an optional\nC<$limit> argument that can be a non-negative L<C<Int>|/type/Int>, C<Inf>, or L<C<Whatever>|/type/Whatever>\n(which is interpreted to mean C<Inf>), to indicate only up-to C<$limit> words\nmust be returned. If L<C<Bool>|/type/Bool> C<:$close> named argument is set to C<True>,\nwill automatically close the handle when the returned L<C<Seq>|/type/Seq> is exhausted.\nSubroutine form defaults to\nL«C<$*ARGFILES>|/language/variables#index-entry-%24%2AARGFILES», if no handle\nis provided.\n\nAttempting to call this method when the handle is\nL<in binary mode|/type/IO::Handle#method_encoding> will result in\nL<C<X::IO::BinaryMode>|/type/X::IO::BinaryMode> exception being thrown.\n\n=for code\nmy %dict := bag $*IN.words;\nsay \"Most common words: \", %dict.sort(-*.value).head: 5;\n\nB<NOTE:> implementations may read I<more> data than necessary when a call\nto C<.words> is made. That is, C<$handle.words(2)> may read more data than two\n\"words\" worth of data and subsequent calls to read methods might not read from\nthe place right after the two fetched words. After a call to C<.words>, the\nfile position should be treated as undefined.\n\n=head2 method split\n\n    method split(IO::Handle:D: :$close, |c)\n\nL<Slurps|/routine/slurp> the handle's content and calls\nL«C<Str.split>|/type/Str#routine_split» on it, forwarding any of the given\narguments. If C<:$close> named parameter is set to C<True>, will\nL<close|/routine/close> the invocant after slurping.\n\nAttempting to call this method when the handle is L<in binary\nmode|/type/IO::Handle#method_encoding> will result in L<C<X::IO::BinaryMode>|/type/X::IO::BinaryMode>\nexception being thrown.\n\n=for code\nmy $fh = 'path/to/file'.IO.open;\n$fh.split: '♥', :close; # Returns file content split on ♥\n\n=head2 method spurt\n\n    multi method spurt(IO::Handle:D: Blob $data, :$close = False)\n    multi method spurt(IO::Handle:D: Cool $data, :$close = False)\n\nWrites all of the C<$data> into the filehandle, closing it when finished,\nif C<$close> is C<True>. For L«C<Cool>|/type/Cool» C<$data>, will use the\nencoding the handle is set to use (L«C<IO::Handle.open>|/routine/open»\nor L«C<IO::Handle.encoding>|/routine/encoding»).\n\nBehavior for spurting a L«C<Cool>|/type/Cool» when the handle is in binary\nmode or spurting a L«C<Blob>|/type/Blob» when the handle is NOT in binary\nmode is undefined.\n\n=head2 method print\n\n    multi method print(**@text --> True)\n    multi method print(Junction:D --> True)\n\nWrites the given C<@text> to the handle, coercing any non-L<C<Str>|/type/Str>\nobjects to L<C<Str>|/type/Str> by calling L«C<.Str>|/routine/Str» method on them.\nL<C<Junction>|/type/Junction> arguments\nL<autothread|/language/glossary#Autothreading> and the order of\nprinted strings is not guaranteed. See L<write|/routine/write> to write bytes.\n\nAttempting to call this method when the handle is\nL<in binary mode|/type/IO::Handle#method_encoding> will result in\nL<C<X::IO::BinaryMode>|/type/X::IO::BinaryMode> exception being thrown.\n\n=for code\nmy $fh = 'path/to/file'.IO.open: :w;\n$fh.print: 'some text';\n$fh.close;\n\n=head2 method print-nl\n\n    method print-nl(IO::Handle:D: --> True)\n\nWrites the value of C<$.nl-out> attribute into the handle. This attribute, by\ndefault, is C<␤>, but see the L<page on newline|/language/newline> for the rules\nit follows in different platforms and environments.\n\nAttempting to call this method when the handle is\nL<in binary mode|/type/IO::Handle#method_encoding> will result in\nL<C<X::IO::BinaryMode>|/type/X::IO::BinaryMode> exception being thrown.\n\n=for code\nmy $fh = 'path/to/file'.IO.open: :w, :nl-out(\"\\r\\n\");\n$fh.print: \"some text\";\n$fh.print-nl; # prints \\r\\n\n$fh.close;\n\n=head2 method printf\n\n    multi method printf(IO::Handle:D: Cool $format, *@args)\n\nFormats a string based on the given format and arguments and C<.print>s the\nresult into the filehandle. See\nL<sprintf|/routine/sprintf> for details on\nacceptable format directives.\n\nAttempting to call this method when the handle is\nL<in binary mode|/type/IO::Handle#method_encoding> will result in\nL<C<X::IO::BinaryMode>|/type/X::IO::BinaryMode> exception being thrown.\n\n=for code\nmy $fh = open 'path/to/file', :w;\n$fh.printf: \"The value is %d\\n\", 32;\n$fh.close;\n\n=head2 method out-buffer\n\n    method out-buffer(--> Int:D) is rw\n\nControls output buffering and can be set via an argument to L<open|/routine/open>. Takes\nan C<int> as the size of the buffer to use (zero is acceptable). Can take\na L<C<Bool>|/type/Bool>: C<True> means to use default, implementation-defined buffer size;\nC<False> means to disable buffering (equivalent to using C<0> as buffer size).\n\nLastly, can take a L<C<Nil>|/type/Nil> to enable TTY-based buffering control: if\nthe handle L<is a TTY|/routine/t>, the buffering is disabled, otherwise,\ndefault, implementation-defined buffer size is used.\n\nSee L<flush|/routine/flush> to write out data currently in the buffer. Changing buffer\nsize flushes the filehandle.\n\n=for code\ngiven 'foo'.IO.open: :w, :1000out-buffer {\n    .say: 'Hello world!'; # buffered\n    .out-buffer = 42;       # buffer resized; previous print flushed\n    .say: 'And goodbye';\n    .close; # closing the handle flushes the buffer\n}\n\n\n=head2 method put\n\n    multi method put(**@text --> True)\n    multi method put(Junction:D --> True)\n\nWrites the given C<@text> to the handle, coercing any non-L<C<Str>|/type/Str> objects to\nL<C<Str>|/type/Str> by calling L«C<.Str>|/routine/Str» method on them, and appending the\nvalue of L«C<.nl-out>|/type/IO::Handle#method_nl-out» at the end. L<C<Junction>|/type/Junction>\narguments L<autothread|/language/glossary#Autothreading> and the\norder of printed strings is not guaranteed.\n\nAttempting to call this method when the handle is\nL<in binary mode|/type/IO::Handle#method_encoding> will result in\nL<C<X::IO::BinaryMode>|/type/X::IO::BinaryMode> exception being thrown.\n\n=for code\nmy $fh = 'path/to/file'.IO.open: :w;\n$fh.put: 'some text';\n$fh.close;\n\n=head2 method say\n\n    multi method say(IO::Handle:D: **@text --> True)\n\nThis method is identical to L<put|/type/IO::Handle#method_put> except\nthat it stringifies its arguments by calling L«C<.gist>|/routine/gist» instead\nof L«C<.Str>|/routine/Str».\n\nAttempting to call this method when the handle is\nL<in binary mode|/type/IO::Handle#method_encoding> will result in\nL<C<X::IO::BinaryMode>|/type/X::IO::BinaryMode> exception being thrown.\n\n=for code\nmy $fh = open 'path/to/file', :w;\n$fh.say(Complex.new(3, 4));        # OUTPUT: «3+4i␤»\n$fh.close;\n\n=head2 method read\n\n    method read(IO::Handle:D: Int(Cool:D) $bytes = 65536 --> Buf:D)\n\nBinary reading; reads and returns up to C<$bytes> bytes from the filehandle.\nC<$bytes> defaults to an implementation-specific value (in Rakudo,\nthe value of C<$*DEFAULT-READ-ELEMS>, which by default is set to C<65536>).\nThis method can be called even when the handle is not\nL<in binary mode|/type/IO::Handle#method_encoding>.\n\n=begin code\n(my $file = 'foo'.IO).spurt: 'I ♥ Raku';\ngiven $file.open {\n    say .read: 6; # OUTPUT: «Buf[uint8]:0x<49 20 e2 99 a5 20>␤»\n    .close;\n}\n=end code\n\n=head2 method readchars\n\n    method readchars(IO::Handle:D: Int(Cool:D) $chars = 65536 --> Str:D)\n\nReading chars; reads and returns up to C<$chars> chars (graphemes) from the\nfilehandle. C<$chars> defaults to an implementation-specific value (in Rakudo,\nthe value of C<$*DEFAULT-READ-ELEMS>, which by default is set to C<65536>).\nAttempting to call this method when the handle is\nL<in binary mode|/type/IO::Handle#method_encoding> will result in\nL<C<X::IO::BinaryMode>|/type/X::IO::BinaryMode> exception being thrown.\n\n=begin code\n(my $file = 'foo'.IO).spurt: 'I ♥ Raku';\ngiven $file.open {\n    say .readchars: 5; # OUTPUT: «I ♥ R␤»\n    .close;\n}\n=end code\n\nB<Note>: Calling C<.tell> after using C<.readchars>\nL<might be off by up to 3 bytes|https://github.com/rakudo/rakudo/issues/3646>\nas a result of L<unicode processing|https://www.nntp.perl.org/group/perl.perl6.users/2020/04/msg8385.html>.\n\n=head2 method write\n\n    method write(IO::Handle:D: Blob:D $buf --> True)\n\nWrites C<$buf> to the filehandle. This method can be called even when the\nhandle is not L<in binary mode|/type/IO::Handle#method_encoding>.\n\nX<|Reference,SeekFromBeginning>\nX<|Reference,SeekFromCurrent>\nX<|Reference,SeekFromEnd>\n=head2 method seek\n\n     method seek(IO::Handle:D: Int:D $offset, SeekType:D $whence --> True)\n\nMove the file pointer (that is, the position at which any subsequent read\nor write operations will begin) to the byte position specified by\nC<$offset> relative to the location specified by C<$whence> which may be\none of:\n\n=item C<SeekFromBeginning>: The beginning of the file.\n\n=item C<SeekFromCurrent>: The current position in the file.\n\n=item C<SeekFromEnd>: The end of the file.  Please note that you need to specify\na negative offset if you want to position before the end of the file.\n\n=head2 method tell\n\n    method tell(IO::Handle:D: --> Int:D)\n\nReturn the current position of the file pointer in bytes.\n\n=head2 method slurp-rest\n\n    multi method slurp-rest(IO::Handle:D: :$bin! --> Buf)\n    multi method slurp-rest(IO::Handle:D: :$enc --> Str)\n\nB<DEPRECATION NOTICE:> this method is deprecated in the C<6.d> version. Do\nnot use it for new code, use L«C<.slurp> method|/routine/slurp» instead.\n\nReturns the remaining content of the file from the current file position (which\nmay have been set by previous reads or by C<seek>.)  If the adverb C<:bin> is\nprovided a L<C<Buf>|/type/Buf> will be returned; otherwise the return will be a L<C<Str>|/type/Str> with\nthe optional encoding C<:enc>.\n\n=head2 method slurp\n\n    method slurp(IO::Handle:D: :$close, :$bin)\n\nReturns all the content from the current file pointer to the end. If the\ninvocant is in binary mode or if C<$bin> is set to C<True>, will return a\nL<C<Buf>|/type/Buf>, otherwise will decode the content using invocant's current\nL«C<.encoding>|/routine/encoding» and return a L<C<Str>|/type/Str>.\n\nIf C<:$close> is set to C<True>, will close the handle when finished reading.\n\nB<Note:> On L<Rakudo|/language/glossary#Rakudo> this method was introduced\nwith release 2017.04; C<$bin> arg was added in 2017.10.\n\n=head2 method Supply\n\n    multi method Supply(IO::Handle:D: :$size = 65536)\n\nReturns a L«C<Supply>|/type/Supply» that will emit the contents of the handle in chunks.\nThe chunks will be L«C<Buf>|/type/Buf» if the handle is in binary mode\nor, if it isn't, L«C<Str>|/type/Str» decoded using same encoding as\nL«C<IO::Handle.encoding>|/routine/encoding».\n\nThe size of the chunks is determined by the optional C<:size> named\nparameter and C<65536> bytes in binary mode or C<65536> characters in non-binary\nmode.\n\n=begin code\n\"foo\".IO.open(:bin).Supply(:size<10>).tap: *.raku.say;\n# OUTPUT:\n# Buf[uint8].new(73,32,226,153,165,32,80,101,114,108)\n# Buf[uint8].new(32,54,33,10)\n\n\"foo\".IO.open.Supply(:size<10>).tap: *.raku.say;\n# OUTPUT:\n# \"I ♥ Perl\"\n# \" 6!\\n\"\n=end code\n\n=head2 method path\n\n    method path(IO::Handle:D:)\n\nFor a handle opened on a file this returns the L<C<IO::Path>|/type/IO::Path> that\nrepresents the file. For the standard I/O handles\nL«C<$*IN>|/language/variables#index-entry-%24%2AIN»,\nL«C<$*OUT>|/language/variables#index-entry-%24%2AOUT», and\nL«C<$*ERR>|/language/variables#index-entry-%24%2AERR» it returns an\nL<C<IO::Special>|/type/IO::Special> object.\n\n=head2 method IO\n\n    method IO(IO::Handle:D:)\n\nAlias for L«C<.path>|/type/IO::Handle#method_path»\n\n=head2 method Str\n\nReturns the value of L«C<.path>|/type/IO::Handle#method_path», coerced\nto L<C<Str>|/type/Str>.\n\n=for code\nsay \"foo\".IO.open.Str; # OUTPUT: «foo␤»\n\n=head2 routine close\n\n    method close(IO::Handle:D: --> Bool:D)\n    multi  close(IO::Handle $fh)\n\nCloses an open filehandle, returning C<True> on success. No error is thrown if the\nfilehandle is already closed, although if you close one of the standard\nfilehandles (by default: C<$*IN>, C<$*OUT>, or C<$*ERR>: any handle\nwith L<native-descriptor|/routine/native-descriptor> C<2> or lower), you won't be\nable to re-open them.\n\n=for code\ngiven \"foo/bar\".IO.open(:w) {\n    .spurt: \"I ♥ Raku!\";\n    .close;\n}\n\nIt's a common idiom to use L«C<LEAVE> phaser|/language/phasers#LEAVE» for\nclosing the handles, which ensures the handle is closed regardless of how the\nblock is left.\n\n=begin code\ndo {\n    my $fh = open \"path-to-file\";\n    LEAVE close $fh;\n    # ... do stuff with the file\n}\n\nsub do-stuff-with-the-file (IO $path-to-file) {\n  my $fh = $path-to-file.open;\n\n  # stick a `try` on it, since this will get run even when the sub is\n  # called with wrong arguments, in which case the `$fh` will be an `Any`\n  LEAVE try close $fh;\n\n  # ... do stuff with the file\n}\n=end code\n\nB<Note:> unlike some other languages, Raku does not use reference counting,\nand so B<the filehandles are NOT closed when they go out of scope>. While\nthey I<will> get closed when garbage collected, garbage collection isn't\nguaranteed to get run. This means B<you must> use an explicit C<close> on\nhandles opened for writing, to avoid data loss, and an explicit C<close>\nis I<recommended> on handles opened for reading as well, so that your program\ndoes not open too many files at the same time, triggering exceptions on further\nC<open> calls.\n\nNote several methods allow for providing C<:close> argument, to close the handle\nafter the operation invoked by the method completes. As a simpler alternative,\nthe L<C<IO::Path>|/type/IO::Path> type provides many reading and writing methods that let you work\nwith files without dealing with filehandles directly.\n\n=head2 method flush\n\n    method flush(IO::Handle:D: --> True)\n\nWill flush the handle, writing any of the buffered data. Returns C<True>\non success; otherwise, L<fails|/routine/fail> with L<C<X::IO::Flush>|/type/X::IO::Flush>.\n\n=begin code\ngiven \"foo\".IO.open: :w {\n    LEAVE .close;\n    .print: 'something';\n    'foo'.IO.slurp.say; # (if the data got buffered) OUTPUT: «␤»\n    .flush;             # flush the handle\n    'foo'.IO.slurp.say; # OUTPUT: «something␤»\n}\n=end code\n\n=head2 method native-descriptor\n\n    method native-descriptor(IO::Handle:D:)\n\nThis returns a value that the operating system would understand as a \"file\ndescriptor\" and is suitable for passing to a native function that requires a\nfile descriptor as an argument such as C<fcntl> or C<ioctl>.\n\n=head2 method nl-in\n\n    method nl-in(--> Str:D) is rw\n\nOne of the attributes that can be set via C<.new> or L<open|/routine/open>.\nDefaults to C<[\"\\x0A\", \"\\r\\n\"]>. Takes either a L<C<Str>|/type/Str> or\nL<C<Array>|/type/Array> of L<C<Str>|/type/Str> specifying input line ending(s) for this handle.\nIf C<.chomp> attribute is set to C<True>, will strip these endings in routines\nthat C<chomp>, such as L«C<get>|/routine/get» and L«C<lines>|/routine/lines».\n\n=begin code\nwith 'test'.IO {\n    .spurt: '1foo2bar3foo'; # write some data into our test file\n    my $fh will leave {.close} = .open; # can also set .nl-in via .open arg\n    $fh.nl-in = [<foo bar>]; # set two possible line endings to use;\n    $fh.lines.say; # OUTPUT: (\"1\", \"2\", \"3\").Seq\n}\n=end code\n\n=head2 method nl-out\n\n    has Str:D $.nl-out is rw = \"\\n\";\n\nOne of the attributes that can be set via C<.new> or L<open|/routine/open>.\nDefaults to C<\"\\n\">. Takes a L<C<Str>|/type/Str> specifying output line ending for this\nhandle, to be used by methods L«C<.put>|/type/IO::Handle#method_put»\nand L«C<.say>|/type/IO::Handle#method_say».\n\n=begin code\nwith 'test'.IO {\n    given .open: :w {\n        .put: 42;\n        .nl-out = 'foo';\n        .put: 42;\n        .close;\n    }\n    .slurp.raku.say; # OUTPUT: «\"42\\n42foo\"␤»\n}\n=end code\n\n=head2 method opened\n\n    method opened(IO::Handle:D: --> Bool:D)\n\nReturns C<True> if the handle is open, C<False> otherwise.\n\nX<|Reference,tty>\n=head2 method t\n\n    method t(IO::Handle:D: --> Bool:D)\n\nReturns C<True> if the handle is opened to a\nL<TTY|https://en.wikipedia.org/wiki/Terminal_emulator>, C<False> otherwise.\n\n=head1 Creating Custom Handles\n\nAs of 6.d language (early implementation available in Rakudo compiler\nrelease 2018.08), a few helper methods are available to simplify creation of\ncustom C<IO::Handle> objects. In your subclass you simply need to implement\nthose methods to affect all of the related features. If your handle wants\nto work with textual read/write methods and doesn't use the standard C<.open>\nmethod, be sure to call C<.encoding> method in your custom handle to get\ndecoder/encoder properly set up:\n\n=begin code :skip-test<needs ecosystem>\nclass IO::URL is IO::Handle {\n    has $.URL is required;\n    has Buf $!content;\n    submethod TWEAK {\n        use WWW; # ecosystem module that will let us `get` a web page\n        use DOM::Tiny; # ecosystem module that will parse out all text from HTML\n        $!content := Buf.new: DOM::Tiny.parse(get $!URL).all-text(:trim).encode;\n        self.encoding: 'utf8'; # set up encoder/decoder\n    }\n\n    method open(|)  { self }       # block out some IO::Handle methods\n    method close(|) { self }       # that work with normal low-level file\n    method opened   { ! self.EOF } # handles, since we don't. This isn't\n    method lock(| --> True) { }    # necessary, but will make our handle\n    method unlock( --> True) { }   # be more well-behaved if someone\n    # actually calls one of these methods. There are more of these you\n    # can handle, such as .tell, .seek, .flush, .native-descriptor, etc.\n\n    method WRITE(|) {\n        # For this handle we'll just die on write. If yours can handle writes.\n        # The data to write will be given as a Blob positional argument.\n        die \"Cannot write into IO::URL\";\n    }\n    method READ(\\bytes) {\n        # We splice off the requested number of bytes from the head of\n        # our content Buf. The handle's decoder will handle decoding them\n        # automatically, if textual read methods were called on the handle.\n        $!content.splice: 0, bytes\n    }\n    method EOF {\n        # For \"end of file\", we'll simply report whether we still have\n        # any bytes of the website we fetched on creation.\n        not $!content\n    }\n}\n\nmy $fh := IO::URL.new: :URL<raku.org>;\n\n# .slurp and print all the content from the website. We can use all other\n# read methods, such as .lines, or .get, or .readchars. All of them work\n# correctly, even though we only defined .READ and .EOF\n$fh.slurp.say;\n=end code\n\n=head2 method WRITE\n\n    method WRITE(IO::Handle:D: Blob:D \\data --> Bool:D)\n\nCalled whenever a write operation is performed on the handle. Always receives\nthe data as a L<C<Blob>|/type/Blob>, even if a textual writing method has been\ncalled.\n\n=begin code\nclass IO::Store is IO::Handle {\n    has @.lines = [];\n\n    submethod TWEAK {\n        self.encoding: 'utf8'; # set up encoder/decoder\n    }\n\n    method WRITE(IO::Handle:D: Blob:D \\data --> Bool:D) {\n        @!lines.push: data.decode();\n        True;\n    }\n\n    method gist() {\n        return @!lines.join(\"\\n\" );\n    }\n}\nmy $store = IO::Store.new();\nmy $output = $PROCESS::OUT;\n$PROCESS::OUT = $store;\n.say for <one two three>;\n$PROCESS::OUT = $output;\nsay $store.lines(); # OUTPUT: «[one␤ two␤ three␤]»\n=end code\n\nIn this example we are creating a simple C<WRITE> redirection which stores\nanything written to the filehandle to an array. We need to save the standard\noutput first, which we do in C<$output>, and then everything that is C<print>ed\nor said (through C<say>) gets stored in the defined C<IO::Store> class. Two\nthings should be taken into account in this class. By default, C<IO::Handle>s\nare in binary mode, so we need to C<TWEAK> the objects if we want them to work\nwith text. Second, a C<WRITE> operation should return C<True> if successful. It\nwill fail if it does not.\n\n=head2 method READ\n\n    method READ(IO::Handle:D: Int:D \\bytes --> Buf:D)\n\nCalled whenever a read operation is performed on the handle. Receives the number\nof bytes requested to read. Returns a L<C<Buf>|/type/Buf> with those bytes which\ncan be used to either fill the decoder buffer or returned from reading methods\ndirectly. The result is allowed to have fewer than the requested number of\nbytes, including no bytes at all.\n\nIf you provide your own C<.READ>, you very likely need to provide your own\nL<C«.EOF»|/routine/EOF> as well, for all the features to behave correctly.\n\nThe compiler may call L<C«.EOF»|/routine/EOF> method any number of times during\na read operation to ascertain whether a call to C<.READ> should be made. More\nbytes than necessary to satisfy a read operation may be requested from C<.READ>,\nin which case the extra data may be buffered by the C<IO::Handle> or the decoder\nit's using, to fulfill any subsequent reading operations, without necessarily\nhaving to make another C<.READ> call.\n\n=begin code\nclass IO::Store is IO::Handle {\n    has @.lines = [];\n\n    submethod TWEAK {\n      self.encoding: 'utf8'; # set up encoder/decoder\n    }\n\n    method WRITE(IO::Handle:D: Blob:D \\data --> Bool:D) {\n      @!lines.push: data;\n      True;\n    }\n\n    method whole() {\n      my Buf $everything = Buf.new();\n      for @!lines -> $b {\n        $everything ~= $b;\n      }\n      return $everything;\n    }\n\n    method READ(IO::Handle:D: Int:D \\bytes --> Buf:D) {\n      my Buf $everything := self.whole();\n      return $everything;\n    }\n\n    method EOF {\n      my $everything = self.whole();\n      !$everything;\n    }\n}\n\nmy $store := IO::Store.new();\n\n$store.print( $_ ) for <one two three>;\nsay $store.read(3).decode; # OUTPUT: «one␤»\nsay $store.read(3).decode; # OUTPUT: «two␤»\n=end code\n\nIn this case, we have programmed the two C<READ> and C<EOF> methods, as well as\nC<WRITE>, which stores every line in an element in an array. The C<read> method\nactually calls C<READ>, returning 3 bytes, which correspond to the three\ncharacters in the first two elements. Please note that it's the C<IO::Handle>\nbase class the one that is taking care of cursor, since C<READ> just provides a\nhandle into the whole content of the object; the base class will C<READ> 1024 *\n1024 bytes at a time. If your object is planned to hold an amount of bytes\nbigger than that, you will have to handle an internal cursor yourself. That is\nwhy in this example we don't actually use the C<bytes> argument.\n\n=head2 method EOF\n\n    method EOF(IO::Handle:D: --> Bool:D)\n\nIndicates whether \"end of file\" has been reached for the B<data source> of the\nhandle; i.e. no more data can be obtained by calling L<C«.READ»|/routine/READ>\nmethod. Note that this is B<not> the same as L<eof|/routine/eof> method, which\nwill return C<True> only if C<.EOF> returns C<True> B<and all the decoder\nbuffers>, if any were used by the handle, are also empty. See\nL<C«.READ»|/routine/READ> for an example implementation.\n\n=head1 Related roles and classes\n\nSee also the related role L<C<IO>|/type/IO> and the related class L<C<IO::Path>|/type/IO::Path>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Notification/Change.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::Notification::Change\n\n=SUBTITLE Changes in a file, produced by watch-file\n\n    class IO::Notification::Change {}\n\nC<IO::Notification.watch-path($path)> as well as\nL<C<IO::Path.watch>|/type/IO::Path#method_watch> produce a\nL<C<Supply>|/type/Supply>\nof C<IO::Notification::Change> events for a file or directory, depending on\nwhat is used as the C<$path> argument or L<C<IO::Path>|/type/IO::Path> object.\n\nHere is a small example that prints the first ten\nC<FileChanged>-notifications for the current working directory:\n\n=for code\nmy $finish = Promise.new;\nmy $count = 0;\nIO::Notification.watch-path($*CWD).act( -> $change {\n    $count++ if $change.event ~~ FileChanged;\n    say \"($count) $change.path(): $change.event()\";\n    $finish.keep if $count >= 10;\n});\nawait $finish;\n\nThe type of the change is very much dependent both on the platform and\non specific system calls that were used to initiate the change. At this\npoint in time you should not rely on the type of change in general, and\ntest your particular situation.\n\n=head1 Methods\n\n=head2 method path\n\nReturns the path of the file that's being watched.\n\n=head2 method event\n\nReturns the type of event: C<FileChanged> or C<FileRenamed>.\n\n=head2 method IO\n\nReturns a handle of the file that's being watched.\n\n=head2 method gist\n\n    multi method gist(IO::Notification::Change:D:)\n\nReturns the path and event attributes, separated by semicolon.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Notification.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::Notification\n\n=SUBTITLE Asynchronous notification for file and directory changes\nX<|Types,FileChangeEvent (enum)>\nX<|Types,FileChanged (FileChangeEvent)>\nX<|Types,FileRenamed (FileChangeEvent)>\n=for code\nenum FileChangeEvent (:FileChanged(1), :FileRenamed(2));\n=for code\nclass IO::Notification {}\n\nEssentially, this class exists as a placeholder for the C<IO::Notification.watch-path($path)>\nmethod, that produces a L<C<Supply>|/type/Supply>\nof L<C<IO::Notification::Change>|/type/IO::Notification::Change> events for a\nfile or directory.\n\n=head1 Methods\n\n=head2 method watch-path\n\n=for code\nmethod watch-path(IO::Notification: Str() $path, :$scheduler = $*SCHEDULER)\n\nReturns a L<C<Supply>|/type/Supply> that emits L<C<IO::Notification::Change>|/type/IO::Notification::Change> objects.\n\nIf C<$path> is a file, only modifications of that file are reported. If\nC<$path> is a directory, both modifications to the directory itself (for\nexample permission changes) and to files in the directory (including new\nfiles in the directory) are reported.\n\nThe C<:$scheduler> named argument allows you to specify which thread scheduler\nis going to be responsible for the notification stream; it can be omitted if\nthe default scheduler is used.\n\n=begin code\nmy $supply = IO::Notification.watch-path( \"/var/log/syslog\" );\n\n$supply.tap( -> $v { say \"Got \", $v });\n\nsleep 60;\n=end code\n\nThis snippet of code sets a watch on the system log file, emitting the kind\nof event that has occurred or capturing an error otherwise; the created\nL<C<Supply>|/type/Supply> is tapped, and the event printed. It does so for 60 minutes,\nemitting something like this:\n\n=for code :lang<text>\nGot /var/log/syslog: FileChanged\nGot /var/log/syslog: FileChanged\nGot /var/log/syslog: FileChanged\nGot /var/log/syslog: FileChanged\nGot /var/log/syslog: FileChanged\nGot /var/log/syslog: FileChanged\nGot /var/log/syslog: FileChanged\nGot /var/log/syslog: FileChanged\n\nThe only kind of information this method provides is the bare fact that\nsomething has change or been renamed. You will need to actually open and read\nthe file or directory to check the actual changes.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Path/Cygwin.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::Path::Cygwin\n\n=SUBTITLE IO::Path pre-loaded with IO::Spec::Cygwin\n\n    class IO::Path::Cygwin is IO::Path { }\n\nThis sub-class of L«C<IO::Path>|/type/IO::Path», pre-loaded with\nL«C<IO::Spec::Cygwin>|/type/IO::Spec::Cygwin» in the C<$.SPEC> attribute.\n\n=head1 Methods\n\n=head2 method new\n\nSame as L«C<IO::Path.new>|/type/IO::Path#method_new», except\nC<:$SPEC> cannot be set and defaults to\nL«C<IO::Spec::Cygwin>|/type/IO::Spec::Cygwin», regardless of the operating\nsystem the code is being run on.\n\n=head2 method raku\n\n    method raku(IO::Path::Cygwin:D: --> Str:D)\n\nReturns a string that, when given passed through L«C<EVAL>|/routine/EVAL»\ngives the original invocant back.\n\n=for code\nIO::Path::Cygwin.new(\"foo/bar\").raku.say;\n# OUTPUT: IO::Path::Cygwin.new(\"foo/bar\", :CWD(\"/home/camelia\"))\n\nNote that this string includes the value of the C<.CWD> attribute that is set\nto L«C<$*CWD>|/language/variables#Dynamic_variables» when the path\nobject was created, by default.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Path/Parts.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::Path::Parts\n\n=SUBTITLE IO::Path parts encapsulation\n\n=begin code :skip-test<XXX need to define 'of' method in test's anon class>\nclass IO::Path::Parts does Positional does Associative does Iterable { }\n=end code\n\nAn C<IO::Path::Parts> object is a container for the parts of an\nL«C<IO::Path>|/type/IO::Path» object. It is usually created with\na call to the method L«C<.parts>|/type/IO::Path#method_parts» on an\nL«C<IO::Path>|/type/IO::Path» object. It can also be created with a call to the method\nL«C<.split>|/routine/split» on an object of one of the low-level path\noperations sub-classes of L«C<IO::Spec>|/type/IO::Spec».\n\nThe parts of an L«C<IO::Path>|/type/IO::Path» are:\n\n=item the volume, see L«C<.volume>|/type/IO::Path#method_volume»\n=item the directory name, see L«C<.dirname>|/type/IO::Path#method_dirname»\n=item the basename, see L«C<.basename>|/type/IO::Path#method_basename»\n\n=head1 Methods\n\n=head2 method new\n\n    method new(\\volume, \\dirname, \\basename)\n\nCreate a new C<IO::Path::Parts> object with C<\\volume>, C<\\dirname>\nand C<\\basename> as respectively the volume, directory name and basename\nparts.\n\n=head2 attribute volume\n\nRead-only. Returns the volume of the C<IO::Path::Parts> object.\n\n=begin code\nIO::Path::Parts.new('C:', '/some/dir', 'foo.txt').volume.say;\n# OUTPUT: «C:␤»\n=end code\n\n=head2 attribute dirname\n\nRead-only. Returns the directory name part of the C<IO::Path::Parts>\nobject.\n\n=begin code\nIO::Path::Parts.new('C:', '/some/dir', 'foo.txt').dirname.say;\n# OUTPUT: «/some/dir␤»\n=end code\n\n=head2 attribute basename\n\nRead-only. Returns the basename part of the C<IO::Path::Parts> object.\n\n=begin code\nIO::Path::Parts.new('C:', '/some/dir', 'foo.txt').basename.say;\n# OUTPUT: «foo.txt␤»\n=end code\n\n=head1 Previous implementations\n\nBefore Rakudo 2020.06 the C<.parts> method of L«C<IO::Path>|/type/IO::Path» returned\na L«C<Map>|/type/Map» and the C<.split> routine of the L«C<IO::Spec>|/type/IO::Spec»\nsub-classes returned a L«C<List>|/type/List» of L«C<Pair>|/type/Pair».\nThe C<IO::Path::Parts> class maintains compatibility with these\nprevious implementations by doing L«C<Positional>|/type/Positional»,\nL«C<Associative>|/type/Associative» and L«C<Iterable>|/type/Iterable».\n\n=begin code\nmy $parts = IO::Path::Parts.new('C:', '/some/dir', 'foo.txt');\nsay $parts<volume>;      # OUTPUT: «C:␤»\nsay $parts[0];           # OUTPUT: «volume => C:␤»\nsay $parts[0].^name;     # OUTPUT: «Pair␤»\n.say for $parts[];\n# OUTPUT: «volume => C:␤dirname => /some/dir␤basename => foo.txt␤»\n=end code\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Path/QNX.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::Path::QNX\n\n=SUBTITLE IO::Path pre-loaded with IO::Spec::QNX\n\n    class IO::Path::QNX is IO::Path { }\n\nThis sub-class of L«C<IO::Path>|/type/IO::Path», pre-loaded with\nL«C<IO::Spec::QNX>|/type/IO::Spec::QNX» in the C<$.SPEC> attribute.\n\n=head1 Methods\n\n=head2 method new\n\nSame as L«C<IO::Path.new>|/type/IO::Path#method_new», except\nC<:$SPEC> cannot be set and defaults to\nL«C<IO::Spec::QNX>|/type/IO::Spec::QNX», regardless of the operating system\nthe code is being run on.\n\n=head2 method raku\n\n    method raku(IO::Path::QNX:D: --> Str:D)\n\nReturns a string that, when given passed through L«C<EVAL>|/routine/EVAL»\ngives the original invocant back.\n\n=for code\nIO::Path::QNX.new(\"foo/bar\").raku.say;\n# OUTPUT: IO::Path::QNX.new(\"foo/bar\", :CWD(\"/home/camelia\"))\n\nNote that this string includes the value of the C<.CWD> attribute that is set\nto L«C<$*CWD>|/language/variables#Dynamic_variables» when the path\nobject was created, by default.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Path/Unix.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::Path::Unix\n\n=SUBTITLE IO::Path pre-loaded with IO::Spec::Unix\n\n    class IO::Path::Unix is IO::Path { }\n\nThis sub-class of L«C<IO::Path>|/type/IO::Path», pre-loaded with\nL«C<IO::Spec::Unix>|/type/IO::Spec::Unix» in the C<$.SPEC> attribute.\n\n=head1 Methods\n\n=head2 method new\n\nSame as L«C<IO::Path.new>|/type/IO::Path#method_new», except\nC<:$SPEC> cannot be set and defaults to\nL«C<IO::Spec::Unix>|/type/IO::Spec::Unix», regardless of the operating system\nthe code is being run on.\n\n=head2 method raku\n\n    method raku(IO::Path::Unix:D: --> Str:D)\n\nReturns a string that, when given passed through L«C<EVAL>|/routine/EVAL»\ngives the original invocant back.\n\n=for code\nIO::Path::Unix.new(\"foo/bar\").raku.say;\n# OUTPUT: IO::Path::Unix.new(\"foo/bar\", :CWD(\"/home/camelia\"))\n\nNote that this string includes the value of the C<.CWD> attribute that is set\nto L«C<$*CWD>|/language/variables#Dynamic_variables» when the path\nobject was created, by default.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Path/Win32.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::Path::Win32\n\n=SUBTITLE IO::Path pre-loaded with IO::Spec::Win32\n\n    class IO::Path::Win32 is IO::Path { }\n\nThis sub-class of L«C<IO::Path>|/type/IO::Path», pre-loaded with\nL«C<IO::Spec::Win32>|/type/IO::Spec::Win32» in the C<$.SPEC> attribute.\n\n=head1 Methods\n\n=head2 method new\n\nSame as L«C<IO::Path.new>|/type/IO::Path#method_new», except\nC<:$SPEC> cannot be set and defaults to\nL«C<IO::Spec::Win32>|/type/IO::Spec::Win32», regardless of the operating system\nthe code is being run on.\n\n=head2 method raku\n\n    method raku(IO::Path::Win32:D: --> Str:D)\n\nReturns a string that, when given passed through L«C<EVAL>|/routine/EVAL»\ngives the original invocant back.\n\n=for code\nIO::Path::Win32.new(\"foo/bar\").raku.say;\n# OUTPUT: IO::Path::Win32.new(\"foo/bar\", :CWD(\"C:\\\\Users\\\\camelia\"))\n\nNote that this string includes the value of the C<.CWD> attribute that is set\nto L«C<$*CWD>|/language/variables#Dynamic_variables» when the path\nobject was created, by default.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Path.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::Path\n\n=SUBTITLE File or directory path\n\n=for code\nclass IO::Path is Cool does IO { }\n\nC<IO::Path> is the workhorse of IO operations.\n\nConceptually, an C<IO::Path> object consists of a volume, a directory,\nand a basename. It supports both purely textual operations, and\noperations that access the filesystem, e.g. to resolve a path, or to\nread all the content of a file.\n\nAt creation, each C<IO::Path> object is given information about the\ncurrent working directory the path might be relative to using the\nC<$.CWD> attribute (defaults to\nL«C<$*CWD>|/language/variables#Dynamic_variables»), as well as what\noperating system semantics should be used for path manipulation using\nthe special L«C<IO::Spec>|/type/IO::Spec» type given in the C<$.SPEC>\nattribute.\n\nThe C<$.SPEC> defaults to the value of\nL«C<$*SPEC>|/language/variables#Dynamic_variables», which uses the object\nsuitable for the operating system the code is currently running on. This is\nthe default most code will be comfortable with.\n\nIn certain situations, e.g. testing, you may wish to force C<$*SPEC> to use one\nof the specific SPEC modules: L«C<IO::Spec::Unix>|/type/IO::Spec::Unix»,\nL«C<IO::Spec::Win32>|/type/IO::Spec::Win32»,\nL«C<IO::Spec::Cygwin>|/type/IO::Spec::Cygwin», and\nL«C<IO::Spec::QNX>|/type/IO::Spec::QNX», or to create C<IO::Path> objects via\nshortcut subclasses L«C<IO::Path::Unix>|/type/IO::Path::Unix»,\nL«C<IO::Path::Win32>|/type/IO::Path::Win32»,\nL«C<IO::Path::Cygwin>|/type/IO::Path::Cygwin», and\nL«C<IO::Path::QNX>|/type/IO::Path::QNX» that pre-set the C<$.SPEC> attribute\nfor you.\n\nThe rest of this document silently assumes Unix semantics in its\nexamples, unless stated otherwise.\n\n=head1 Methods\n\n=head2 method new\n\n=for code :skip-test<compile time error>\nmulti method new(Str:D $path, IO::Spec :$SPEC = $*SPEC, Str() :$CWD = $*CWD)\nmulti method new(\n    :$basename!, :$dirname = '.', :$volume = ''\n    IO::Spec :$SPEC = $*SPEC, Str() :$CWD = $*CWD\n)\n\nCreates a new C<IO::Path> object from a path string (which is being\nparsed for volume, directory name and basename), or from volume,\ndirectory name and basename passed as named arguments.\n\nThe path's operation will be performed using C<:$SPEC> semantics (defaults to\ncurrent L«C<$*SPEC>|/language/variables#Dynamic_variables») and will use\nC<:$CWD> as the directory the path is relative to (defaults to\nL«C<$*CWD>|/language/variables#Dynamic_variables»).\n\nIf C<$path> includes the null byte, it will throw an Exception with a \"Cannot\nuse null character (U+0000) as part of the path\" message.\n\n\n=head2 attribute CWD\n\n    IO::Path.new(\"foo\", :CWD</home/camelia>)\n        .CWD.say; # OUTPUT: «/home/camelia␤»\n\nRead-only. Contains implicit or explicit value of C<:$CWD> argument to C<.new>.\n\n=head2 attribute SPEC\n\n    IO::Path.new(\"foo\", :SPEC(IO::Spec::Unix.new))\\\n        .SPEC.^name.say; # OUTPUT: «IO::Spec::Unix␤»\n\nRead-only. Contains implicit or explicit value of C<:$SPEC> argument to C<.new>.\n\n=head2 attribute path\n\n    IO::Path.new(\"foo\").path.say; # OUTPUT: «foo␤»\n\nRead-only. Returns the string the object was constructed from or the value of\nC<$SPEC.join($volume, $dirname, $basename)> if multi-part version of C<.new>\nwas used. B<NOTE:> this does not include the C<$.CWD>; see\nL«C<IO::Path.absolute>|/routine/absolute»\nand L«C<IO::Path.relative>|/routine/relative» for\nstringification options that include C<$.CWD>.\n\nB<NOTE:> Implementations may cache operations done with this attribute, so\nmodifying its value (via cloning or Proxy) is NOT recommended and may result\nin broken C<IO::Path> objects. Create a new C<IO::Path> object instead.\n\n=head2 method ACCEPTS\n\n    multi method ACCEPTS(IO::Path:D: Cool:D $other --> Bool:D)\n\nCoerces the argument to C<IO::Path>, if necessary. Returns C<True> if\nL«C<.absolute>|/routine/absolute» method on both paths returns the same string.\nB<NOTE:> it's possible for two paths that superficially point to the same\nresource to NOT smartmatch as C<True>, if they were constructed differently and\nwere never fully resolved:\n\n    say \"foo/../bar\".IO ~~ \"bar\".IO # False\n\nThe reason is the two paths above may point to different resources when fully\nresolved (e.g. if C<foo> is a symlink). Resolve the paths before smartmatching\nto check they point to same resource:\n\n    say \"foo/../bar\".IO.resolve(:completely) ~~ \"bar\".IO.resolve(:completely) # True\n\n=head2 method basename\n\n    method basename(IO::Path:D:)\n\nReturns the basename part of the path object, which is the name of the\nfilesystem object itself that is referenced by the path.\n\n    \"docs/README.pod\".IO.basename.say; # OUTPUT: «README.pod␤»\n    \"/tmp/\".IO.basename.say;           # OUTPUT: «tmp␤»\n\nNote that in L«C<IO::Spec::Win32>|/type/IO::Spec::Win32» semantics, the\nC<basename> of a Windows share is C<\\>, not the name of the share itself:\n\n    IO::Path::Win32.new('//server/share').basename.say; # OUTPUT: «\\␤»\n\n=head2 method add\n\n    method add(IO::Path:D: Str() $what --> IO::Path:D)\n\nConcatenates a path fragment to the invocant and returns the resultant\nC<IO::Path>. If adding C<../> to paths that end with a file, you may\nneed to call L<resolve|/routine/resolve> for the resultant path to be accessible by other\nC<IO::Path> methods like L<dir|/routine/dir> or L<open|/routine/open>. See also L<sibling|/routine/sibling> and\nL<parent|/routine/parent>.\n\n    \"foo/bar\".IO.mkdir;\n    \"foo/bar\".IO.add(\"meow\")    .resolve.relative.say; # OUTPUT: «foo/bar/meow␤»\n    \"foo/bar\".IO.add(\"/meow\")   .resolve.relative.say; # OUTPUT: «foo/bar/meow␤»\n    \"foo/bar\".IO.add(\"meow.txt\").resolve.relative.say; # OUTPUT: «foo/bar/meow.txt␤»\n    \"foo/bar\".IO.add(\"../meow\") .resolve.relative.say; # OUTPUT: «foo/meow␤»\n    \"foo/bar\".IO.add(\"../../\")  .resolve.relative.say; # OUTPUT: «.␤»\n\n    method add(IO::Path:D: *@parts --> IO::Path:D)\n\nAs of release 2021.07 of the Rakudo compiler, it is also possible to\nspecify multiple parts to be added to a path.\n\n    \"foo\".IO.add(<bar baz>).resolve.relative.say;      # OUTPUT: «foo/bar/baz␤»\n\n=head2 method child\n\n    method child(IO::Path:D: Str() $childname --> IO::Path:D)\n\nAlias for L«C<.add>|/routine/add».\n\n=head2 method cleanup\n\n    method cleanup(IO::Path:D: --> IO::Path:D)\n\nReturns a new path that is a canonical representation of the invocant path,\ncleaning up any extraneous path parts:\n\n    \"foo/./././..////bar\".IO.cleanup.say;      # OUTPUT: «\"foo/../bar\".IO␤»\n    IO::Path::Win32.new(\"foo/./././..////bar\")\n        .cleanup.say; \"foo\\..\\bar\".IO;         # OUTPUT: «\"foo\\..\\bar\".IO␤»\n\nNote that no filesystem access is made. See also\nL«C<resolve>|/routine/resolve».\n\n=head2 method comb\n\n    method comb(IO::Path:D: |args --> Seq:D)\n\nOpens the file and processes its contents the same way\nL«C<Str.comb>|/type/Str#routine_comb» does, taking the same arguments.\nImplementations may slurp the file in its entirety when this method is called.\n\n=head2 method split\n\n    method split(IO::Path:D: |args --> Seq:D)\n\nOpens the file and processes its contents the same way\nL«C<Str.split>|/type/Str#routine_split» does, taking the same arguments.\nImplementations may slurp the file in its entirety when this method is called.\n\n=head2 method extension\n\n    multi method extension(IO::Path:D:                                         --> Str:D)\n    multi method extension(IO::Path:D:               Int :$parts               --> Str:D)\n    multi method extension(IO::Path:D:             Range :$parts               --> Str:D)\n    multi method extension(IO::Path:D: Str $subst,   Int :$parts, Str :$joiner --> IO::Path:D)\n    multi method extension(IO::Path:D: Str $subst, Range :$parts, Str :$joiner --> IO::Path:D)\n\nReturns the extension consisting of C<$parts> parts (defaults to C<1>),\nwhere a \"part\" is defined\nas a dot followed by possibly-empty string up to the end of the string, or\nprevious part. That is C<\"foo.tar.gz\"> has an extension of two parts: first part\nis C<\"gz\"> and second part is C<\"tar\"> and calling\nC<\"foo.tar.gz\".IO.extension: :2parts> gives C<\"tar.gz\">. If an extension with\nthe specified number of C<$parts> is not found, returns an empty string.\n\nC<$parts> can be a L«C<Range>|/type/Range», specifying the minimum number of\nparts and maximum number of parts the extension should have. The routine will\nattempt to much the most parts it can. If C<$parts> range's endpoints that are\nsmaller than C<0> they'll be treated as C<0>; implementations may treat\nendpoints larger than C<2⁶³-1> as C<2⁶³-1>. Ranges with C<NaN> or\nL«C<Str>|/type/Str» endpoints will cause an exception to be thrown.\n\nIf C<$subst> is provided, the extension will be instead replaced with C<$subst>\nand a new C<IO::Path> object will be returned. It will be joined to the file's\nname with C<$joiner>, which defaults to an empty string when C<$subst> is\nan empty string and to C<\".\"> when C<$subst> is not empty. B<Note:> if as\nthe result of replacement the L«C<basename>|/routine/basename» of the path\nends up being empty, it will be assumed to be C<.> (a single dot).\n\n    # Getting an extension:\n    say \"foo.tar.gz\".IO.extension;               # OUTPUT: «gz␤»\n    say \"foo.tar.gz\".IO.extension: :2parts;      # OUTPUT: «tar.gz␤»\n    say \"foo.tar.gz\".IO.extension: :parts(^5);   # OUTPUT: «tar.gz␤»\n    say \"foo.tar.gz\".IO.extension: :parts(0..1); # OUTPUT: «gz␤»\n\n    # Replacing an extension\n    say \"foo.tar.gz\".IO.extension: '';                # OUTPUT: «\"foo.tar\".IO␤»\n    say \"foo.tar.gz\".IO.extension: 'ZIP';             # OUTPUT: «\"foo.tar.ZIP\".IO␤»\n    say \"foo.tar.gz\".IO.extension: 'ZIP', :0parts;    # OUTPUT: «\"foo.tar.gz.ZIP\".IO␤»\n    say \"foo.tar.gz\".IO.extension: 'ZIP', :2parts;    # OUTPUT: «\"foo.ZIP\".IO␤»\n    say \"foo.tar.gz\".IO.extension: 'ZIP', :parts(^5); # OUTPUT: «\"foo.ZIP\".IO␤»\n\n    # Replacing an extension using non-standard joiner:\n    say \"foo.tar.gz\".IO.extension: '',    :joiner<_>;  # OUTPUT: «\"foo.tar_\".IO␤»\n    say \"foo.tar.gz\".IO.extension: 'ZIP', :joiner<_>;  # OUTPUT: «\"foo.tar_ZIP\".IO␤»\n    say \"foo.tar.gz\".IO.extension: 'ZIP', :joiner<_>,\n                                           :2parts;     # OUTPUT: «\"foo_ZIP\".IO␤»\n    say \"foo.tar.gz\".IO.extension: 'ZIP', :joiner<_>,\n                                           :parts(^5);  # OUTPUT: «\"foo_ZIP\".IO␤»\n\n    # EDGE CASES:\n\n    # There is no 5-part extension, so returned value is an empty string\n    say \"foo.tar.gz\".IO.extension: :5parts; # OUTPUT: «␤»\n\n    # There is no 5-part extension, so we replaced nothing:\n    say \"foo.tar.gz\".IO.extension: 'ZIP', :5parts; # OUTPUT: «\"foo.tar.gz\".IO␤»\n\n    # Replacing a 0-part extension is just appending:\n    say \"foo.tar.gz\".IO.extension: 'ZIP', :0parts; # OUTPUT: «\"foo.tar.gz.ZIP\".IO␤»\n\n    # Replace 1-part of the extension, using '.' joiner\n    say \"...\".IO.extension: 'tar'; # OUTPUT: «\"...tar\".IO␤»\n\n    # Replace 1-part of the extension, using empty string joiner\n    say \"...\".IO.extension: 'tar', :joiner(''); # OUTPUT: «\"..tar\".IO␤»\n\n    # Remove 1-part extension; results in empty basename, so result is \".\".IO\n    say \".\".IO.extension: ''; # OUTPUT: «\".\".IO␤»\n\n=head2 method dirname\n\n    method dirname(IO::Path:D:)\n\nReturns the directory name portion of the path object. That is, it returns\nthe path excluding the L<volume|/routine/volume> and the\nL<base name|/routine/basename>. Unless the dirname consist of I<only> the directory\nseparator (i.e. it's the top directory), the trailing directory separator will I<not>\nbe included in the return value.\n\n    say IO::Path.new(\"/home/camelia/myfile.raku\").dirname; # OUTPUT: «/home/camelia␤»\n    say IO::Path::Win32.new(\"C:/home/camelia\").dirname;  # OUTPUT: «/home␤»\n    say IO::Path.new(\"/home\").dirname;                   # OUTPUT: «/␤»\n\n=head2 method volume\n\n    method volume(IO::Path:D:)\n\nReturns the volume portion of the path object. On Unix system, this is always\nthe empty string.\n\n    say IO::Path::Win32.new(\"C:\\\\Windows\\\\registry.ini\").volume;    # OUTPUT: «C:␤»\n\n=head2 method parts\n\n    method parts(IO::Path:D:)\n\nReturns an L«C<IO::Path::Parts>|/type/IO::Path::Parts» for the invocant.\n\n    say IO::Path::Win32.new(\"C:/rakudo/raku.bat\").parts.raku;\n    # OUTPUT: «IO::Path::Parts.new(\"C:\",\"/rakudo\",\"raku.bat\")␤»\n\nB<Note>: Before Rakudo release 2020.06 a L«C<Map>|/type/Map» was\nreturned, with the keys C<volume>, C<dirname>, C<basename> whose values\nwere the respective invocant parts.\n\n=head2 method raku\n\n    method raku(IO::Path:D: --> Str:D)\n\nReturns a string that, when given passed through L«C<EVAL>|/routine/EVAL»\ngives the original invocant back.\n\n=for code\n\"foo/bar\".IO.raku.say;\n# OUTPUT: IO::Path.new(\"foo/bar\", :SPEC(IO::Spec::Unix), :CWD(\"/home/camelia\"))\n\nNote that this string includes the value of the C<.CWD> attribute that is set\nto L«C<$*CWD>|/language/variables#Dynamic_variables» when the path\nobject was created, by default.\n\n=head2 method gist\n\n    method gist(IO::Path:D: --> Str:D)\n\nReturns a string, part of which contains either the value of\nL«C<.absolute>|/type/IO::Path#method_absolute» (if path is absolute) or\nL«C<.path>|/type/IO::Path#attribute_path». Note that no escaping\nof special characters is made, so e.g. C<\"\\b\"> means a path contains a backslash\nand letter \"b\", not a backspace.\n\n    say \"foo/bar\".IO;                       # OUTPUT: «\"foo/bar\".IO␤»\n    say IO::Path::Win32.new: ｢C:\\foo/bar\\｣; # OUTPUT: «\"C:\\foo/bar\\\".IO␤»\n\n=head2 method Str\n\n    method Str(IO::Path:D: --> Str)\n\nAlias for L«C<IO::Path.path>|/routine/path». In particular, note that default\nstringification of an C<IO::Path> does B<NOT> use the value of\nL«C<$.CWD> attribute|/type/IO::Path#attribute_CWD». To stringify while\nretaining full path information use L«C<.absolute>|/routine/absolute» or\nL«C<.relative>|/routine/relative» methods.\n\n=head2 method succ\n\n    method succ(IO::Path:D: --> IO::Path:D)\n\nReturns a new C<IO::Path> constructed from the invocant, with\nL«C<.basename>|/routine/basename» changed by calling\nL«C<Str.succ>|/type/Str#method_succ» on it.\n\n    \"foo/file_02.txt\".IO.succ.say; # OUTPUT: «\"foo/file_03.txt\".IO␤»\n\n=head2 method open\n\n    method open(IO::Path:D: *%opts)\n\nOpens the path as a file; the named options control the mode, and are the\nsame as the L<open|/routine/open> function accepts.\n\n=head2 method pred\n\n    method pred(IO::Path:D: --> IO::Path:D)\n\nReturns a new C<IO::Path> constructed from the invocant, with\nL«C<.basename>|/routine/basename» changed by calling\nL«C<Str.pred>|/type/Str#method_pred» on it.\n\n    \"foo/file02.txt\".IO.pred.say; # OUTPUT: «\"foo/file01.txt\".IO␤»\n\n=head2 method watch\n\n    method watch(IO::Path:D: --> Supply:D)\n\nEquivalent to calling\nL«IO::Notification.watch-path|/type/IO::Notification#method_watch-path»\nwith the invocant as the argument.\n\n=head2 method is-absolute\n\n    method is-absolute(IO::Path:D: --> Bool)\n\nReturns C<True> if the path is an absolute path, and C<False> otherwise.\n\n    \"/foo\".IO.is-absolute.say; # OUTPUT: «True␤»\n    \"bars\".IO.is-absolute.say; # OUTPUT: «False␤»\n\nNote that on Windows a path that starts with a slash or backslash is still\nconsidered absolute even if no volume was given, as it is absolute for that\nparticular volume:\n\n    IO::Path::Win32.new(\"/foo\"  ).is-absolute.say; # OUTPUT: «True␤»\n    IO::Path::Win32.new(\"C:/foo\").is-absolute.say; # OUTPUT: «True␤»\n    IO::Path::Win32.new(\"C:foo\" ).is-absolute.say; # OUTPUT: «False␤»\n\n=head2 method is-relative\n\n    method is-relative(IO::Path:D: --> Bool)\n\nReturns C<True> if the path is a relative path, and C<False> otherwise.\nWindows caveats for L«C<.is-absolute>|/type/IO::Path#method_is-absolute»\napply.\n\n=head2 method absolute\n\n    multi method absolute(IO::Path:D: --> Str)\n    multi method absolute(IO::Path:D: $base --> Str)\n\nReturns a new L«C<Str>|/type/Str» object that is an absolute path. If the invocant\nis not already an absolute path, it is first made absolute using C<$base>\nas base, if it is provided, or the C<.CWD> attribute the object was\ncreated with if it is not.\n\n=head2 method relative\n\n    method relative(IO::Path:D: $base = $*CWD --> Str)\n\nReturns a new L«C<Str>|/type/Str» object with the path relative to the C<$base>. If C<$base>\nis not provided, C<$*CWD> is used in its place. If the invocant is not\nan absolute path, it's first made to be absolute using the C<.CWD>\nattribute the object was created with, and then is made relative to C<$base>.\n\n=head2 method parent\n\n    multi method parent(IO::Path:D:)\n    multi method parent(IO::Path:D: UInt:D $level)\n\nReturns the parent path of the invocant. Note that no actual filesystem access\nis made, so the returned parent is physical and not the logical parent of\nsymlinked directories.\n\n    '/etc/foo'.IO.parent.say; # OUTPUT: «\"/etc\".IO␤»\n    '/etc/..' .IO.parent.say; # OUTPUT: «\"/etc\".IO␤»\n    '/etc/../'.IO.parent.say; # OUTPUT: «\"/etc\".IO␤»\n    './'      .IO.parent.say; # OUTPUT: «\"..\".IO␤»\n    'foo'     .IO.parent.say; # OUTPUT: «\".\".IO␤»\n    '/'       .IO.parent.say; # OUTPUT: «\"/\".IO␤»\n    IO::Path::Win32.new('C:/').parent.say; # OUTPUT: «\"C:/\".IO␤»\n\nIf C<$level> is specified, the call is equivalent to calling C<.parent()>\nC<$level> times:\n\n=for code\nsay \"/etc/foo\".IO.parent(2) eqv \"/etc/foo\".IO.parent.parent; # OUTPUT: «True␤»\n\n=head2 method resolve\n\n    method resolve(IO::Path:D: :$completely --> IO::Path)\n\nReturns a new C<IO::Path> object with all symbolic links and references to the\nparent directory (C<..>) resolved. This means that the filesystem is examined\nfor each directory in the path, and any symlinks found are followed.\n\n    # bar is a symlink pointing to \"/baz\"\n    my $io = \"foo/./bar/..\".IO.resolve;      # now \"/\" (the parent of \"/baz\")\n\nIf C<:$completely>, which defaults to C<False>, is set to a true value, the\nmethod will L«C<fail>|/routine/fail» with C<X::IO::Resolve> if it cannot\ncompletely resolve the path, otherwise, it will resolve as much as possible, and\nwill merely perform L«C<cleanup>|/routine/cleanup» of the rest of the path. The\nlast part of the path does B<NOT> have to exist to C<:$completely> resolve the\npath.\n\nNOTE: Currently (April 2017) this method doesn't work correctly on all\nplatforms, e.g. Windows, since C<resolve> assumes POSIX semantics.\n\n=head2 routine dir\n\n    multi  dir(*%_)\n    multi  dir(IO::Path:D $path, |c)\n    multi  dir(IO()       $path, |c)\n    method dir(IO::Path:D: Mu :$test = $*SPEC.curupdir)\n\nReturns a lazy list of C<IO::Path> objects corresponding to the entries in a\ndirectory, optionally filtered by L<smartmatching|/language/operators#infix_~~>\ntheir names I<as strings> per the C<:test> parameter. The order in which the\nfilesystem returns entries determines the order of the entries/objects in the\nlist. Objects corresponding to special directory entries C<.> and C<..> are not\nincluded. C<$path> determines whether the objects' paths are absolute or relative.\n\nSince the tests are performed against L«C<Str>|/type/Str» arguments, not L<C<IO>|/type/IO>, the tests are\nexecuted in the C<$*CWD>, instead of the target directory. When testing against\nfile test operators, this won't work:\n\n    dir('mydir', test => { .IO.d })\n\nwhile this will:\n\n    dir('mydir', test => { \"mydir/$_\".IO.d })\n\nB<NOTE:> a C<dir> call opens a directory for reading, which counts towards\nmaximum per-process open files for your program. Be sure to exhaust returned\nL<C<Seq>|/type/Seq> before doing something like recursively performing more C<dir>\ncalls. You can exhaust it by assigning to an C<@->sigiled variable or simply\nlooping over it. Note how examples below push further dirs to look through into\nan L<C<Array>|/type/Array>, rather than immediately calling C<dir> on them. See\nalso L«C<IO::Dir> module|https://raku.land/zef:raku-community-modules/IO::Dir» that gives you\nfiner control over closing dir handles.\n\nExamples:\n\n    # To iterate over the contents of the current directory:\n    for dir() -> $file {\n        say $file;\n    }\n\n    # As before, but include even '.' and '..' which are filtered out by\n    # the default :test matcher:\n    for dir(test => *) -> $file {\n        say $file;\n    }\n\n    # To get the names of all .jpg and .jpeg files in the home directory of the current user:\n    my @jpegs = $*HOME.dir: test => /:i '.' jpe?g $/;\n\nAn example program that lists all files and directories recursively:\n\n    sub MAIN($dir = '.') {\n        my @todo = $dir.IO;\n        while @todo {\n            for @todo.pop.dir -> $path {\n                say $path.Str;\n                @todo.push: $path if $path.d;\n            }\n        }\n    }\n\nA lazy way to find the first three files ending in \".raku\" recursively\nstarting from the current directory:\n\n=for code\nmy @stack = '.'.IO;\nmy $raku-files = gather while @stack {\n    with @stack.pop {\n        when :d { @stack.append: .dir }\n        .take when .extension.lc eq 'raku'\n    }\n}\n.put for $raku-files[^3];\n\n=head2 File test operators\n\nFor most file tests, you can do a smartmatch C<~~> or you can call a method.\nYou don't need to actually open a filehandle in the traditional way (although\nyou can) to do a filetest. You can simply append C<.IO> to the filename and\nsmartmatch it to a test adverb. For\ninstance, here is how to check whether a file is readable using smartmatch:\n\n    '/path/to/file'.IO ~~ :r;\n\nFile tests include:\n\n=item C<:d> (L«Directory|/type/IO::Path#method_d»)\n=item C<:e> (L«Exists|/type/IO::Path#method_e»)\n=item C<:f> (L«File|/type/IO::Path#method_f»)\n=item C<:l> (L«Symbolic link|/type/IO::Path#method_l»)\n=item C<:r> (L«Readable|/type/IO::Path#method_r»)\n=item C<:rw> (L«Readable and writable|/type/IO::Path#method_rw»)\n=item C<:rwx> (L«Readable, writable and executable|/type/IO::Path#method_rwx»)\n=item C<:s> (L«Size|/type/IO::Path#method_s»)\n=item C<:w> (L«Writable|/type/IO::Path#method_w»)\n=item C<:x> (L«Executable|/type/IO::Path#method_x»)\n=item C<:z> (L«Zero size|/type/IO::Path#method_z»)\n\nThese tests will not cache the results of earlier test executions.\n\nL«Smartmatching on Pairs|/type/Pair#method_ACCEPTS» can be used to perform\nmultiple tests at once:\n\n    say :d & :x;                # OUTPUT: «all(d => True, x => True)␤»\n    say '/tmp'.IO ~~ :d & :x;   # OUTPUT: «True␤»\n    say '/'.IO    ~~ :d & :rw;  # OUTPUT: «False␤»\n\nAll of the above tests can be used as methods (without the colon), though method\ntests may throw L<C<X::IO::DoesNotExist>|/type/X::IO::DoesNotExist> as documented below.  Three tests only\nexist as methods: L«C<accessed>|#method_accessed», L«C<changed>|#method_changed»\nand L«C<modified>|#method_modified».\n\nYou can also perform file tests on an already opened filehandle by testing\nagainst its L«C<.path>|/type/IO::Handle#method_path» method. For example, given\nfilehandle C<$fh>:\n\n=for code :preamble<my $fh>\n$fh.path ~~ :r;\n$fh.path.r;       # method form\n\n=head2 method e\n\n    method e(IO::Path:D: --> Bool:D)\n\nReturns C<True> if the invocant is a path that exists.\n\n=head2 method d\n\n    method d(IO::Path:D: --> Bool:D)\n\nReturns C<True> if the invocant is a path that exists and is a directory.\nThe method will L«C<fail>|/routine/fail» with L<C<X::IO::DoesNotExist>|/type/X::IO::DoesNotExist> if the\npath points to a non-existent filesystem entity.\n\n=head2 method f\n\n    method f(IO::Path:D: --> Bool:D)\n\nReturns C<True> if the invocant is a path that exists and is a file. The method\nwill L«C<fail>|/routine/fail» with L<C<X::IO::DoesNotExist>|/type/X::IO::DoesNotExist> if the path points to\na non-existent filesystem entity.\n\n=head2 method s\n\n    method s(IO::Path:D: --> Int:D)\n\nReturns the file size in bytes. May be called on paths that are directories, in\nwhich case the reported size is dependent on the operating system. The method\nwill L«C<fail>|/routine/fail» with L<C<X::IO::DoesNotExist>|/type/X::IO::DoesNotExist> if the path points to\na non-existent filesystem entity.\n\n    say $*EXECUTABLE.IO.s; # OUTPUT: «467␤»\n\n=head2 method l\n\n    method l(IO::Path:D: --> Bool:D)\n\nReturns C<True> if the invocant is a path that exists and is a symlink.\nThe method will L«C<fail>|/routine/fail» with L<C<X::IO::DoesNotExist>|/type/X::IO::DoesNotExist> if the\npath points to a non-existent filesystem entity.\n\n=head2 method r\n\n    method r(IO::Path:D: --> Bool:D)\n\nReturns C<True> if the invocant is a path that exists and is accessible.\nThe method will L«C<fail>|/routine/fail» with L<C<X::IO::DoesNotExist>|/type/X::IO::DoesNotExist> if the\npath points to a non-existent filesystem entity.\n\n=head2 method w\n\n    method w(IO::Path:D: --> Bool:D)\n\nReturns C<True> if the invocant is a path that exists and is writable.\nThe method will L«C<fail>|/routine/fail» with L<C<X::IO::DoesNotExist>|/type/X::IO::DoesNotExist> if the\npath points to a non-existent filesystem entity.\n\n=head2 method rw\n\n    method rw(IO::Path:D: --> Bool:D)\n\nReturns C<True> if the invocant is a path that exists and is readable and\nwritable. The method will L«C<fail>|/routine/fail» with L<C<X::IO::DoesNotExist>|/type/X::IO::DoesNotExist>\nif the path points to a non-existent filesystem entity.\n\n=head2 method x\n\n    method x(IO::Path:D: --> Bool:D)\n\nReturns C<True> if the invocant is a path that exists and is executable.\nThe method will L«C<fail>|/routine/fail» with L<C<X::IO::DoesNotExist>|/type/X::IO::DoesNotExist> if the\npath points to a non-existent filesystem entity.\n\nB<NOTE:> If the file is a script (an executable text file and not a native executable),\nand the file has I<only> executable permissions and I<no> read permissions,\nthis method will return C<True> but trying to execute will fail. That is a\nlimitation of the operating system.\n\n=head2 method rwx\n\n    method rwx(IO::Path:D: --> Bool:D)\n\nReturns C<True> if the invocant is a path that exists and is executable,\nreadable, and writable. The method will L«C<fail>|/routine/fail» with\nL<C<X::IO::DoesNotExist>|/type/X::IO::DoesNotExist> if the path points to a non-existent filesystem entity.\n\n=head2 method z\n\n    method z(IO::Path:D: --> Bool:D)\n\nReturns C<True> if the invocant is a path that exists and has size of C<0>. May\nbe called on paths that are directories, in which case the reported file size\n(and thus the result of this method) is dependent on the operating system. The\nmethod will L«C<fail>|/routine/fail» with L<C<X::IO::DoesNotExist>|/type/X::IO::DoesNotExist> if the path\npoints to a non-existent filesystem entity.\n\n=head2 method sibling\n\n    method sibling(IO::Path:D: Str() $sibling --> IO::Path:D)\n\nAllows to reference a sibling file or directory. Returns a new\nC<IO::Path> based on the invocant, with the\nL«C<.basename>|/type/IO::Path#method_basename» changed to C<$sibling>. The\nC<$sibling> is allowed to be a multi-part path fragment; see also\nL«C<.add>|/type/IO::Path#method_add».\n\n    say '.bashrc'.IO.sibling: '.bash_aliases'; # OUTPUT: «.bash_aliases\".IO␤»\n    say '/home/camelia/.bashrc'.IO.sibling: '.bash_aliases';\n    # OUTPUT: «/home/camelia/.bash_aliases\".IO␤»\n\n    say '/foo/' .IO.sibling: 'bar';  # OUTPUT: «/bar\".IO␤»\n    say '/foo/.'.IO.sibling: 'bar';  # OUTPUT: «/foo/bar\".IO␤»\n\n=head2 method words\n\n    method words(IO::Path:D: :$chomp = True, :$enc = 'utf8', :$nl-in = [\"\\x0A\", \"\\r\\n\"], |c --> Seq:D)\n\nOpens the invocant and returns its L«words|/type/IO::Handle#routine_words».\n\nThe behavior is equivalent to L<opening|/routine/open> the file specified by\nthe invocant, forwarding the C<:$chomp>, C<:$enc>, and C<:$nl-in> arguments to\nL«C<IO::Handle.open>|/type/IO::Handle#method_open», then calling\nL«C<IO::Handle.words>|/type/IO::Handle#routine_words» on that handle, forwarding\nany of the remaining arguments to that method, and returning the resultant\nL<C<Seq>|/type/Seq>.\n\nB<NOTE:> words are lazily read. The handle used under the hood is not closed\nuntil the returned L<C<Seq>|/type/Seq> is\nL<fully reified|/language/glossary#Reify>, and this could lead to\nleaking open filehandles. It is possible to avoid leaking open filehandles using\nthe L«C<$limit> argument|/type/IO::Handle#routine_words» to cut down the L<C<Seq>|/type/Seq>\nof words to be generated.\n\n=for code\nmy %dict := bag 'my-file.txt'.IO.words;\nsay \"Most common words: \", %dict.sort(-*.value).head: 5;\n\n=head2 method lines\n\n    method lines(IO::Path:D: :$chomp = True, :$enc = 'utf8', :$nl-in = [\"\\x0A\", \"\\r\\n\"], |c --> Seq:D)\n\nOpens the invocant and returns its L«lines|/type/IO::Handle#routine_lines».\n\nThe behavior is equivalent to L<opening|/routine/open> the file specified by\nthe invocant, forwarding the C<:$chomp>, C<:$enc>, and C<:$nl-in> arguments to\nL«C<IO::Handle.open>|/type/IO::Handle#method_open», then calling\nL«C<IO::Handle.lines>|/type/IO::Handle#routine_lines» on that handle, forwarding\nany of the remaining arguments to that method, and returning the resultant\nL<C<Seq>|/type/Seq>.\n\nB<NOTE:> the lines are ready lazily and the handle used under the hood won't\nget closed until the returned L<C<Seq>|/type/Seq> is\nL<fully reified|/language/glossary#Reify>, so ensure it is,\nor you'll be leaking open filehandles. (TIP: use the\nL«C<$limit> argument|/type/IO::Handle#routine_lines»)\n\n=begin code\nsay \"The file contains \",\n  '50GB-file'.IO.lines.grep(*.contains: 'Raku').elems,\n  \" lines that mention Raku\";\n# OUTPUT: «The file contains 72 lines that mention Raku␤»\n=end code\n\n=head2 routine slurp\n\n    multi method slurp(IO::Path:D: :$bin, :$enc)\n\nRead all of the file's content and return it as either L<C<Buf>|/type/Buf>, if\nC<:$bin> is C<True>, or if not, as L<C<Str>|/type/Str> decoded with C<:$enc>\nencoding, which defaults to C<utf8>. File will be closed afterwards. See\nL«C<&open>|/routine/open» for valid values for C<:$enc>.\n\n=head2 method spurt\n\n    method spurt(IO::Path:D: $data, :$enc, :$append, :$createonly)\n\nOpens the path for writing, and writes all of the C<$data> into it. File\nwill be closed afterwards. Will L«C<fail>|/routine/fail» if it cannot succeed\nfor any reason. The C<$data> can be any L«C<Cool>|/type/Cool» type or any\nL«C<Blob>|/type/Blob» type. Arguments are as follows:\n\n=item C<:$enc> — character encoding of the data. Takes same values as C<:$enc>\nin L«C<IO::Handle.open>|/routine/open». Defaults to C<utf8>. Ignored if C<$data>\nis a L«C<Blob>|/type/Blob».\n\n=item C<:$append> — open the file in C<append> mode, preserving existing\ncontents, and appending data to the end of the file.\n\n=item C<:$createonly> — L«C<fail>|/routine/fail» if the file already exists.\n\n    method spurt(IO::Path:D:)\n\nAs of the 2020.12 release of the Rakudo compiler, it is also possible to\ncall the C<spurt> method without any data.  This will either create an\nempty file, or will truncate any existing file at the given path.\n\n=head2 method chdir\n\n    multi method chdir(IO::Path:D: IO $path, |c)\n    multi method chdir(IO::Path:D: Str() $path, :$d = True, :$r, :$w, :$x)\n\nContrary to the name, the C<.chdir> method does not change any directories,\nbut merely concatenates the given C<$path> to the invocant and returns the\nresultant C<IO::Path>. Optional file tests can be performed by providing\nC<:d>, C<:r>, C<:w>, or C<:x> L«C<Bool>|/type/Bool» named arguments; when\nset to C<True>, they'll perform L«C<.d>|/routine/d», L«C<.r>|/routine/r»,\nL«C<.w>|/routine/w», and L«C<.x>|/routine/x» tests respectively. By default,\nonly C<:d> is set to C<True>.\n\n=head2 method mkdir\n\n    method mkdir(IO::Path:D: Int() $mode = 0o777 --> IO::Path:D)\n\nCreates a new directory, including its parent directories, as needed (similar to *nix utility C<mkdir> with C<-p> option).\nThat is, C<mkdir \"foo/bar/ber/meow\"> will create C<foo>, C<foo/bar>, and C<foo/bar/ber>\ndirectories as well if they do not exist.\n\nReturns the C<IO::Path> object pointing to\nthe newly created directory on success;\nL<fails|/routine/fail> with L<C<X::IO::Mkdir>|/type/X::IO::Mkdir> if directory cannot be created.\n\nSee also L«C<mode>|/routine/mode» for explanation and\nvalid values for C<$mode>.\n\n=head2 routine rmdir\n\n    sub    rmdir(*@dirs --> List:D)\n    method rmdir(IO::Path:D: --> True)\n\nRemove the invocant, or in sub form, all of the provided directories in the\ngiven list, which can contain any L<C<Cool>|/type/Cool> object. Only works on empty\ndirectories.\n\nMethod form returns C<True> on success and returns a L<C<Failure>|/type/Failure>\nof type L<C<X::IO::Rmdir>|/type/X::IO::Rmdir> if the directory cannot be removed (e.g.\nthe directory is not empty, or the path is not a directory). Subroutine\nform returns a list of directories that were successfully deleted.\n\nTo delete non-empty directory, see L«rmtree in C<File::Directory::Tree> module|https://github.com/labster/p6-file-directory-tree».\n\n=head2 method chmod\n\n    method chmod(IO::Path:D: Int() $mode --> Bool)\n\nChanges the POSIX permissions of a file or directory to C<$mode>.\nReturns C<True> on success; on failure,\nL<fails|/routine/fail> with L<C<X::IO::Chmod>|/type/X::IO::Chmod>.\n\nThe mode is expected as an integer following the L<standard numeric notation|https://en.wikipedia.org/wiki/File_system_permissions#Numeric_notation>, and is\nbest written as an octal number:\n\n=for code\n'myfile'.IO.chmod(0o444);          # make a file read-only\n'somedir'.IO.chmod(0o777);         # set 0777 permissions on a directory\n\nMake sure you I<don't> accidentally pass the intended octal digits as a decimal\nnumber (or string containing a decimal number):\n\n=for code\n'myfile'.IO.chmod:  '0444';        # BAD!!! (interpreted as mode 0o674)\n'myfile'.IO.chmod: '0o444';        # OK (an octal in a string)\n'myfile'.IO.chmod:  0o444;         # Also OK (an octal literal)\n\n=head2 routine rename\n\n    method rename(IO::Path:D: IO() $to, :$createonly = False --> Bool:D)\n    sub    rename(IO() $from, IO() $to, :$createonly = False --> Bool:D)\n\nRenames a file or directory. Returns C<True> on success; L<fails|/routine/fail>\nwith L<C<X::IO::Rename>|/type/X::IO::Rename> if C<:$createonly> is C<True> and the C<$to> path already\nexists or if the operation failed for some other reason.\n\nB<Note:> some renames will always fail, such as when the new name is on a\ndifferent storage device. See also: L«C<move>|/routine/move».\n\n=head2 routine copy\n\n    method copy(IO::Path:D: IO() $to, :$createonly --> Bool:D)\n    sub    copy(IO() $from, IO() $to, :$createonly --> Bool:D)\n\nCopies a file. Returns C<True> on success; L<fails|/routine/fail>\nwith L<C<X::IO::Copy>|/type/X::IO::Copy> if C<:$createonly> is C<True> and the C<$to> path already\nexists or if the operation failed for some other reason, such as when\nC<$to> and C<$from> are the same file.\n\n=head2 routine move\n\n    method move(IO::Path:D: IO() $to, :$createonly --> Bool:D)\n    sub    move(IO() $from, IO() $to, :$createonly --> Bool:D)\n\nCopies a file and then removes the original. If removal fails, it's possible\nto end up with two copies of the file. Returns C<True> on success;\nL<fails|/routine/fail> with L<C<X::IO::Move>|/type/X::IO::Move> if C<:$createonly> is C<True> and\nthe C<$to> path already exists or if the operation failed for some other reason,\nsuch as when C<$to> and C<$from> are the same file.\n\nTo avoid copying, you can use L«C<rename>|/routine/rename», if the files are on\nthe same storage device. It also works with directories, while C<move> does not.\n\n=head2 method Numeric\n\n    method Numeric(IO::Path:D: --> Numeric:D)\n\nCoerces L«C<.basename>|/routine/basename» to L<C<Numeric>|/type/Numeric>. L<Fails|/routine/fail>\nwith L<C<X::Str::Numeric>|/type/X::Str::Numeric> if base name is not numerical.\n\n=head2 method Int\n\n    method Int(IO::Path:D: --> Int:D)\n\nCoerces L«C<.basename>|/routine/basename» to L<C<Int>|/type/Int>. L<Fails|/routine/fail>\nwith L<C<X::Str::Numeric>|/type/X::Str::Numeric> if base name is not numerical.\n\n=head2 routine symlink\n\n    method symlink(IO::Path:D $target: IO() $link, Bool :$absolute = True --> Bool:D)\n    sub    symlink(      IO() $target, IO() $link, Bool :$absolute = True --> Bool:D)\n\nCreate a new I<symbolic> link C<$link> to existing C<$target>.\nReturns C<True> on success; L<fails|/routine/fail> with\nL<C<X::IO::Symlink>|/type/X::IO::Symlink> if the symbolic link could not be created. If C<$target>\ndoes not exist, creates a dangling symbolic link.\n\nC<symlink> creates a symbolic link using an absolute path\nby default. To create a relative symlink set the C<absolute>\nparameter to C<False> e.g. C<:!absolute>. This flag was\nintroduced in Rakudo release 2020.11.\n\nTo create a hard link, see L«C<link>|/routine/link».\n\nB<Note:> on Windows, creation of symbolic links may require escalated\nprivileges.\n\n=head2 routine link\n\n    method link(IO::Path:D $target: IO() $link --> Bool:D)\n    sub    link(      IO() $target, IO() $link --> Bool:D)\n\nCreate a new I<hard> link C<$link> to existing C<$target>.\nReturns C<True> on success; L<fails|/routine/fail> with\nL<C<X::IO::Link>|/type/X::IO::Link> if the hard link could not be created.\nTo create a symbolic link, see L«C<symlink>|/routine/symlink».\n\n=head2 routine unlink\n\n    method unlink(IO::Path:D: --> True)\n    sub    unlink(*@filenames --> List:D)\n\nDelete all specified ordinary files, links, or symbolic links for which there\nare privileges to do so. See L<rmdir|/routine/rmdir> to delete directories.\n\nThe subroutine form returns the names of all the files in the list, excluding\nthose for which the filesystem raised some error; since trying to delete a file\nthat does not exist does not raise any error at that level, this list will\ninclude the names of the files in the list that do not exist.\n\nThe method form returns C<True> on success, or L<fails|/routine/fail>\nwith L<C<X::IO::Unlink>|/type/X::IO::Unlink> if the operation could not be completed. If the file to be\ndeleted does not exist, the routine treats it as success.\n\n=begin code\n'foo.txt'.IO.open(:w).close;\n'bar'.IO.mkdir;\nsay unlink <foo.txt  bar  not-there.txt>; # OUTPUT: «[foo.txt not-there.txt]␤»\n# `bar` is not in output because it failed to delete (it's a directory)\n# `not-there.txt` is present. It never existed, so that's deemed a success.\n\n# Method form `fail`s:\nsay .exception.message without 'bar'.IO.unlink;\n# OUTPUT: «Failed to remove the file […] illegal operation on a directory␤»\n=end code\n\n=head2 routine chown\n\n    method chown(IO::Path:D: :$uid, :$gid --> True)\n    sub    chown(*@filenames, :$uid, :$gid --> List:D)\n\nAvailable as of release 2022.12 of the Rakudo compiler.\n\nChange the owner and/or group of all specified ordinary files, links, or\nsymbolic links for which there are privileges to do so.\n\nThe subroutine form returns the names of all the files in the list, excluding\nthose for which the filesystem raised some error.\n\nThe method form returns C<True> on success, or L<fails|/routine/fail>\nwith L<C<X::IO::Chown>|/type/X::IO::Chown> if the operation could not be completed.\n\nNote that this operation only makes sense on operating systems with\nthe concept of an \"owner\" and a \"group\", which is typically on Unix-like\nsystems.\n\n=for code\nsay \"success\" if 'foo.txt'.IO.chown(:uid(137));\n\n=head2 method IO\n\n    method IO(IO::Path:D: --> IO::Path)\n\nReturns the invocant.\n\n=head2 method SPEC\n\n    method SPEC(IO::Path:D: --> IO::Spec)\n\nReturns the L<C<IO::Spec>|/type/IO::Spec> object that was (implicitly) specified at\nobject creation time.\n\n    my $io = IO::Path.new(\"/bin/bash\");\n    say $io.SPEC;                            # OUTPUT: «(Unix)␤»\n    say $io.SPEC.dir-sep;                    # OUTPUT: «/␤»\n\n=head1 File timestamp retrieval\n\nThere are also 3 methods for fetching the 3 timestamps of a file (inode),\non Operating Systems where these are available:\n\n=head2 method created\n\nReturns an L«C<Instant>|/type/Instant» object indicating when the file was\ncreated.\n\n=for code\nsay \"path/to/file\".IO.created;          # Instant:1424089165\nsay \"path/to/file\".IO.created.DateTime; # 2015-02-16T12:18:50Z\n\nAvailable as of the 2022.12 release of the Rakudo compiler.\n\n=head2 method modified\n\nReturns an L«C<Instant>|/type/Instant» object indicating when the content\nof the file was last modified. Compare with L<changed|/routine/changed>.\n\n=for code\nsay \"path/to/file\".IO.modified;          # Instant:1424089165\nsay \"path/to/file\".IO.modified.DateTime; # 2015-02-16T12:18:50Z\n\n=head2 method accessed\n\nReturn an L<C<Instant>|/type/Instant> object representing the timestamp when the file was\nlast accessed. B<Note:> depending on how the filesystem was mounted, the\nlast accessed time may not update on I<each access> to the file, but only\non the first access after modifications.\n\n=for code\nsay \"path/to/file\".IO.accessed;          # Instant:1424353577\nsay \"path/to/file\".IO.accessed.DateTime; # 2015-02-19T13:45:42Z\n\n=head2 method changed\n\nReturns an L«C<Instant>|/type/Instant» object indicating the metadata of\nthe file or directory was last changed (e.g. permissions, or files\ncreated/deleted in directory). Compare with L<modified|/routine/modified>.\n\n=for code\nsay \"path/to/file\".IO.changed;           # Instant:1424089165\nsay \"path/to/file\".IO.changed.DateTime;  # 2015-02-16T12:18:50Z\n\n=head1 File permissions retrieval\n\n=head2 method mode\n\nReturn an L<C<IntStr>|/type/IntStr> object representing the POSIX permissions of a file.  The\nL<C<Str>|/type/Str> part of the result is the octal representation of the file permission,\nlike the form accepted by the C<chmod(1)> utility.\n\n=for code\nsay ~\"path/to/file\".IO.mode;  # e.g. '0644'\nsay +\"path/to/file\".IO.mode;  # e.g. 420, where sprintf('%04o', 420) eq '0644'\n\nThe result of this can be used in the other methods that take a mode as an\nargument.\n\n=for code\n\"path/to/file1\".IO.chmod(\"path/to/file2\".IO.mode);  # will change the\n                                                    # permissions of file1\n                                                    # to be the same as file2\n\n=head1 Other informational methods\n\n=head2 method user\n\nAvailable as of the 2021.04 Rakudo compiler release.\n\nThe C<user> method returns the numeric user ID (aka \"uid\") of the path on\noperating systems that support such a notion.\n\n=head2 method group\n\nAvailable as of the 2021.04 Rakudo compiler release.\n\nThe C<group> method returns the numeric group ID (aka \"gid\") of the path\non operating systems that support such a notion.\n\n=head2 method dir-with-entries\n\nAvailable as of the 2022.04 Rakudo compiler release.\n\nReturns a L<C<Bool>|/type/Bool> indicating whether the path is a directory with B<any> entries\nin it.  Throws an exception if the path is not a directory, or the path doesn't\nexist.\n\n=for code\nsay \"'$_' has entries\" if .d && .dir-with-entries given \"path/to/dir\".IO;\n\n=head2 method inode\n\nAvailable as of the 2022.07 Rakudo compiler release.\n\nReturns an L<C<Int>|/type/Int> object representing the inode of the path on the filesystem\n(if the filesystem supports such a notion).\n\n=for code\nsay \"path/to/file\".IO.inode;  # e.g. 9003678\n\n=head2 method dev\n\nAvailable as of the 2022.07 Rakudo compiler release.\n\nReturns an L<C<Int>|/type/Int> object representing the C<dev> (the C<st_dev> field of\nthe POSIX C<stat> function) of the path on the filesystem (if the\nfilesystem supports such a notion).\n\n=for code\nsay \"path/to/file\".IO.dev;  # e.g. 16777233\n\n=head2 method devtype\n\nAvailable as of the 2022.07 Rakudo compiler release.\n\nReturns an L<C<Int>|/type/Int> object representing the C<devtype> (the C<st_rdev>\nfield of the POSIX C<stat> function) of the path on the filesystem (if\nthe filesystem supports such a notion).\n\n=for code\nsay \"path/to/file\".IO.devtype;  # e.g. 0\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Pipe.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::Pipe\n\n=SUBTITLE Buffered inter-process string or binary stream\n\n    class IO::Pipe is IO::Handle {}\n\nAn C<IO::Pipe> object closely corresponds to a UNIX pipe. It has one end where\nit consumes string or binary data, and another where it reproduces the same\ndata. It is buffered, so that a write without a read doesn't immediately\nblock.\n\nPipes can be easily constructed with L<sub run and Proc::Async.new|/type/Proc::Async>.\n\n=head1 Methods\n\n=head2 method close\n\n    method close(IO::Pipe: --> Proc:D)\n\nCloses the pipe and returns L<C<Proc>|/type/Proc> object from which the pipe originates.\n\n=head2 method IO\n\n    method IO(IO::Pipe: --> IO::Path:U)\n\nReturns an L<C<IO::Path>|/type/IO::Path> type object.\n\n=head2 method path\n\n    method path(IO::Pipe: --> IO::Path:U)\n\nReturns an L<C<IO::Path>|/type/IO::Path> type object.\n\n=head2 method proc\n\n    method proc(IO::Pipe: --> Proc:D)\n\nReturns the L<C<Proc>|/type/Proc> object from which the pipe originates.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Socket/Async/ListenSocket.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::Socket::Async::ListenSocket\n\n=SUBTITLE A tap for listening TCP sockets\n\n    class IO::Socket::Async::ListenSocket is Tap {}\n\nC<IO::Socket::Async::ListenSocket> represents a listening TCP socket.\nInstances of this are returned by the L<tap|/type/Supply#method_tap>\nmethod of the supply returned by\nL<IO::Socket::Async.listen|/type/IO::Socket::Async#method_listen>:\n\n=begin code\nmy IO::Socket::Async::ListenSocket:D $server =\n    IO::Socket::Async.listen('127.0.0.1', 0).tap(-> $peer {\n        await $peer.print: \"Hello. Goodbye!\\r\\n\";\n        $peer.close;\n    });\n\nmy (Str:D $host, Int:D $port) = await $server.socket-host, $server.socket-port;\nsay \"The rude service is listening on $host:$port for the next 10 seconds...\";\nawait Promise.in(10).then({ $server.close });\nsay \"I'm done now.\";\n=end code\n\nAlternatively, by using the C<do> prefix with C<whenever>, you can also\nuse it from within a C<react> block:\n\n=for code\nreact {\n    my IO::Socket::Async::ListenSocket:D $server =\n        do whenever IO::Socket::Async.listen('127.0.0.1', 0) -> IO::Socket::Async:D $connection {\n            await $connection.print: \"Hello. Goodbye!\\r\\n\";\n            $connection.close;\n            QUIT { $server.close; .rethrow }\n        };\n    # Use $server here somehow.\n}\n\n=head1 Methods\n\n=head2 method socket-host\n\n    method socket-host(--> Promise)\n\nReturns a L<C<Promise>|/type/Promise> that will be kept with a L<C<Str>|/type/Str>\ncontaining the address of the listening socket.\n\n=head2 method socket-port\n\n    method socket-port(--> Promise)\n\nReturns a L<C<Promise>|/type/Promise> that will be kept with an L<C<Int>|/type/Int>\ncontaining the port of the listening socket.\n\n=head2 method native-descriptor\n\n    method native-descriptor(--> Int)\n\nReturns the corresponding file descriptor (C<SOCKET> on Windows) for the\nlistening socket.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Socket/Async.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::Socket::Async\n\n=SUBTITLE Asynchronous socket in TCP or UDP\n\n    class IO::Socket::Async {}\n\nC<IO::Socket::Async> provides asynchronous sockets, for both the\nserver and the client side.\n\nHere is a simple example of a simple \"hello world\" HTTP server that\nlistens on port 3333:\n\n=begin code\nreact {\n    whenever IO::Socket::Async.listen('0.0.0.0', 3333) -> $conn {\n        await $conn.print: qq:heredoc/END/;\n            HTTP/1.1 200 OK\n            Content-Type: text/html; charset=UTF-8\n            Content-Encoding: UTF-8\n\n            <html>\n            <body>\n                <h1>Incoming request:</h1>\n            <pre>\n            END\n        whenever $conn.Supply.lines -> $line {\n            $conn.say: $line;\n            if $line ~~ \"\" {\n                await $conn.print: \"</pre></body></html>\";\n                $conn.close;\n            }\n            LAST { say \"closed connection\"; }\n        }\n    }\n    CATCH {\n        default {\n            say .^name, ': ', .Str;\n            say \"handled in $?LINE\";\n        }\n    }\n}\n=end code\n\nAnd a client that connects to it, and prints out what the server answers:\n\n=begin code\nawait IO::Socket::Async.connect('127.0.0.1', 3333).then( -> $promise {\n    given $promise.result {\n        .print(\"Lorem ipsum dolor sit amet, consectetur adipiscing elit.\\n\");\n        react {\n            whenever .Supply() -> $v {\n                $v.print;\n                done;\n            }\n        }\n        .close;\n    }\n});\n=end code\n\nC<IO::Socket::Async> can also send and receive\nL<UDP|https://en.wikipedia.org/wiki/User_Datagram_Protocol> messages\nAn example server that outputs all the data it receives would be:\n\n=begin code\nmy $socket = IO::Socket::Async.bind-udp('localhost', 3333);\n\nreact {\n    whenever $socket.Supply -> $v {\n        if $v.chars > 0 {\n            say $v;\n        }\n    }\n}\n=end code\n\nAnd an associated client might be:\n\n=begin code\nmy $socket = IO::Socket::Async.udp();\nawait $socket.print-to('localhost', 3333, \"Hello, Raku!\");\n=end code\n\nThe L<C<CATCH> phaser|/language/phasers#CATCH> can be included to deal\nspecifically with problems that might occur in this kind of sockets, such as a\nport being already taken:\n\n=begin code\nreact {\n    whenever IO::Socket::Async.listen('0.0.0.0', 3000) -> $conn {\n        whenever $conn.Supply.lines -> $line {\n            $conn.print: qq:heredoc/END/;\n                HTTP/1.1 200 OK\n                Content-Type: text/html; charset=UTF-8\n                Content-Encoding: UTF-8\n\n                <html>\n                <body>\n                    <h1>Hello World!</h1>\n                    <p>{ $line }</p>\n                </body>\n                </html>\n                END\n            $conn.close;\n        }\n        QUIT {\n            default {\n                say .^name, '→ ', .Str;\n                say \"handled in line $?LINE\";\n            }\n        }\n    }\n\n}\n# Will print this, if address 3000 is already in use:\n# X::AdHoc→ address already in use\n# handled in 23\n=end code\n\nMain difference with using other phasers such as C<CATCH> is that this kind of\nexception will be caught within the C<whenever> block and will put exiting the\nprogram, or not, under your control.\n\n=head1 Methods\n\nThe C<IO::Socket::Async> cannot be constructed directly, either\nC<connect> or C<listen> (for TCP connections) or C<udp> or C<bind-udp>\n(for UDP data) should be used to create a client or a server\nrespectively.\n\n=head2 method connect\n\n    method connect(Str $host, Int $port --> Promise)\n\nAttempts to connect to the TCP server specified by C<$host> and\nC<$port>, returning a L<C<Promise>|/type/Promise> that will either be kept with a\nconnected C<IO::Socket::Async> or broken if the connection cannot be\nmade.\n\n=head2 method connect-path\n\n    method connect-path(Str $path --> Promise)\n\nAttempts to connect to a unix domain stream socket specified by C<$path>,\nreturning a L<C<Promise>|/type/Promise> that will either be kept with a\nconnected C<IO::Socket::Async> or broken if the connection cannot be\nmade.\n\n=head2 method listen\n\n    method listen(Str $host, Int $port --> Supply)\n\nCreates a listening socket on the specified C<$host> and C<$port>,\nreturning a L<C<Supply>|/type/Supply> to which the accepted client\nC<IO::Socket::Async>s will be emitted. This\nL<C<Supply>|/type/Supply> should be tapped start listening for client\nconnections.  You can set C<$port> to C<0> if you want the operating\nsystem to find one for you.\n\nThe L<C<IO::Socket::Async::ListenSocket>|/type/IO::Socket::Async::ListenSocket>\nreturned by calling the L<tap|/type/Supply#method_tap> method on the supply\nreturned represents the underlying listening TCP socket, which can be closed\nusing its L<close|/type/Tap#method_close> method. If C<$port> was set to C<0>,\nyou can get the port the socket ended up with using its\nL<socket-port|/type/IO::Socket::Async::ListenSocket#method_socket-port> method.\n\n=head2 method listen-path\n\n    method listen-path(Str $path)\n\nCreates a unix domain stream listening socket on the specified C<$path>,\nreturning a L<C<Supply>|/type/Supply> to which the accepted client\nC<IO::Socket::Async>s will be emitted. This\nL<C<Supply>|/type/Supply> should be tapped start listening for client\nconnections.\n\nThe L<C<IO::Socket::Async::ListenSocket>|/type/IO::Socket::Async::ListenSocket>\nreturned by calling the L<tap|/type/Supply#method_tap> method on the supply\nreturned represents the underlying listening TCP socket, which can be closed\nusing its L<close|/type/Tap#method_close> method.\n\n=head2 method udp\n\n    method udp(IO::Socket::Async:U: :$broadcast --> IO::Socket::Async)\n\nReturns an initialized C<IO::Socket::Async> client object that is\nconfigured to send UDP messages using C<print-to> or C<write-to>.  The\nC<:broadcast> adverb will set the C<SO_BROADCAST> option which will\nallow the socket to send packets to a broadcast address.\n\n=head2 method bind-udp\n\n    method bind-udp(IO::Socket::Async:U: Str() $host, Int() $port, :$broadcast --> IO::Socket::Async)\n\nThis returns an initialized C<IO::Socket::Async> server object that is\nconfigured to receive UDP messages sent to the specified C<$host> and\nC<$port> and is equivalent to C<listen> for a TCP socket.  The\nC<:broadcast> adverb can be specified to allow the receipt of messages\nsent to the broadcast address.\n\n=head2 method print\n\n    method print(IO::Socket::Async:D: Str $str --> Promise)\n\nAttempt to send C<$str> on the C<IO::Socket::Async> that will have been\nobtained indirectly via C<connect> or C<listen>, returning a L<C<Promise>|/type/Promise>\nthat will be kept with the number of bytes sent or broken if there was\nan error sending.\n\n=head2 method print-to\n\n    method print-to(IO::Socket::Async:D: Str() $host, Int() $port, Str() $str --> Promise)\n\nThis is the equivalent of C<print> for UDP sockets that have been\ncreated with the C<udp> method, it will try send a UDP message of\nC<$str> to the specified C<$host> and C<$port> returning a\nL<C<Promise>|/type/Promise> that will be kept when the data is successfully\nsent or broken if it was unable to send the data. In order to send to a\nbroadcast address the C<:broadcast> flag must have been specified when\nthe socket was created.\n\n=head2 method write\n\n    method write(IO::Socket::Async:D: Blob $b --> Promise)\n\nThis method will attempt to send the bytes in C<$b> on the\nC<IO::Socket::Async> that will have been obtained indirectly via\nC<connect> or C<listen>, returning a L<C<Promise>|/type/Promise> that will be kept with\nthe number of bytes sent or broken if there was an error sending.\n\n=head2 method write-to\n\n    method write-to(IO::Socket::Async:D: Str() $host, Int() $port, Blob $b --> Promise)\n\nThis is the equivalent of C<write> for UDP sockets that have been\ncreated with the C<udp> method. It will try send a UDP message comprised\nof the bytes in the L<C<Blob>|/type/Blob>  C<$b> to the specified C<$host>\nand C<$port> returning a L<C<Promise>|/type/Promise> that will be kept when\nthe data is successfully sent or broken if it was unable to send the\ndata. In order to send to a broadcast address the C<:broadcast> flag\nmust have been specified when the socket was created.\n\n=head2 method Supply\n\n    method Supply(:$bin, :$buf = buf8.new --> Supply)\n\nReturns a L<C<Supply>|/type/Supply> which can be tapped to obtain the data read from\nthe connected C<IO::Socket::Async> as it arrives.  By default the data\nwill be emitted as characters, but if the C<:bin> adverb is provided a\nL<C<Buf>|/type/Buf> of bytes will be emitted instead, optionally in this\ncase you can provide your own L<C<Buf>|/type/Buf> with the C<:buf> named parameter.\n\nA UDP socket in character mode will treat each packet as a complete\nmessage and decode it. In the event of a decoding error, the L<C<Supply>|/type/Supply>\nwill C<quit>.\n\nOn the other hand, a TCP socket treats the incoming packets as part of a\nstream, and feeds the incoming bytes into a streaming decoder. It then\nemits whatever characters the decoder considers ready. Since strings\nwork at grapheme level in Raku, this means that only known complete\ngraphemes will be emitted. For example, if the UTF-8 encoding were\nbeing used and the last byte in the packet decoded to C<a>, this would\nnot be emitted since the next packet may include a combining character\nthat should form a single grapheme together with the C<a>. Control\ncharacters (such as C<\\n>) always serve as grapheme boundaries, so any\ntext-based protocols that use newlines or null bytes as terminators\nwill not need special consideration. A TCP socket will also C<quit>\nupon a decoding error.\n\n=head2 method close\n\n    method close(IO::Socket::Async:D: )\n\nClose the connected client C<IO::Socket::Async> which will have been\nobtained from the C<listen> L<C<Supply>|/type/Supply> or the C<connect>\nL<C<Promise>|/type/Promise>.\n\nIn order to close the underlying listening socket created by C<listen> you can\nC<close> the\nL<C<IO::Socket::Async::ListenSocket>|/type/IO::Socket::Async::ListenSocket>. See\nL<listen|#method_listen> for examples.\n\n=head2 method socket-host\n\n    method socket-host(--> Str)\n\nReturns the IP address of the local end of this socket.\n\n=head2 method peer-host\n\n    method peer-host(--> Str)\n\nReturns the IP address of the remote end of this socket.\n\n=head2 method socket-port\n\n    method socket-port(--> Int)\n\nReturns the port of the local end of this socket.\n\n=head2 method peer-port\n\n    method peer-port(--> Int)\n\nReturns the port of the remote end of this socket.\n\n=head2 method native-descriptor\n\n    method native-descriptor(--> Int)\n\nReturns the file descriptor of this socket.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Socket/INET.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::Socket::INET\n\n=SUBTITLE TCP Socket\n\n=for code :preamble<role IO::Socket {}>\nclass IO::Socket::INET does IO::Socket {}\n\nC<IO::Socket::INET> provides TCP sockets, both the server and the client side.\n\nFor UDP support, please see L<C<IO::Socket::Async>|/type/IO::Socket::Async>.\n\nHere is an example of a very simplistic \"echo\" server that listens on\nC<localhost>, port C<3333>:\n\n=begin code\nmy $listen = IO::Socket::INET.new( :listen,\n                                   :localhost<localhost>,\n                                   :localport(3333) );\nloop {\n    my $conn = $listen.accept;\n    try {\n        while my $buf = $conn.recv(:bin) {\n            $conn.write: $buf;\n        }\n    }\n    $conn.close;\n\n    CATCH {\n          default { .payload.say;      }\n    }\n\n}\n=end code\n\nAnd a client that connects to it, and prints out what the server answers:\n\n=begin code\nmy $conn = IO::Socket::INET.new( :host<localhost>,\n                                 :port(3333) );\n$conn.print: 'Hello, Raku';\nsay $conn.recv;\n$conn.close;\n=end code\n\nPlease bear in mind that this is a synchronous connection; an attempt by any of the nodes to write without the other reading will produce the error C<Could not receive data from socket: Connection reset by peer>.\n\n=head1 Methods\n\n=head2 method new\n\n=for code\nmulti method new(\n        :$host,\n        :$port,\n        :$family = PF_INET,\n        :$encoding = 'utf-8',\n        :$nl-in = \"\\r\\n\",\n    --> IO::Socket::INET:D)\nmulti method new(\n        :$localhost,\n        :$localport,\n        :$family = PF_INET,\n        :$listen,\n        :$encoding = 'utf-8',\n        :$nl-in = \"\\r\\n\",\n    --> IO::Socket::INET:D)\n\nCreates a new socket.\n\nIf C<:$listen> is True, creates a new socket that listen on C<:$localhost>\n(which can be an IP address or a domain name) on port C<:$localport>; in other words\nthe C<:$listen> flag determines the I<server mode> of the socket.\nOtherwise (i.e., C<:$listen> is C<False>), the new socket opens immediately\na connection to C<:$host> on port C<:$port>.\n\nC<:$family> defaults to C<PF_INET> constant for IPv4, and can be set\nto C<PF_INET6> constant for IPv6.\n\nFor text operations (such as L<method lines|#method lines> and L<method get|#method get>),\nC<:$encoding> specifies the encoding, and C<:$nl-in> determines\nthe character(s) that separate lines.\n\n=head1 Methods\n\n=head2 method get\n\n    method get()\n\nReads a line from the socket and returns it as of type L<C<Str>|/type/Str>.\nReturn L<C<Nil>|/type/Nil> on end-of-file (EOF).\n\n=head2 method lines\n\n    method lines()\n\nReturns a lazy list of lines read from the socket.\n\n=head2 method accept\n\n    method accept()\n\nIn listen/server mode, waits for a new incoming connection.\nOnce a new connection is established, an C<IO::Socket::INET>\ninstance (or a subclass instance) for consuming\nthe connection is returned.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Socket.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"domain-specific\")\n\n=TITLE role IO::Socket\n\n=SUBTITLE Network socket\n\n    role IO::Socket { ... }\n\nC<IO::Socket> contains read and write methods for sockets. It is usually used\nthrough L<C<IO::Socket::INET>|/type/IO::Socket::INET>.\n\n=head1 Methods\n\n=head2 method recv\n\n    method recv(IO::Socket:D: Cool $elems = Inf, :$bin)\n\nReceive a packet and return it, either as a L<C<Blob>|/type/Blob> if\nC<:bin> was passed, or a L<C<Str>|/type/Str> if not.\nReceives up to C<$elems> or C<65535> (whichever is smaller) bytes or characters.\n\nIf the socket has previously been read from in non-C<:bin> mode, it's not always\nsafe to read from it in C<:bin> mode again. Depending on the decoder it's\npossible for the C<:bin> read to skip over bytes that the decoder has read\nahead messing up the order of bytes and chars. This effect can occur with the\nUTF-8 decoder and if the previously decoded char could still receive combiners.\n\nIn Rakudo versions prior to 2024.07 mixing of binary and non-binary reads is\nunsupported.\n\nFails if the socket is not connected.\n\n=head2 method read\n\n    method read(IO::Socket:D: Int(Cool) $bytes)\n\nReads C<$bytes> bytes from the socket and returns them in a\nL<C<Blob>|/type/Blob>.\n\nThe same caveat of mixed binary and non-binary reads described in\nL<method recv|#method recv> applies.\n\nFails if the socket is not connected.\n\n=head2 routine get\n\n    method get(IO::Socket:D: --> Str:D)\n\nReads a single line of input from the socket, removing the trailing newline\ncharacters (as set by L«C<.nl-in>|/routine/nl-in»). Returns L<C<Nil>|/type/Nil>, if no\nmore input is available.\n\nFails if the socket is not connected.\n\n=head2 method print\n\n    method print(IO::Socket:D: Str(Cool) $string)\n\nWrites the supplied string to the socket, thus sending it to other end of the\nconnection. The binary version is L<method write|#method write>.\n\nFails if the socket is not connected.\n\n=head2 method write\n\n    method write(IO::Socket:D: Blob:D $buf)\n\nWrites the supplied buffer to the socket, thus sending it to other end of the\nconnection. The string version is L<method print|#method print>.\n\nFails if the socket is not connected.\n\n=head2 method put\n\n    method put(IO::Socket:D: Str(Cool) $string)\n\nWrites the supplied string, with a C<\\n> appended to it,\nto the socket, thus sending it to other end of the connection.\n\nFails if the socket is not connected.\n\n=head2 method close\n\n    method close(IO::Socket:D)\n\nCloses the socket.\n\nFails if the socket is not connected.\n\n=head2 method native-descriptor\n\n    method native-descriptor()\n\nThis returns a value that the operating system would understand as a \"socket descriptor\" and\nis suitable for passing to a native function that requires a socket descriptor as an\nargument such as C<setsockopt>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Spec/Cygwin.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::Spec::Cygwin\n\n=SUBTITLE Platform specific operations on file and directory paths for Cygwin\n\n    class IO::Spec::Cygwin is IO::Spec::Unix { }\n\nAn object of this type is available via the variable C<$*SPEC> if the\nRaku interpreter is running on C<Cygwin>.\n\nAbout this class and its related classes also see\nL<C<IO::Spec>|/type/IO::Spec>.\n\n=head1 Methods\n\n=head2 method abs2rel\n\n    method abs2rel(IO::Path:D $path, IO::Path:D $base = $*CWD --> Str:D)\n\nReturns a string that represents C<$path>, but relative to C<$base> path.\nBoth C<$path> and C<$base> may be relative paths. C<$base> defaults to C<$*CWD>.\nUses L«C<IO::Spec::Win32>|/type/IO::Spec::Win32»'s semantics.\n\n=head2 method canonpath\n\n    method canonpath(Str() $path, :$parent --> Str:D)\n\nReturns a string that is a canonical representation of C<$path>. If C<:$parent>\nis set to true, will also clean up references to parent directories. B<NOTE:>\nthe routine does not access the filesystem.\n\n    IO::Spec::Cygwin.canonpath(｢C:\\foo\\\\..\\bar\\..\\ber｣).say;\n    # OUTPUT: «C:/foo/../bar/../ber␤»\n\n    IO::Spec::Cygwin.canonpath(\"foo///./../bar/../ber\").say;\n    # OUTPUT: «foo/../bar/../ber␤»\n\n    IO::Spec::Cygwin.canonpath(\"foo///./../bar/../ber\", :parent).say;\n    # OUTPUT: «ber␤»\n\n=head2 method catdir\n\n    method catdir (*@parts --> Str:D)\n\nConcatenates multiple path fragments and returns the canonical representation\nof the resultant path as a string. The C<@parts> are L«C<Str>|/type/Str» objects\nand are allowed to contain path separators.\n\n    IO::Spec::Cygwin.catdir(<foo/bar ber raku>).say;\n    # OUTPUT: «foo/bar/ber/raku␤»\n\n=head2 method catpath\n\n    method catpath (Str:D $volume, Str:D $dir, Str:D $file --> Str:D)\n\nSame as L«C<IO::Spec::Win32.catpath>|/type/IO::Spec::Win32#method_catpath»,\nexcept will also change all backslashes to slashes at the end:\n\n    IO::Spec::Cygwin.catpath('C:', '/some/dir', 'foo.txt').say;\n    # OUTPUT: «C:/some/dir/foo.txt␤»\n\n    IO::Spec::Cygwin.catpath('C:', '/some/dir', '').say;\n    # OUTPUT: «C:/some/dir␤»\n\n    IO::Spec::Cygwin.catpath('', '/some/dir', 'foo.txt').say;\n    # OUTPUT: «/some/dir/foo.txt␤»\n\n    IO::Spec::Cygwin.catpath('E:', '', 'foo.txt').say;\n    # OUTPUT: «E:foo.txt␤»\n\n=head2 method is-absolute\n\n    method is-absolute(Str:D $path --> Bool:D)\n\nReturns C<True> if the C<$path> starts with a slash (C<\"/\">) or backslash\n(C<\"\\\">), even if they have combining character on them, optionally preceded by\na volume:\n\n    say IO::Spec::Cygwin.is-absolute: \"/foo\";        # OUTPUT: «True␤»\n    say IO::Spec::Cygwin.is-absolute: \"/\\x[308]foo\"; # OUTPUT: «True␤»\n    say IO::Spec::Cygwin.is-absolute: ｢C:\\foo｣;      # OUTPUT: «True␤»\n    say IO::Spec::Cygwin.is-absolute: \"bar\";         # OUTPUT: «False␤»\n\n=head2 method join\n\n    method join(|c)\n\nSame as L«C<IO::Spec::Win32.join>|/type/IO::Spec::Win32#method_join», except\nreplaces backslashes with slashes in the final result.\n\n=head2 method rel2abs\n\n    method rel2abs(|c --> List:D)\n\nSame as L«C<IO::Spec::Win32.rel2abs>|/type/IO::Spec::Win32#method_rel2abs»,\nexcept replaces backslashes with slashes in the final result.\n\n=head2 method split\n\n    method split(IO::Spec::Cygwin: Cool:D $path)\n\nSame as L«C<IO::Spec::Win32.split>|/type/IO::Spec::Win32#method_split»,\nexcept it replaces backslashes with slashes in all the values of the\nfinal result.\n\n=head2 method splitpath\n\n    method splitpath(|c --> List:D)\n\nSame as L«C<IO::Spec::Win32.splitpath>|/type/IO::Spec::Win32#method_splitpath»,\nexcept replaces backslashes with slashes in all the values of the final result.\n\n=head2 method tmpdir\n\n    method tmpdir(--> IO::Path:D)\n\nAttempts to locate a system's temporary directory by checking several typical directories and environment variables. Uses current directory if no suitable directories are found.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Spec/QNX.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::Spec::QNX\n\n=SUBTITLE Platform specific operations on file and directory paths QNX\n\n    class IO::Spec::QNX is IO::Spec::Unix { }\n\nAn object of this type is available via the variable C<$*SPEC> if the\nRaku interpreter is running on a C<QNX> platform.\n\nAbout this class and its related classes also see\nL<C<IO::Spec>|/type/IO::Spec>.\n\n=head1 Methods\n\n=head2 method canonpath\n\n    method canonpath(Str() $path, :$parent --> Str:D)\n\nReturns a string that is a canonical representation of C<$path>. If C<:$parent>\nis set to true, will also clean up references to parent directories. B<NOTE:>\nthe routine does not access the filesystem, so no symlinks are followed.\n\n    IO::Spec::QNX.canonpath(\"foo//../bar/../ber\").say;\n    # OUTPUT: «foo/../bar/../ber␤»\n\n    IO::Spec::QNX.canonpath(\"foo///./../bar/../ber\").say;\n    # OUTPUT: «foo/../bar/../ber␤»\n\n    IO::Spec::QNX.canonpath(\"foo///./../bar/../ber\", :parent).say;\n    # OUTPUT: «ber␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Spec/Unix.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::Spec::Unix\n\n=SUBTITLE Platform specific operations on file and directory paths for POSIX\n\n    class IO::Spec::Unix is IO::Spec  { }\n\nAn object of this type is available via the variable C<$*SPEC> if the\nRaku interpreter is running on a Unix-like platform.\n\nAbout this class and its related classes also see\nL<C<IO::Spec>|/type/IO::Spec>.\n\n=head1 Methods\n\n=head2 method abs2rel\n\n    method abs2rel(IO::Path:D $path, IO::Path:D $base = $*CWD --> Str:D)\n\nReturns a string that represents C<$path>, but relative to C<$base>\npath. Both C<$path> and C<$base> may be relative paths. C<$base>\ndefaults to C<$*CWD>.\n\n=head2 method basename\n\n    method basename(Str:D $path --> Str:D)\n\nTakes a path as a string and returns a possibly-empty portion after the\nlast slash:\n\n    IO::Spec::Unix.basename(\"foo/bar/\") .raku.say; # OUTPUT: «\"\"␤»\n    IO::Spec::Unix.basename(\"foo/bar/.\").raku.say; # OUTPUT: «\".\"␤»\n    IO::Spec::Unix.basename(\"foo/bar\")  .raku.say; # OUTPUT: «\"bar\"␤»\n\n=head2 method canonpath\n\n    method canonpath(Str() $path, :$parent --> Str:D)\n\nReturns a string that is a canonical representation of C<$path>. If\nC<:$parent> is set to true, will also clean up references to parent\ndirectories. B<NOTE:> the routine does not access the filesystem, so no\nsymlinks are followed.\n\n    IO::Spec::Unix.canonpath(\"foo//../bar/../ber\").say;\n    # OUTPUT: «foo/../bar/../ber␤»\n\n    IO::Spec::Unix.canonpath(\"foo///./../bar/../ber\").say;\n    # OUTPUT: «foo/../bar/../ber␤»\n\n    IO::Spec::Unix.canonpath(\"foo///./../bar/../ber\", :parent).say;\n    # OUTPUT: «ber␤»\n\n=head2 method catdir\n\n    method catdir (*@parts --> Str:D)\n\nConcatenates multiple path fragments and returns the canonical\nrepresentation of the resultant path as a string. The C<@parts> are\nL«C<Str>|/type/Str» objects and are allowed to contain path separators.\n\n    IO::Spec::Unix.catdir(<foo/bar ber raku>).say; # OUTPUT: «foo/bar/ber/raku␤»\n\n=head2 method catfile\n\nAlias for L«C<catdir>|/routine/catdir».\n\n=head2 method catpath\n\n    method catpath ($, Str:D $part1, Str:D $part2 --> Str:D)\n\nTakes two path fragments and concatenates them, adding or removing a\npath separator, if necessary. The first argument is ignored (it exists\nto maintain consistent interface with other L«C<IO::Spec>|/type/IO::Spec» types for\nsystems that have volumes).\n\n    IO::Spec::Unix.catpath($, 'some/dir', 'and/more').say;\n    # OUTPUT: «some/dir/and/more␤»\n\n=head2 method curdir\n\n    method curdir()\n\nReturns a string representing the current directory:\n\n    say '.' eq $*SPEC.curdir; # OUTPUT: «True␤»\n\n=head2 method curupdir\n\n    method curupdir()\n\nReturns a L«C<Block>|/type/Block» taking an argument. This block\nreturns C<True> if its argument is neither the string representing the\ncurrent directory nor the string representing the directory one up from\nthe current one.  It returns C<False> otherwise.\nThis block is intended to be used with\nL<smartmatching|/language/operators#infix_~~>.\n\n=begin code\nsay $*SPEC.curupdir;\n# OUTPUT: «-> str $dir { #`(Block|65335808) ... }␤»\n\nmy @dirs = <. foo .. bar>;\nsay @dirs.grep: { $_ ~~ $*SPEC.curupdir };\n# OUTPUT: «(foo bar)␤»\n=end code\n\nNeither C<foo> nor C<bar> are equal to the representation of the current\nor parent directory, that is why they are returned by C<grep>.\n\nB<Note>: Before Rakudo release 2020.06 a L«C<none>|/routine/none»\nL<C<Junction>|/type/Junction> was returned instead of a L<C<Block>|/type/Block>.\n\n=head2 method devnull\n\n    method devnull(--> Str:D)\n\nReturns the string C<\"/dev/null\"> representing the\nL<\"Null device\"|https://en.wikipedia.org/wiki/Null_device>:\n\n=for code\n$*SPEC.devnull.IO.spurt: \"foo bar baz\";\n\n=head2 method dir-sep\n\n    method dir-sep(--> Str:D)\n\nReturns the string C<\"/\"> representing canonical directory separator\ncharacter.\n\n=for code\nIO::Spec::Unix.dir-sep.say; # OUTPUT: «/␤»\n\n=head2 method extension\n\nB<NOTE:> Most users would want to use the higher-level routine\nL«C<IO::Path.extension>|/type/IO::Path#method_extension» instead of this\nlower-level version.\n\n    method extension(Str:D $path --> Str:D)\n\nTakes a string representing a base name and returns the characters after\nthe last dot (C<\".\">), or empty string if no dots are present. The\nroutine makes no attempt to detect path separators and will return\neverything after the last dot.\n\n    $*SPEC.extension('foo.'      ).raku.say;  # OUTPUT: «\"\"␤»\n    $*SPEC.extension('foo.txt'   ).raku.say;  # OUTPUT: «\"txt\"␤»\n    $*SPEC.extension('foo.tar.gz').raku.say;  # OUTPUT: «\"gz\"␤»\n    $*SPEC.extension('foo'       ).raku.say;  # OUTPUT: «\"\"␤»\n    $*SPEC.extension('bar.foo/foo').raku.say; # OUTPUT: «\"foo/foo\"␤»\n\n=head2 method is-absolute\n\n    method is-absolute(Str:D $path --> Bool:D)\n\nReturns C<True> if the C<$path> starts with a slash (C<\"/\">), even if it\nhas combining character on it:\n\n    say IO::Spec::Unix.is-absolute: \"/foo\";        # OUTPUT: «True␤»\n    say IO::Spec::Unix.is-absolute: \"/\\x[308]foo\"; # OUTPUT: «True␤»\n    say IO::Spec::Unix.is-absolute: \"bar\";         # OUTPUT: «False␤»\n\n=head2 method join\n\n    method join ($, Str:D $dir, Str:D $file --> Str:D)\n\nSimilar to L«C<catpath>|/routine/catpath», takes two path fragments and\nconcatenates them, adding or removing a path separator, if necessary,\nexcept it will return just C<$file> if both C<$dir> and C<$file> are\nstring C<'/'> or if C<$dir> is the string C<'.'>. The first argument is\nignored (it exists to maintain consistent interface with other\nL<C<IO::Spec>|/type/IO::Spec> types for systems that have volumes).\n\n    IO::Spec::Unix.join($, 'foo', 'bar').say; # OUTPUT: «foo/bar␤»\n    IO::Spec::Unix.join($, '/', '/').say;     # OUTPUT: «/␤»\n    IO::Spec::Unix.join($, '.', 'foo').say;   # OUTPUT: «foo␤»\n    say $*SPEC.join(True,\".\",\"/foo\");         # OUTPUT: «/foo␤»\n\n=head2 method path\n\n    method path(--> Seq:D)\n\nSplits the value of C«%*ENV<PATH>» on colons (C<\":\">), replaces empty parts with\nC<\".\">, and returns a L<C<Seq>|/type/Seq> with each of the resultant parts. Returns\nan empty L<C<Seq>|/type/Seq> if C«%*ENV<PATH>» is not set or is an empty string.\n\n    %*ENV<PATH> = 'foo:bar/ber::foo:';\n    IO::Spec::Unix.path.raku.say;\n    # OUTPUT: «(\"foo\", \"bar/ber\", \".\", \"foo\", \".\").Seq␤»\n\n=head2 method rel2abs\n\n    method rel2abs(Str() $path, $base = $*CWD --> Str:D)\n\nReturns a string representing C<$path> converted to absolute path, based at\nC<$base>, which defaults to C<$*CWD>. If C<$base> is not an absolute path,\nit will be made absolute relative to C<$*CWD>, unless C<$*CWD> and C<$base>\nare the same.\n\n=begin code\nsay $*CWD;                                  # OUTPUT: «\"/home/camelia\".IO␤»\n\nsay IO::Spec::Unix.rel2abs: 'foo';          # OUTPUT: «/home/camelia/foo␤»\nsay IO::Spec::Unix.rel2abs: './';           # OUTPUT: «/home/camelia␤»\nsay IO::Spec::Unix.rel2abs: 'foo/../../';   # OUTPUT: «/home/camelia/foo/../..␤»\nsay IO::Spec::Unix.rel2abs: '/foo/';        # OUTPUT: «/foo␤»\n\nsay IO::Spec::Unix.rel2abs: 'foo', 'bar';   # OUTPUT: «/home/camelia/bar/foo␤»\nsay IO::Spec::Unix.rel2abs: './', '/bar';   # OUTPUT: «/bar␤»\nsay IO::Spec::Unix.rel2abs: '/foo/', 'bar'; # OUTPUT: «/foo␤»\n\nsay IO::Spec::Unix.rel2abs: 'foo/../../', 'bar';\n# OUTPUT: «/home/camelia/bar/foo/../..␤»\n=end code\n\n=head2 method rootdir\n\n    method rootdir(--> Str:D)\n\nReturns string C<'/'>, representing root directory.\n\n=head2 method split\n\n    method split(IO::Spec::Unix: Cool:D $path)\n\nCreates an L«C<IO::Path::Parts>|/type/IO::Path::Parts» for C<$path>,\nwith an empty string as its C<volume> attribute's value.\n\n=begin code\nIO::Spec::Unix.split('C:/foo/bar.txt').raku.say;\n# OUTPUT: «IO::Path::Parts.new(\"\",\"C:/foo\",\"bar.txt\")␤»\n\nIO::Spec::Unix.split('/foo/').raku.say;\n# OUTPUT: «IO::Path::Parts.new(\"\",\"/\",\"foo\")␤»\n\nIO::Spec::Unix.split('///').raku.say;\n# OUTPUT: «IO::Path::Parts.new(\"\",\"/\",\"/\")␤»\n\nIO::Spec::Unix.split('./').raku.say;\n# OUTPUT: «IO::Path::Parts.new(\"\",\".\",\".\")␤»\n\nIO::Spec::Unix.split('.').raku.say;\n# OUTPUT: «IO::Path::Parts.new(\"\",\".\",\".\")␤»\n\nIO::Spec::Unix.split('').raku.say;\n# OUTPUT: «IO::Path::Parts.new(\"\",\"\",\"\")␤»\n=end code\n\nB<Note>: Before Rakudo release 2020.06 this method split the given\nC<$path> into \"volume\", \"dirname\", and \"basename\" and returned the result\nas a L<C<List>|/type/List> of three L<C<Pair>|/type/Pair>s, in that order.\n\n=head2 method splitdir\n\n    method splitdir(Cool:D $path --> List:D)\n\nSplits the given C<$path> on slashes.\n\n=begin code\nIO::Spec::Unix.splitdir('C:\\foo/bar.txt').raku.say;\n# OUTPUT: «(\"C:\\\\foo\", \"bar.txt\")␤»\n\nIO::Spec::Unix.splitdir('/foo/').raku.say;\n# OUTPUT: «(\"\", \"foo\", \"\")␤»\n\nIO::Spec::Unix.splitdir('///').raku.say;\n# OUTPUT: «(\"\", \"\", \"\", \"\")␤»\n\nIO::Spec::Unix.splitdir('./').raku.say;\n# OUTPUT: «(\".\", \"\")␤»\n\nIO::Spec::Unix.splitdir('.').raku.say;\n# OUTPUT: «(\".\",)␤»\n\nIO::Spec::Unix.splitdir('').raku.say;\n# OUTPUT: «(\"\",)␤»\n=end code\n\n=head2 method splitpath\n\n    method splitpath(Cool:D $path, :$nofile --> List:D)\n\nSplits the given C<$path> into a list of 3 strings: volume,\ndirname, and file. The volume is always an empty string, returned for API\ncompatibility with other L<C<IO::Spec>|/type/IO::Spec> types. If C<:$nofile> named argument is\nset to C<True>, the content of the file string is undefined and should be\nignored; this is a means to get a performance boost, as implementations may use\nfaster code path when file is not needed.\n\n=begin code\nIO::Spec::Unix.splitpath('C:\\foo/bar.txt').raku.say;\n# OUTPUT: «(\"\", \"C:\\\\foo/\", \"bar.txt\")␤»\n\nIO::Spec::Unix.splitpath('C:\\foo/bar.txt', :nofile).raku.say;\n# OUTPUT: «(\"\", \"C:\\\\foo/bar.txt\", \"\")␤»\n\nIO::Spec::Unix.splitpath('/foo/').raku.say;\n# OUTPUT: «(\"\", \"/foo/\", \"\")␤»\n\nIO::Spec::Unix.splitpath('/foo/', :nofile).raku.say;\n# OUTPUT: «(\"\", \"/foo/\", \"\")␤»\n\nIO::Spec::Unix.splitpath('///').raku.say;\n# OUTPUT: «(\"\", \"///\", \"\")␤»\n\nIO::Spec::Unix.splitpath('./').raku.say;\n# OUTPUT: «(\"\", \"./\", \"\")␤»\n\nIO::Spec::Unix.splitpath('.').raku.say;\n# OUTPUT: «(\"\", \"\", \".\")␤»\n\nIO::Spec::Unix.splitpath('').raku.say;\n# OUTPUT: «(\"\", \"\", \"\")␤»\n=end code\n\n=head2 method tmpdir\n\n        method tmpdir(--> IO::Path:D)\n\nAttempts to locate a system's temporary directory by checking several typical directories and environment variables. Uses current directory if no suitable directories are found.\n\n=head2 method updir\n\n    method updir()\n\nReturns a string representing the directory one up from current:\n\n    say '..' eq $*SPEC.updir; # OUTPUT: «True␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Spec/Win32.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::Spec::Win32\n\n=SUBTITLE Platform specific operations on file and directory paths for Windows\n\n    class IO::Spec::Win32 is IO::Spec::Unix { }\n\nAn object of this type is available via the variable C<$*SPEC> if the\nRaku interpreter is running on a Windows-like platform.\n\nAbout this class and its related classes also see\nL<C<IO::Spec>|/type/IO::Spec>.\n\n=head1 Methods\n\n=head2 method basename\n\n    method basename(Str:D $path --> Str:D)\n\nTakes a path as a string and returns a possibly-empty portion after the\nlast slash or backslash:\n\n    IO::Spec::Win32.basename(\"foo/bar/\") .raku.say; # OUTPUT: «\"\"␤»\n    IO::Spec::Win32.basename(\"foo/bar\\\\\").raku.say; # OUTPUT: «\"\"␤»\n    IO::Spec::Win32.basename(\"foo/bar/.\").raku.say; # OUTPUT: «\".\"␤»\n    IO::Spec::Win32.basename(\"foo/bar\")  .raku.say; # OUTPUT: «\"bar\"␤»\n\n=head2 method canonpath\n\n    method canonpath(Str() $path, :$parent --> Str:D)\n\nReturns a string that is a canonical representation of C<$path>. If C<:$parent>\nis set to true, will also clean up references to parent directories. B<NOTE:>\nthe routine does not access the filesystem.\n\n    IO::Spec::Win32.canonpath(\"C:/foo//../bar/../ber\").say;\n    # OUTPUT: «C:\\foo\\..\\bar\\..\\ber␤»\n\n    IO::Spec::Win32.canonpath(\"C:/foo///./../bar/../ber\").say;\n    # OUTPUT: «C:\\foo\\..\\bar\\..\\ber␤»\n\n    IO::Spec::Win32.canonpath(\"C:/foo///./../bar/../ber\", :parent).say;\n    # OUTPUT: «C:\\ber␤»\n\n=head2 method catdir\n\n    method catdir (*@parts --> Str:D)\n\nConcatenates multiple path fragments and returns the canonical\nrepresentation of the resultant path as a string. The C<@parts> are\nL«C<Str>|/type/Str» objects and are allowed to contain path separators.\n\n    IO::Spec::Win32.catdir(<foo/bar ber raku>).say;\n    # OUTPUT: «foo\\bar\\ber\\raku␤»\n\n=head2 method catfile\n\nAlias for L«C<catdir>|/routine/catdir».\n\n=head2 method catpath\n\n    method catpath (Str:D $volume, Str:D $dir, Str:D $file --> Str:D)\n\nConcatenates a path from given volume, a chain of directories, and file.\nAn empty string can be given for any of the three arguments. No attempt\nto make the path canonical is made. Use\nL«C<canonpath>|/routine/canonpath» for that purpose.\n\n    IO::Spec::Win32.catpath('C:', '/some/dir', 'foo.txt').say;\n    # OUTPUT: «C:/some/dir\\foo.txt␤»\n\n    IO::Spec::Win32.catpath('C:', '/some/dir', '').say;\n    # OUTPUT: «C:/some/dir␤»\n\n    IO::Spec::Win32.catpath('', '/some/dir', 'foo.txt').say;\n    # OUTPUT: «/some/dir\\foo.txt␤»\n\n    IO::Spec::Win32.catpath('E:', '', 'foo.txt').say;\n    # OUTPUT: «E:foo.txt␤»\n\n=head2 method devnull\n\n    method devnull(--> Str:D)\n\nReturns the string C<\"nul\"> representing the\nL<\"Null device\"|https://en.wikipedia.org/wiki/Null_device>:\n\n=for code\n$*SPEC.devnull.IO.spurt: \"foo bar baz\";\n\n=head2 method dir-sep\n\n    method dir-sep(--> Str:D)\n\nReturns the string C<｢\\｣> representing canonical directory separator\ncharacter.\n\n=for code\nIO::Spec::Win32.dir-sep.say; # OUTPUT: «\\␤»\n\n=head2 method is-absolute\n\n    method is-absolute(Str:D $path --> Bool:D)\n\nReturns C<True> if the C<$path> starts with a slash (C<\"/\">) or\nbackslash (C<\"\\\">), even if they have combining character on them,\noptionally preceded by a volume:\n\n    say IO::Spec::Win32.is-absolute: \"/foo\";        # OUTPUT: «True␤»\n    say IO::Spec::Win32.is-absolute: \"/\\x[308]foo\"; # OUTPUT: «True␤»\n    say IO::Spec::Win32.is-absolute: ｢C:\\foo｣;      # OUTPUT: «True␤»\n    say IO::Spec::Win32.is-absolute: \"bar\";         # OUTPUT: «False␤»\n\n=head2 method join\n\n    method join (Str:D $volume, Str:D $dir, Str:D $file --> Str:D)\n\nSimilar to L«C<catpath>|/routine/catpath», takes two path fragments and\nconcatenates them, adding or removing a path separator, if necessary,\nexcept it will return just C<$file> if both C<$dir> and C<$file> are\nstring C<'/'> or if C<$dir> is the string C<'.'>. The first argument is\nignored (it exists to maintain consistent interface with other\nL<C<IO::Spec>|/type/IO::Spec> types for systems that have volumes).\n\n    IO::Spec::Win32.join('C:', '/some/dir', 'foo.txt').say;\n    # OUTPUT: «C:/some/dir\\and/more␤»\n\n    IO::Spec::Win32.join('C:', '.', 'foo.txt').say;\n    # OUTPUT: «C:foo.txt␤»\n\n    IO::Spec::Win32.join('C:', ｢\\｣, '/').say;\n    # OUTPUT: «C:\\␤»\n\n    IO::Spec::Win32.join('//server/share', ｢\\｣, '/').say;\n    # OUTPUT: «//server/share␤»\n\n    IO::Spec::Win32.join('E:', '', 'foo.txt').say;\n    # OUTPUT: «E:foo.txt␤»\n\n=head2 method path\n\n    method path(--> Seq:D)\n\nSplits the value of C«%*ENV<PATH>» (or C«%*ENV<Path>» if the former is not set)\non semicolons (C<\";\">) and returns a L<C<Seq>|/type/Seq> with each of the resultant\nparts, always adding element C<\".\"> to the head. Removes all double\nquotes (C<\">) it finds.\n\n    %*ENV<PATH> = 'foo;\"bar\"/\"ber\"';\n    IO::Spec::Win32.path.raku.say; # OUTPUT: «(\".\", \"foo\", \"bar/ber\").Seq␤»\n\n=head2 method rel2abs\n\n    method rel2abs(Str() $path, $base = $*CWD --> Str:D)\n\nReturns a string representing C<$path> converted to absolute path, based at\nC<$base>, which defaults to C<$*CWD>. If C<$base> is not an absolute path,\nit will be made absolute relative to C<$*CWD>, unless C<$*CWD> and C<$base>\nare the same.\n\n=begin code\nsay $*CWD;                                   # OUTPUT: «\"C:\\Users\\camelia\".IO␤»\n\nsay IO::Spec::Win32.rel2abs: 'foo';          # OUTPUT: «C:\\Users\\camelia\\foo␤»\nsay IO::Spec::Win32.rel2abs: './';           # OUTPUT: «C:\\Users\\camelia␤»\nsay IO::Spec::Win32.rel2abs: 'foo/../../';   # OUTPUT: «C:\\Users\\camelia\\foo\\..\\..␤»\nsay IO::Spec::Win32.rel2abs: '/foo/';        # OUTPUT: «C:\\foo␤»\n\nsay IO::Spec::Win32.rel2abs: 'foo', 'bar';   # OUTPUT: «C:\\Users\\camelia\\bar\\foo␤»\nsay IO::Spec::Win32.rel2abs: './', '/bar';   # OUTPUT: «\\bar␤»\nsay IO::Spec::Win32.rel2abs: '/foo/', 'bar'; # OUTPUT: «C:\\foo␤»\n\nsay IO::Spec::Win32.rel2abs: 'foo/../../', 'bar';\n# OUTPUT: «C:\\Users\\camelia\\bar\\foo\\..\\..␤»\n=end code\n\n=head2 method rootdir\n\n    method rootdir(--> Str:D)\n\nReturns string C<｢\\｣>, representing root directory.\n\n=head2 method split\n\n    method split(IO::Spec::Win32: Cool:D $path)\n\nCreates an L«C<IO::Path::Parts>|/type/IO::Path::Parts» for C<$path>.\n\n=begin code\nIO::Spec::Win32.split('C:/foo/bar.txt').raku.say;\n# OUTPUT: «IO::Path::Parts.new(\"C:\",\"/foo\",\"bar.txt\")␤»\n\nIO::Spec::Win32.split('/foo/').raku.say;\n# OUTPUT: «IO::Path::Parts.new(\"\",\"/\",\"foo\")␤»\n\nIO::Spec::Win32.split('///').raku.say;\n# OUTPUT: «IO::Path::Parts.new(\"\",\"/\",\"\\\\\")␤»\n\nIO::Spec::Win32.split('./').raku.say;\n# OUTPUT: «IO::Path::Parts.new(\"\",\".\",\".\")␤»\n\nIO::Spec::Win32.split('.').raku.say;\n# OUTPUT: «IO::Path::Parts.new(\"\",\".\",\".\")␤»\n\nIO::Spec::Win32.split('').raku.say;\n# OUTPUT: «IO::Path::Parts.new(\"\",\"\",\"\")␤»\n=end code\n\nB<Note>: Before Rakudo release 2020.06 this method split the given\nC<$path> into \"volume\", \"dirname\", and \"basename\" and returned the result\nas a L<C<List>|/type/List> of three L<C<Pair>|/type/Pair>s, in that order.\n\n=head2 method splitdir\n\n    method splitdir(Cool:D $path --> List:D)\n\nSplits the given C<$path> on slashes and backslashes.\n\n=begin code\nIO::Spec::Win32.splitdir('C:\\foo/bar.txt').raku.say;\n# OUTPUT: «(\"C:\", \"foo\", \"bar.txt\")␤»\n\nIO::Spec::Win32.splitdir('/foo/').raku.say;\n# OUTPUT: «(\"\", \"foo\", \"\")␤»\n\nIO::Spec::Win32.splitdir('///').raku.say;\n# OUTPUT: «(\"\", \"\", \"\", \"\")␤»\n\nIO::Spec::Win32.splitdir('./').raku.say;\n# OUTPUT: «(\".\", \"\")␤»\n\nIO::Spec::Win32.splitdir('.').raku.say;\n# OUTPUT: «(\".\",)␤»\n\nIO::Spec::Win32.splitdir('').raku.say;\n# OUTPUT: «(\"\",)␤»\n=end code\n\n=head2 method splitpath\n\n    method splitpath(Cool:D $path, :$nofile --> List:D)\n\nSplits the given C<$path> into a list of 3 strings: volume,\ndirname, and file. The volume is always an empty string, returned for API\ncompatibility with other L<C<IO::Spec>|/type/IO::Spec> types. If C<:$nofile> named argument is\nset to C<True>, the content of the file string is undefined and should be\nignored; this is a means to get a performance boost, as implementations may use\nfaster code path when file is not needed.\n\n=begin code\nIO::Spec::Win32.splitpath('C:\\foo/bar.txt').raku.say;\n# OUTPUT: «(\"C:\", \"\\\\foo/\", \"bar.txt\")␤»\n\nIO::Spec::Win32.splitpath('C:\\foo/bar.txt', :nofile).raku.say;\n# OUTPUT: «(\"C:\", \"\\\\foo/bar.txt\", \"\")␤»\n\nIO::Spec::Win32.splitpath('/foo/').raku.say;\n# OUTPUT: «(\"\", \"/foo/\", \"\")␤»\n\nIO::Spec::Win32.splitpath('/foo/', :nofile).raku.say;\n# OUTPUT: «(\"\", \"/foo/\", \"\")␤»\n\nIO::Spec::Win32.splitpath('///').raku.say;\n# OUTPUT: «(\"\", \"///\", \"\")␤»\n\nIO::Spec::Win32.splitpath('./').raku.say;\n# OUTPUT: «(\"\", \"./\", \"\")␤»\n\nIO::Spec::Win32.splitpath('.').raku.say;\n# OUTPUT: «(\"\", \"\", \".\")␤»\n\nIO::Spec::Win32.splitpath('').raku.say;\n# OUTPUT: «(\"\", \"\", \"\")␤»\n=end code\n\n=head2 method tmpdir\n\n        method tmpdir(--> IO::Path:D)\n\nAttempts to locate a system's temporary directory by checking several typical directories and environment variables. Uses current directory if no suitable directories are found.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Spec.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::Spec\n\n=SUBTITLE Platform specific operations on file and directory paths\n\n    class IO::Spec { }\n\nObjects of this class are not used directly but as a sub-class specific to\nthe platform Raku is running on via the C<$*SPEC> variable which will contain\nan object of the appropriate type.\n\nThe sub-classes are documented separately, with the platform-specific\ndifferences documented in L<C<IO::Spec::Cygwin>|/type/IO::Spec::Cygwin>, L<C<IO::Spec::QNX>|/type/IO::Spec::QNX>,\nL<C<IO::Spec::Unix>|/type/IO::Spec::Unix> and L<C<IO::Spec::Win32>|/type/IO::Spec::Win32>.\n\n=head1 About sub-classes IO::Spec::*\n\nThe C<IO::Spec::*> classes provide low-level path operations. Unless\nyou're creating your own high-level path manipulation routines, you don't\nneed to use C<IO::Spec::*>. Use L«C<IO::Path>|/type/IO::Path» instead.\n\nBeware that no special validation is done by these classes (e.g. check whether\npath contains a null character). It is the job of higher-level classes, like\nL«C<IO::Path>|/type/IO::Path», to do that.\n\n=head1 Methods\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO/Special.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class IO::Special\n\n=SUBTITLE Path to special I/O device\n\n=for code\nclass IO::Special does IO { }\n\nUsed as a L«C<$.path>|/type/IO::Handle#method_path» attribute in filehandles\nfor special standard input C<$*IN> and output C<$*OUT> and C<$*ERR>. Provides\na bridged interface of L«C<IO::Handle>|/type/IO::Handle», mostly file tests\nand stringification.\n\n=head1 Methods\n\n=head2 method new\n\n=for code :skip-test<compile time error>\nmethod new(:$!what!)\n\nTakes a single required attribute L<what|/routine/what>. It is unlikely that you will ever\nneed to construct one of these objects yourself.\n\n=head2 method what\n\n    say $*IN.path.what;  # OUTPUT: «<STDIN>␤»\n    say $*OUT.path.what; # OUTPUT: «<STDOUT>␤»\n    say $*ERR.path.what; # OUTPUT: «<STDERR>␤»\n\nReturns one of the strings C«'<STDIN>'», C«'<STDOUT>'», or C«'<STDERR>'»,\nspecifying the type of the special IO device.\n\n=head2 method WHICH\n\n    method WHICH(IO::Special:D: --> Str)\n\nThis returns a string that identifies the object. The string is composed by the\ntype of the instance (C<IO::Special>) and the C<what> attribute:\n\n    $*IN.path.what;  # OUTPUT: «<STDIN>␤»\n    $*IN.path.WHICH; # OUTPUT: «IO::Special<STDIN>␤»\n\n=head2 method Str\n\n    method Str(IO::Special:D:)\n\nThis returns C«'<STDIN>'», C«'<STDOUT>'», or C«'<STDERR>'» as appropriate.\n\n=head2 method IO\n\n    method IO(IO::Special:D: --> IO::Special)\n\nReturns the invocant.\n\n    say $*IN.path.IO.what;  # OUTPUT: «<STDIN>␤»\n    say $*IN.path.what;     # OUTPUT: «<STDIN>␤»\n\n=head2 method e\n\n    method e(IO::Special:D: --> True)\n\nThe 'exists' file test operator, always returns C<True>.\n\n=head2 method d\n\n    method d(IO::Special:D: --> False)\n\nThe 'directory' file test operator, always returns C<False>.\n\n=head2 method f\n\n    method f(IO::Special:D: --> False)\n\nThe 'file' file test operator, always returns C<False>.\n\n=head2 method s\n\n    method s(IO::Special:D: --> 0)\n\nThe 'size' file test operator, always returns C<0>.\n\n=head2 method l\n\n    method l(IO::Special:D: --> False)\n\nThe 'symbolic links' file test operator, always returns C<False>.\n\n=head2 method r\n\n    method r(IO::Special:D: --> Bool)\n\nThe 'read access' file test operator, returns C<True> if and only if\nthis instance represents the standard input handle(C«<STDIN>»).\n\n=head2 method w\n\n    method w(IO::Special:D: --> Bool)\n\nThe 'write access' file test operator, returns C<True>\nonly if this instance represents either the standard output (C«<STOUT>»)\nor the standard error (C«<STDERR>») handle.\n\n=head2 method x\n\n    method x(IO::Special:D: --> False)\n\nThe 'execute access' file test operator, always returns C<False>.\n\n=head2 method modified\n\n    method modified(IO::Special:D: --> Instant)\n\nThe last modified time for the filehandle.\nIt always returns an L«C<Instant>|/type/Instant» type\nobject.\n\n=head2 method accessed\n\n    method accessed(IO::Special:D: --> Instant)\n\nThe last accessed time for the filehandle.\nIt always returns an L«C<Instant>|/type/Instant» type\nobject.\n\n=head2 method changed\n\n    method changed(IO::Special:D: --> Instant)\n\nThe last changed time for the filehandle.\nIt always returns an L«C<Instant>|/type/Instant» type\nobject.\n\n=head2 method mode\n\n    method mode(IO::Special:D: --> Nil)\n\nThe mode for the filehandle, it always returns L<C<Nil>|/type/Nil>\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IO.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"domain-specific\")\n\n=TITLE role IO\n\n=SUBTITLE Input/output related routines\n\nThe role provides no methods, but exists so that C<IO()> coercers, which\ncoerce to L<C<IO::Path>|/type/IO::Path>, correctly type-check the resultant value. The\nrole is implemented by L<C<IO::Path>|/type/IO::Path> and\nL<C<IO::Special>|/type/IO::Special>.\n\nSee also the related classes L<C<IO::Handle>|/type/IO::Handle> and\nL<C<IO::Path>|/type/IO::Path>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Instant.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Instant\n\n=SUBTITLE Specific moment in time\n\n    class Instant is Cool does Real { }\n\nAn C<Instant> is a particular moment in time measured in atomic seconds, with\nfractions. It is not tied to or aware of any epoch.\n\nAn C<Instant> can be used to create a L<C<DateTime>|/type/DateTime> object set to that\nC<Instant>. The pseudo-constant C<now> returns the current time as an\nC<Instant>.\n\nBasic math is defined for C<Instant>s (as well as L<C<Duration>|/type/Duration>s). Adding an\nC<Instant> to a L<C<Duration>|/type/Duration> returns another Instant. Subtracting two C<Instant>s\nwill yield a L<C<Duration>|/type/Duration>. Adding two C<Instant>s is explicitly disallowed. All\nother operations with Instants are undefined.\n\nI<NOTE:> L<POSIX time|https://en.wikipedia.org/wiki/Unix_time>, a commonly used\nL<time standard|https://en.wikipedia.org/wiki/Time_standard>,\ndoes not address leap seconds, while C<Instant> objects do, so there's some\nextra machinery in the conversion methods to handle this. See methods C<from-posix>,\nC<to-posix>, and the discussion of leap seconds below.\n\n=head1 Methods\n\n=head2 method from-posix\n\n    method from-posix($posix, Bool $prefer-leap-second = False)\n\nConverts the POSIX timestamp C<$posix> to an Instant.\nIf C<$prefer-leap-second> is C<True>, the return value will be\nthe first of the two possible seconds in the case of a leap second.\n\n    say DateTime.new(Instant.from-posix(1483228800, True));  # OUTPUT: «2016-12-31T23:59:60Z␤»\n    say DateTime.new(Instant.from-posix(1483228800));        # OUTPUT: «2017-01-01T00:00:00Z␤»\n\n=head2 method to-posix\n\n    method to-posix()\n\nConverts the invocant to a POSIX timestamp and returns a two\nelement list containing the POSIX timestamp and a L<C<Bool>|/type/Bool>.\nIt is the inverse of L<method from-posix|#method from-posix>, except that the second return\nvalue is C<True> if *and only if* this Instant is in a leap\nsecond.\n\n    say DateTime.new('2017-01-01T00:00:00Z').Instant.to-posix; # OUTPUT: «(1483228800 False)␤»\n    say DateTime.new('2016-12-31T23:59:60Z').Instant.to-posix; # OUTPUT: «(1483228800 True)␤»\n\n=head2 method Date\n\n    method Date(Instant:D: --> Date:D)\n\nCoerces the invocant to L<C<Date>|/type/Date>.\n\n    my $i = \"/etc/passwd\".IO.modified;\n    say $i;             # OUTPUT: «Instant:1771879757.95139447␤»\n    say $i.Date;        # OUTPUT: «2026-02-23␤»\n\n=head2 method DateTime\n\n    method DateTime(Instant:D: --> DateTime:D)\n\nCoerces the invocant to L<C<DateTime>|/type/DateTime>.\n\n    say now.DateTime;  # OUTPUT: «2026-03-07T13:56:42.930951Z␤»\n\n=head1 Leap Seconds\n\nPOSIX time (commonly called \"Unix time\") does not address leap seconds; in\nother words, it assumes that the period of rotation of the Earth is a fixed\nconstant. Since in fact the amount of time that passes between one noon and\nthe next varies from day to day, we must occasionally have a 61st second in\nthe 60th minute of some hour; this is called a leap second, and happens at the\nsame time all over the world, and therefore at different times of day in\ndifferent timezones. POSIX handles this by assigning the same integer label to\ntwo different consecutive seconds; that is, when a leap second happens,\nC<DateTime.now.posix> does not change for two whole seconds.\n\n    my Instant $i .= from-posix(1483228799);\n    my Duration $s = DateTime.new(1) - DateTime.new(0);\n    sub demo { say [$_, .posix] with DateTime.new($i + $^n * $s) }\n    demo(0); # OUTPUT: «[2016-12-31T23:59:59Z 1483228799]␤»\n    demo(1); # OUTPUT: «[2016-12-31T23:59:60Z 1483228800]␤»\n    demo(2); # OUTPUT: «[2017-01-01T00:00:00Z 1483228800]␤»\n    demo(3); # OUTPUT: «[2017-01-01T00:00:01Z 1483228801]␤»\n\nAtomic clocks also disregard the Earth's rotation, so between 1958 when they\nwere first calibrated and the introduction of leap seconds in 1972,\nL<UTC|https://en.wikipedia.org/wiki/Coordinated_Universal_Time> had fallen 10 seconds\nbehind L<atomic-clock time|https://en.wikipedia.org/wiki/International_Atomic_Time>.\nThe numerical value of C<Instant> follows atomic-clock time, and as of\n2026 there have been 27 leap seconds recorded. This adds up to a total of 37\nseconds, which is why, as of 2026, the following holds:\n\n    with now { say .Int - DateTime.new($_).posix } # OUTPUT: «37␤»\n\n=head2 Future Leap Seconds\n\nThe methods that involve knowledge of leap seconds always assume\nthat there will be no further leaps after the last leap second\nthat the implementation knows about, which may not be the last\nleap second that has actually been scheduled.\nThis means you can get different results, depending on the\ncompiler version you're using. For example, the December 31, 2016 leap second\nwas announced in July and shipped with Rakudo 2016.07, so 2016.06 and earlier\nreleases won't know about it.\n\n=begin code :lang<text>\n$ perl6-2016.06 -e 'say Instant.from-posix: 1485726595'\nInstant:1485726631\n\n$ perl6-2016.07 -e 'say Instant.from-posix: 1485726595'\nInstant:1485726632\n=end code\n\nSince a Rakudo compiler always returns 0 for future leap seconds it doesn't\nknow about, you can patch your old code when new leap seconds are announced,\nso it will give correct results, regardless of what version of the compiler\nit runs on:\n\n=begin code :lang<text>\n$ perl6-2016.06 -e 'say ($*VM.version before v2016.07 ?? 1 !! 0) + Instant.from-posix: 1485726595'\nInstant:1485726632\n\n$ perl6-2016.07 -e 'say ($*VM.version before v2016.07 ?? 1 !! 0) + Instant.from-posix: 1485726595'\nInstant:1485726632\n=end code\n\nI<These examples require compilers that predate the rename, and so still refer\nto perl6. This is because there have been no new leap seconds so far since\nthen, as Earth's rotation has been steady since the end of 2016.>\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Int.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Int\n\n=SUBTITLE Integer (arbitrary-precision)\n\n=for code\nclass Int is Cool does Real { }\n\nC<Int> objects store integral numbers of arbitrary size. C<Int>s are immutable.\n\nThere are two main syntax forms for C<Int> literals\n\n    123;         # Int in decimal notation\n    :16<BEEF>;   # Int in radix notation\n\nFor your convenience common radix forms come with a prefix shortcut.\n\n    say so :2<11111111> == 0b11111111 == :8<377> == 0o377 == 255 == 0d255 == :16<ff> == 0xff;\n    # OUTPUT: «True␤»\n\nAll forms allow underscores between any two digits which can serve as visual\nseparators, but don't carry any meaning:\n\n    5_00000;       # five Lakhs\n    500_000;       # five hundred thousand\n    0xBEEF_CAFE;   # a strange place\n    :2<1010_1010>; # 0d170\n\nRadix notation also supports round and square brackets which allow you to parse\na string for a given base, and putting together digits into a whole number\nrespectively:\n\n    :16(\"9F\");         # 159\n    :100[99, 2, 3];    # 990203\n\nThese notations allow you to use variables, too:\n\n    my $two = \"2\";\n    my $ninety-nine = \"99\";\n    :16($ninety-nine); # 153\n    :100[99, $two, 3]; # 990203\n\n=head1 Methods\n\n=head2 method new\n\n    multi method new(Any:U $type)\n    multi method new(Any:D \\value --> Int:D)\n    multi method new(int   \\value --> Int:D)\n\nThe first form will throw an exception; the second and third form will create\n a new Int from the actual integer value contained in the variable.\n\n=head2 method Str\n\n    multi method Str(Int:D)\n    multi method Str(Int:D, :$superscript)\n    multi method Str(Int:D, :$subscript)\n\nReturns a string representation of the number.\n\n    say 42.Str;                # OUTPUT: «42␤»\n\nL«C<Cool>|/type/Cool» being a parent class of C<Int>, an explicit call\nto the C<Int.Str> method is seldom needed, unless you want the string\nto be returned in superscript or subscript.\n\n    say 42.Str(:superscript); # OUTPUT: «⁴²␤»\n    say 42.Str(:subscript);   # OUTPUT: «₄₂␤»\n\nThe C<:superscript> and C<:subscript> named arguments are available as\nof the 2023.05 Rakudo compiler release.\n\n=head2 method Capture\n\n    method Capture()\n\nThrows C<X::Cannot::Capture>.\n\n=head2 routine chr\n\n    multi        chr(Int:D  --> Str:D)\n    multi method chr(Int:D: --> Str:D)\n\nReturns a one-character string, by interpreting the integer as a Unicode\ncodepoint number and converting it to the corresponding character.\n\nExample:\n\n    65.chr;  # returns \"A\"\n    196.chr; # returns \"Ä\"\n\n=head2 routine expmod\n\n    multi        expmod(      $x,     $y,     $mod --> Int:D)\n    multi        expmod(Int:D $x, Int $y, Int $mod --> Int:D)\n    multi method expmod(Int:D:    Int $y, Int $mod --> Int:D)\n\nReturns the given C<Int> raised to the C<$y> power within modulus C<$mod>,\nthat is gives the result of C<($x ** $y) mod $mod>. The subroutine form\ncan accept non-C<Int> arguments, which will be coerced to C<Int>.\n\n    say expmod(4, 2, 5);    # OUTPUT: «1␤»\n    say 7.expmod(2, 5);     # OUTPUT: «4␤»\n\nC<$y> argument can also be negative, in which case, the result is\nequivalent to C<($x ** $y)> mod $mod.\n\n    say 7.expmod(-2, 5);     # OUTPUT: «4␤»\n\n\n=head2 method polymod\n\n    method polymod(Int:D: +@mods)\n\nReturns a sequence of mod results corresponding to the divisors in C<@mods> in\nthe same order as they appear there. For the best effect,  the divisors should\nbe given from the smallest \"unit\" to the largest (e.g. 60 seconds per minute, 60\nminutes per hour) and the results are returned in the same way: from smallest to\nthe largest (5 seconds, 4 minutes). The last non-zero value will be the last\nremainder.\n\n    say 120.polymod(10);    # OUTPUT: «(0 12)␤»\n    say 120.polymod(10,10); # OUTPUT: «(0 2 1)␤»\n\nIn the first case, 120 is divided by 10 giving as a remainder 12, which is the\nlast element. In the second, 120 is C<div>ided by 10, giving 12, whose remainder\nonce divided by 10 is 2; the result of the integer division of 12 C<div> 10 is\nthe last remainder.  The number of remainders will be always one more item than\nthe number of given divisors. If the divisors are given as a lazy list, runs\nuntil the remainder is 0 or the list of divisors is exhausted.\n\n    my $seconds = 1 * 60*60*24 # days\n                + 3 * 60*60    # hours\n                + 4 * 60       # minutes\n                + 5;           # seconds\n\n    say $seconds.polymod(60, 60);                # OUTPUT: «(5 4 27)␤»\n    say $seconds.polymod(60, 60, 24);            # OUTPUT: «(5 4 3 1)␤»\n\n    say 120.polymod:      1, 10, 10², 10³, 10⁴;  # OUTPUT: «(0 0 12 0 0 0)␤»\n    say 120.polymod: lazy 1, 10, 10², 10³, 10⁴;  # OUTPUT: «(0 0 12)␤»\n    say 120.polymod:      1, 10, 10² … ∞;        # OUTPUT: «(0 0 12)␤»\n    my @digits-in-base37 = 9123607.polymod(37 xx *); # Base conversion\n    say @digits-in-base37.reverse                    # OUTPUT: «[4 32 4 15 36]␤»\n\nAll divisors must be C<Int>s when called on an C<Int>.\n\n    say 120.polymod(⅓);                            # ERROR\n\n\nTo illustrate how the C<Int>, non-lazy version of polymod works, consider\nthis code that implements it:\n\n    my $seconds = 2 * 60*60*24 # days\n                + 3 * 60*60    # hours\n                + 4 * 60       # minutes\n                + 5;           # seconds\n\n    my @pieces;\n    for 60, 60, 24 -> $divisor {\n        @pieces.push: $seconds mod $divisor;\n        $seconds div= $divisor\n    }\n    @pieces.push: $seconds;\n\n    say @pieces; # OUTPUT: «[5 4 3 2]␤»\n\nFor a more detailed discussion, see\nL<this blog post|http://blogs.perl.org/users/zoffix_znet/2016/05/perl-6-polymod-break-up-a-number-into-denominations.html>.\n\nWe can use lazy lists in C<polymod>, as long as they are finite:\n\n=for code\nmy $some-numbers = lazy gather { take 3*$_ for 1..3 };\nsay 600.polymod( $some-numbers ); # OUTPUT: «(0 2 6 3)␤»\n\n\n=head2 routine is-prime\n\n    multi        is-prime (Int:D $number --> Bool:D)\n    multi method is-prime (Int:D: --> Bool:D)\n\nReturns C<True> if this C<Int> is known to be a prime, or is likely to be a\nprime based on a L<probabilistic Miller-Rabin test|https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test>.\n\nReturns C<False> if this C<Int> is known not to be a prime.\n\n    say 2.is-prime;         # OUTPUT: «True␤»\n    say is-prime(9);        # OUTPUT: «False␤»\n\n=head2 routine lsb\n\n    multi method lsb(Int:D:)\n    multi        lsb(Int:D)\n\nShort for \"Least Significant Bit\".  Returns L<C<Nil>|/type/Nil> if the number is\n0. Otherwise returns the zero-based index from the right of the least\nsignificant (rightmost) 1 in the binary representation of the number.\n\n    say 0b01011.lsb;        # OUTPUT: «0␤»\n    say 0b01010.lsb;        # OUTPUT: «1␤»\n    say 0b10100.lsb;        # OUTPUT: «2␤»\n    say 0b01000.lsb;        # OUTPUT: «3␤»\n    say 0b10000.lsb;        # OUTPUT: «4␤»\n\n=head2 routine msb\n\n    multi method msb(Int:D:)\n    multi        msb(Int:D)\n\nShort for \"Most Significant Bit\".  Returns L<C<Nil>|/type/Nil> if the number is 0.\nOtherwise returns the zero-based index from the right of the most significant\n(leftmost) 1 in the binary representation of the number.\n\n    say 0b00001.msb;        # OUTPUT: «0␤»\n    say 0b00011.msb;        # OUTPUT: «1␤»\n    say 0b00101.msb;        # OUTPUT: «2␤»\n    say 0b01010.msb;        # OUTPUT: «3␤»\n    say 0b10011.msb;        # OUTPUT: «4␤»\n\n=head2 routine unival\n\n    multi        unival(Int:D  --> Numeric)\n    multi method unival(Int:D: --> Numeric)\n\nReturns the number represented by the Unicode codepoint with the given integer\nnumber, or L<NaN|/type/Num#NaN> if it does not represent a number.\n\n    say ord(\"¾\").unival;    # OUTPUT: «0.75␤»\n    say 190.unival;         # OUTPUT: «0.75␤»\n    say unival(65);         # OUTPUT: «NaN␤»\n\n=head2 method Range\n\nReturns a L<Range object|/type/Range> that represents the range of values supported.\n\n=head2 method Bridge\n\n    method Bridge(Int:D: --> Num:D)\n\nReturns the integer converted to L<C<Num>|/type/Num>.\n\n=head1 Operators\n\n=head2 infix div\n\n    multi infix:<div>(Int:D, Int:D --> Int:D)\n\nDoes an integer division, rounded down.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IntStr.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class IntStr\n\n=SUBTITLE Dual value integer and string\n\n    class IntStr is Allomorph is Int { }\n\nC<IntStr> is a dual value type, a subclass of both\nL«C<Allomorph>|/type/Allomorph», hence L«C<Str>|/type/Str», and\nL«C<Int>|/type/Int».\n\nSee L«C<Allomorph>|/type/Allomorph» for further details.\n\n=begin code\nmy $int-str = <42>;\nsay $int-str.^name;     # OUTPUT: «IntStr␤»\n\nmy Int $int = $int-str; # OK!\nmy Str $str = $int-str; # OK!\n\n# ∈ operator cares about object identity\nsay 42 ∈ <42  55  1>;   # OUTPUT: «False␤»\n=end code\n\n=head1 Methods\n\n=head2 method new\n\n    method new(Int $i, Str $s)\n\nThe constructor requires both the L<C<Int>|/type/Int> and the L<C<Str>|/type/Str> value, when constructing one\ndirectly the values can be whatever is required:\n\n    my $f = IntStr.new(42, \"forty two\");\n    say +$f; # OUTPUT: «42␤»\n    say ~$f; # OUTPUT: «\"forty two\"␤»\n\n=head2 method Int\n\n    method Int\n\nReturns the integer value of the C<IntStr>.\n\n=head2 method Numeric\n\n    multi method Numeric(IntStr:D: --> Int:D)\n    multi method Numeric(IntStr:U: --> Int:D)\n\nThe C<:D> variant returns the numeric portion of the invocant. The C<:U> variant issues\na warning about using an uninitialized value in numeric context and then returns value C<0>.\n\n=head2 method Real\n\n    multi method Real(IntStr:D: --> Int:D)\n    multi method Real(IntStr:U: --> Int:D)\n\nThe C<:D> variant returns the numeric portion of the invocant. The C<:U> variant issues\na warning about using an uninitialized value in numeric context and then returns value C<0>.\n\n=head1 Operators\n\n=head2 infix C«===»\n\n    multi infix:<===>(IntStr:D $a, IntStr:D $b)\n\nC<IntStr> Value identity operator. Returns C<True> if the L<C<Int>|/type/Int>\nvalues of C<$a> and C<$b> are L<identical|/routine/===> and their L<C<Str>|/type/Str>\nvalues are also L<identical|/routine/===>. Returns C<False> otherwise.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Iterable.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"composite\")\n\n=TITLE role Iterable\n\n=SUBTITLE Interface for container objects that can be iterated over\n\n    role Iterable { }\n\nC<Iterable> serves as an API for objects that can be iterated with\nC<for> and related iteration constructs, like assignment to a\nL<C<Positional>|/type/Positional> variable.\n\nC<Iterable> objects nested in other C<Iterable> objects (but not within\nscalar containers) flatten in certain contexts, for example when passed\nto a slurpy parameter (C<*@a>), or on explicit calls to C<flat>.\n\nIts most important aspect is a method stub for C<iterator>.\n\n=begin code\nclass DNA does Iterable {\n    has $.chain;\n    method new ($chain where { $chain ~~ /^^ <[ACGT]>+ $$ / } ) {\n        self.bless( :$chain );\n    }\n\n    method iterator(DNA:D:) {\n        $!chain.comb.rotor(3).iterator;\n    }\n}\n\nmy $a := DNA.new('GAATCC');\n.say for $a; # OUTPUT: «(G A A)␤(T C C)␤»\n=end code\n\nThis example mixes in the Iterable role to offer a new way of iterating\nover what is essentially a string (constrained by\nL<C<where>|/language/signatures#index-entry-where_clause> to just\nthe four DNA letters). In the last statement, C<for> actually hooks to\nthe C<iterator> role printing the letters in groups of 3.\n\n=head1 Methods\n\n=head2 method iterator\n\n    method iterator(--> Iterator:D)\n\nMethod stub that ensures all classes doing the C<Iterable> role have a\nmethod C<iterator>.\n\nIt is supposed to return an L<C<Iterator>|/type/Iterator>.\n\n    say (1..10).iterator;\n\n=head2 method flat\n\n    method flat(Iterable:D: --> Iterable)\n\nReturns another C<Iterable> that flattens out all iterables that\nthe first one returns.\n\nFor example\n\n    say (<a b>, 'c').elems;         # OUTPUT: «2␤»\n    say (<a b>, 'c').flat.elems;    # OUTPUT: «3␤»\n\nbecause C«<a b>» is a L<C<List>|/type/List> and thus iterable, so\nC«(<a b>, 'c').flat» returns C<('a', 'b', 'c')>, which has three elems.\n\nNote that the flattening is recursive, so C<(((\"a\", \"b\"), \"c\"),\n\"d\").flat> returns C<(\"a\", \"b\", \"c\", \"d\")>, but it does not flatten\nL<itemized|/type/List#Items,_flattening_and_sigils> sublists:\n\n    say ($('a', 'b'), 'c').flat;    # OUTPUT: «($(\"a\", \"b\"), \"c\")␤»\n\nYou can use the L«hyper method call|/language/operators#index-entry-methodop_>>.» to\ncall the L«C<.List>|/routine/List» method on all the inner itemized sublists\nand so de-containerize them, so that C<flat> can flatten them:\n\n    say ($('a', 'b'), 'c')>>.List.flat.elems;    # OUTPUT: «3␤»\n\n=head2 method lazy\n\n    method lazy(--> Iterable)\n\nReturns a lazy iterable wrapping the invocant.\n\n    say (1 ... 1000).is-lazy;      # OUTPUT: «False␤»\n    say (1 ... 1000).lazy.is-lazy; # OUTPUT: «True␤»\n\n=head2 method hyper\n\n    method hyper(Int(Cool) :$batch = 64, Int(Cool) :$degree = Kernel.cpu-cores - 1)\n\nReturns another Iterable that is potentially iterated in parallel, with\na given batch size and degree of parallelism.\n\nThe order of elements is preserved.\n\n    say ([1..100].hyper.map({ $_ +1 }).list);\n\nUse C<hyper> in situations where it is OK to do the processing of items\nin parallel, and the output order should be kept relative to the input\norder. See L«C<race>|/routine/race» for situations where items are\nprocessed in parallel and the output order does not matter.\n\n=head3 Options degree and batch\n\nThe C<degree> option (short for \"degree of parallelism\") configures how\nmany parallel workers should be started. To start 4 workers (e.g. to use\nat most 4 cores), pass C<:degree(4)> to the C<hyper> or C<race> method.\nNote that in some cases, choosing a degree higher than the available CPU\ncores can make sense, for example I/O bound work or latency-heavy tasks\nlike web crawling. For CPU-bound work, however, it makes no sense to\npick a number higher than the CPU core count.\n\nThe C<batch> size option configures the number of items sent to a given\nparallel worker at once. It allows for making a throughput/latency\ntrade-off. If, for example, an operation is long-running per item, and\nyou need the first results as soon as possible, set it to 1. That means\nevery parallel worker gets 1 item to process at a time, and reports the\nresult as soon as possible. In consequence, the overhead for\ninter-thread communication is maximized. In the other extreme, if you\nhave 1000 items to process and 10 workers, and you give every worker a\nbatch of 100 items, you will incur minimal overhead for dispatching the\nitems, but you will only get the first results when 100 items are\nprocessed by the fastest worker (or, for C<hyper>, when the worker\ngetting the first batch returns.) Also, if not all items take the same\namount of time to process, you might run into the situation where some\nworkers are already done and sit around without being able to help with\nthe remaining work. In situations where not all items take the same time\nto process, and you don't want too much inter-thread communication\noverhead, picking a number somewhere in the middle makes sense. Your aim\nmight be to keep all workers about evenly busy to make best use of the\nresources available.\n\nYou can also check out this\nB«L<blog post on the semantics of hyper and race|https://raku.github.io/CCR/Remaster/Jonathan%20Worthington/Considering-hyper-race-semantics.html>»\n\nThe default for C<:degree> is the number of available CPU cores minus 1\nas of the 2020.02 release of the Rakudo compiler.\n\nAs of release 2022.07 of the Rakudo compiler, it is also possible to\nspecify an undefined value to indicate to use the default.\n\n=head2 method race\n\n    method race(Int(Cool) :$batch = 64, Int(Cool) :$degree = 4 --> Iterable)\n\nReturns another Iterable that is potentially iterated in parallel, with a\ngiven batch size and degree of parallelism (number of parallel workers).\n\nUnlike L«C<hyper>|/routine/hyper», C<race> does not preserve the order of\nelements (mnemonic: in a race, you never know who will arrive first).\n\n    say ([1..100].race.map({ $_ +1 }).list);\n\nUse race in situations where it is OK to do the processing of items in parallel,\nand the output order does not matter. See L«C<hyper>|/routine/hyper» for\nsituations where you want items processed in parallel and the output order\nshould be kept relative to the input order.\n\nB«L<Blog post on the semantics of hyper and race|https://raku.github.io/CCR/Remaster/Jonathan%20Worthington/Considering-hyper-race-semantics.html>»\n\nSee L«C<hyper>|/routine/hyper» for an explanation of C<:$batch> and C<:$degree>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/IterationBuffer.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class IterationBuffer\n\n=SUBTITLE Low level storage of positional values\n\n=for code\nmy class IterationBuffer { }\n\nAn C<IterationBuffer> is used when the implementation of an L<C<Iterator>|/type/Iterator>\nclass needs a lightweight way to store/transmit values.  It doesn't make\nL<C<Scalar>|/type/Scalar> containers, and only supports mutation through the C<BIND-POS>\nmethod, only supports adding values with the C<push> and C<unshift>\nmethods, supports merging of two C<IterationBuffer> objects with the\nC<append> and C<prepend> methods, and supports resetting with the\nC<clear> method.\n\nIt can be coerced into a L<C<List>|/type/List>, L<C<Slip>|/type/Slip>, or L<C<Seq>|/type/Seq>.\n\nValues will be stored \"as is\", which means that L<Junctions|/type/Junction>\nwill be stored as such and will B<not> L<autothread|/language/glossary#Autothreading>.\n\nAs of release 2021.12 of the Rakudo compiler, the C<new> method also accepts\nan L<C<Iterable>|/type/Iterable> as an optional argument which will be used to\nfill the C<IterationBuffer>.\n\n=head1 Methods\n\n=head2 method push\n\n    method push(IterationBuffer:D: Mu \\value)\n\nAdds the given value at the end of the C<IterationBuffer> and returns the\ngiven value.\n\n=head2 method unshift\n\n    method unshift(IterationBuffer:D: Mu \\value)\n\nAdds the given value at the beginning of the C<IterationBuffer> and returns\nthe given value.  Available as of the 2021.12 release of the Rakudo compiler.\n\n=head2 method append\n\n    method append(IterationBuffer:D: IterationBuffer:D $other --> IterationBuffer:D)\n\nAdds the contents of the other C<IterationBuffer> at the end of\nthe C<IterationBuffer>, and returns the updated invocant.\n\n=head2 method prepend\n\n    method prepend(IterationBuffer:D: IterationBuffer:D $other --> IterationBuffer:D)\n\nAdds the contents of the other C<IterationBuffer> at the beginning\nof the C<IterationBuffer>, and returns the updated invocant.\nAvailable as of the 2021.12 release of the Rakudo compiler.\n\n=head2 method clear\n\n    method clear(IterationBuffer:D: --> Nil)\n\nResets the number of elements in the C<IterationBuffer> to zero,\neffectively removing all data from it, and returns L<C<Nil>|/type/Nil>.\n\n=head2 method elems\n\n    method elems(IterationBuffer:D: --> Int:D)\n\nReturns the number of elements in the C<IterationBuffer>.\n\n=head2 method AT-POS\n\n    multi method AT-POS(IterationBuffer:D: int   $pos)\n    multi method AT-POS(IterationBuffer:D: Int:D $pos)\n\nReturns the value at the given element position, or L<C<Mu>|/type/Mu> if\nthe element position is beyond the length of the C<IterationBuffer>,\nor an error will be thrown indicating the index is out of bounds\n(for negative position values).\n\n=head2 method BIND-POS\n\n    multi method BIND-POS(IterationBuffer:D: int   $pos, Mu \\value)\n    multi method BIND-POS(IterationBuffer:D: Int:D $pos, Mu \\value)\n\nBinds the given value at the given element position and returns it.\nThe C<IterationBuffer> is automatically lengthened if the given\nelement position is beyond the length of the C<IterationBuffer>.\nAn error indicating the index is out of bounds will be thrown for\nnegative position values.\n\n=head2 method Slip\n\n    method Slip(IterationBuffer:D: --> Slip:D)\n\nCoerces the C<IterationBuffer> to a L<C<Slip>|/type/Slip>.\n\n=head2 method List\n\n    method List(IterationBuffer:D: --> List:D)\n\nCoerces the C<IterationBuffer> to a L<C<List>|/type/List>.\n\n=head2 method Seq\n\n    method Seq(IterationBuffer:D: --> Seq:D)\n\nCoerces the C<IterationBuffer> to a L<C<Seq>|/type/Seq>.\n\n=head2 method raku\n\n    method raku(IterationBuffer:D: --> Str)\n\nProduces a representation of the C<IterationBuffer> as a L<C<List>|/type/List>\npostfixed with \".IterationBuffer\" to make it different from an\nordinary list.  Does B<not> roundtrip.  Intended for debugging\nuses only, specifically for use with L<dd|/programs/01-debugging#Dumper_function_(dd)>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Iterator.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"composite\")\n\n=TITLE role Iterator\n\n=SUBTITLE Generic API for producing a sequence of values\n\n=for code :skip-test<compile time error>\nconstant IterationEnd\nrole Iterator { }\n\nAn C<Iterator> is an object that can generate or provide elements of a sequence.\nUsers usually don't have to care about iterators, their usage is hidden behind\niteration APIs such as C<for @list { }>, L<map|/routine/map>,\nL<grep|/routine/grep>, L<head|/routine/head>, L<tail|/routine/tail>,\nL<skip|/routine/skip> and list indexing with C<.[$idx]>.\n\nThe main API is the C<pull-one> method, which either returns the next\nvalue, or the sentinel value C<IterationEnd> if no more elements are\navailable. Each class implementing C<Iterator> B<must> provide a\nC<pull-one> method. All other non-optional Iterator API methods are\nimplemented in terms of C<pull-one>, but can also be overridden by\nconsuming classes for performance or other reasons. There are also\noptional Iterator API methods that will only be called if they are\nimplemented by the consuming class: these are B<not> implemented by the\nIterator role.\n\nX<|Reference,IterationEnd>\n=head1 IterationEnd\n\nIterators only allow one iteration over the entire sequence. It's forbidden to\nmake attempts to fetch more data, once C<IterationEnd> has been generated, and\nbehavior for doing so is undefined. For example, the following L<C<Seq>|/type/Seq>\nwill not cause the L<die|/routine/die> to be called under normal use, because\nL<pull-one|/routine/pull-one> will never be called after it returns\nC<IterationEnd>:\n\n=begin code\nclass SkippingArray is Array {\n    # skip all undefined values while iterating\n    method iterator {\n        class :: does Iterator {\n            has $.index is rw = 0;\n            has $.array is required;\n            method pull-one {\n                $.index++ while !$.array.AT-POS($.index).defined && $.array.elems > $.index;\n                $.array.elems > $.index ?? $.array.AT-POS($.index++) !! IterationEnd\n            }\n        }.new(array => self)\n    }\n}\n\nmy @a := SkippingArray.new;\n\n@a.append: 1, Any, 3, Int, 5, Mu, 7;\n\nfor @a -> $a, $b {\n    say [$a, $b];\n}\n\n# OUTPUT: «[1 3]␤[5 7]␤»\n=end code\n\nThe only valid use of the sentinel value C<IterationEnd> in a program is\nidentity comparison (using L«C<=:=>|/routine/=:=») with the result of a method\nin the iterator API. Any other behavior is undefined and implementation\ndependent. For instance, using it as part of a list that's going to be iterated\nover might result in the loop ending, or not.\n\n=for code\n.say for [\"foo\",IterationEnd, \"baz\"]; # OUTPUT: «foo␤»\nsay [\"foo\",IterationEnd, \"baz\"].map: \"«\" ~ * ~ \"»\";\n# OUTPUT: «(«foo» «IterationEnd» «baz»)␤»\n\nPlease bear in mind that C<IterationEnd> is a constant, so if you are\ngoing to compare it against the value of a variable, this variable will\nhave to be bound, not assigned. Comparing directly to the output of\nC<pull-one> will work.\n\n=begin code\nmy $it = (1,2).iterator;\n$it.pull-one for ^2;\nsay $it.pull-one =:= IterationEnd; # OUTPUT: «True␤»\n=end code\n\nHowever, if we use a variable we and we assign it, the result will be\nincorrect:\n\n=begin code\nmy $it = (1,2).iterator;\n$it.pull-one for ^2;\nmy $is-it-the-end = $it.pull-one;\nsay $is-it-the-end =:= IterationEnd; # OUTPUT: «False␤»\n=end code\n\nSo we'll have to bind the variable to make it work:\n\n=begin code :preamble<my $it>\nmy $is-it-the-end := $it.pull-one;\nsay $is-it-the-end =:= IterationEnd; # OUTPUT: «True␤»\n=end code\n\n=head1 Methods\n\n=head2 method pull-one\n\n    method pull-one(Iterator:D: --> Mu)\n\nThis method stub ensures that classes implementing the C<Iterator> role\nprovide a method named C<pull-one>.\n\nThe C<pull-one> method is supposed to produce and return the next value if\npossible, or return the sentinel value C<IterationEnd> if no more values could\nbe produced.\n\n    my $i = (1 .. 3).iterator;\n    say $i.pull-one;       # OUTPUT: «1␤»\n    say $i.pull-one;       # OUTPUT: «2␤»\n    say $i.pull-one;       # OUTPUT: «3␤»\n    say $i.pull-one.raku;  # OUTPUT: «IterationEnd␤»\n\nAs a more illustrative example of its use, here is a count down iterator along with\na simplistic subroutine re-implementation of the C<for> loop.\n\n    # works the same as (10 ... 1, 'lift off')\n    class CountDown does Iterator {\n        has Int:D $!current = 10;\n\n        method pull-one ( --> Mu ) {\n            my $result = $!current--;\n            if $result ==  0 { return 'lift off' }\n            if $result == -1 { return IterationEnd }\n\n            # calling .pull-one again after it returns IterationEnd is undefined\n            if $result <= -2 {\n                # so for fun we will give them nonsense data\n                return (1..10).pick;\n            }\n\n            return $result;\n        }\n    }\n\n    sub for( Iterable:D $sequence, &do --> Nil ) {\n        my Iterator:D $iterator = $sequence.iterator;\n\n        loop {\n            # must bind the result so that =:= works\n            my Mu $pulled := $iterator.pull-one;\n\n            # always check the result and make sure that .pull-one\n            # is not called again after it returns IterationEnd\n            if $pulled =:= IterationEnd { last }\n\n            do( $pulled );\n        }\n    }\n\n    for( Seq.new(CountDown.new), &say );  # OUTPUT: «10␤9␤8␤7␤6␤5␤4␤3␤2␤1␤lift off␤»\n\nIt would be more idiomatic to use C<while> or C<until>, and a sigilless variable.\n\n=begin code :preamble<my $iterator = ().iterator; my &do = &say>\nuntil IterationEnd =:= (my \\pulled = $iterator.pull-one) {\n    do( pulled );\n}\n=end code\n\n=head2 method push-exactly\n\n    method push-exactly(Iterator:D: $target, int $count --> Mu)\n\nShould produce C<$count> elements, and for each of them, call\nC<$target.push($value)>.\n\nIf fewer than C<$count> elements are available from the iterator, it\nshould return the sentinel value C<IterationEnd>. Otherwise it should return\nC<$count>.\n\n    my @array;\n    say (1 .. ∞).iterator.push-exactly(@array, 3); # OUTPUT: «3␤»\n    say @array; # OUTPUT: «[1 2 3]␤»\n\nThe Iterator role implements this method in terms of C<pull-one>. In general,\nthis is a method that is not intended to be called directly from the end user\nwho, instead, should implement it in classes that mix the iterator role. For\ninstance, this class implements that role:\n\n=begin code\nclass DNA does Iterable does Iterator {\n    has $.chain;\n    has Int $!index = 0;\n\n    method new ($chain where {\n                       $chain ~~ /^^ <[ACGT]>+ $$ / and\n                       $chain.chars %% 3 } ) {\n        self.bless( :$chain );\n    }\n\n    method iterator( ){ self }\n\n    method pull-one( --> Mu){\n      if $!index < $.chain.chars {\n         my $codon = $.chain.comb.rotor(3)[$!index div 3];\n         $!index += 3;\n         return $codon;\n      } else {\n        return IterationEnd;\n      }\n    }\n\n    method push-exactly(Iterator:D: $target, int $count --> Mu) {\n        return IterationEnd if $.chain.elems / 3 < $count;\n        for ^($count) {\n            $target.push: $.chain.comb.rotor(3)[ $_ ];\n        }\n    }\n\n};\n\nmy $b := DNA.new(\"AAGCCT\");\nfor $b -> $a, $b, $c { say \"Never mind\" }; # Does not enter the loop\nmy $þor := DNA.new(\"CAGCGGAAGCCT\");\nfor $þor -> $first, $second {\n    say \"Coupled codons: $first, $second\";\n    # OUTPUT: «Coupled codons: C A G, C G G␤Coupled codons: A A G, C C T␤»\n}\n=end code\n\nThis code, which groups DNA chains in triplets (usually called I<codons>)\nreturns those codons when requested in a loop; if too many are requested, like\nin the first case C«for $b -> $a, $b, $c», it simply does not enter the loop\nsince C<push-exactly> will return C<IterationEnd> since it is not able to serve\nthe request for exactly 3 codons. In the second case, however, it requests\nexactly two codons in each iteration of the loop; C<push-exactly> is being\ncalled with the number of loop variables as the C<$count> variable.\n\n=head2 method push-at-least\n\n    method push-at-least(Iterator:D: $target, int $count --> Mu)\n\nShould produce at least C<$count> elements, and for each of them, call\nC<$target.push($value)>.\n\nIf fewer than C<$count> elements are available from the iterator, it\nshould return the sentinel value C<IterationEnd>. Otherwise it should return\nC<$count>.\n\nIterators with side effects should produce exactly C<$count> elements;\niterators without side effects (such as L<C<Range>|/type/Range> iterators) can\nproduce more elements to achieve better performance.\n\n    my @array;\n    say (1 .. ∞).iterator.push-at-least(@array, 10); # OUTPUT: «10␤»\n    say @array; # OUTPUT: «[1 2 3 4 5 6 7 8 9 10]␤»\n\nThe Iterator role implements this method in terms of C<pull-one>. In\ngeneral, it is also not intended to be called directly as in the example\nabove. It can be implemented, if unhappy with this default\nimplementation, by those using this role. See\nL<the documentation for C<push-exactly>|/type/Iterator#method_push-exactly>\nfor an example implementation.\n\n=head2 method push-all\n\n    method push-all(Iterator:D: $target)\n\nShould produce all elements from the iterator and push them to C<$target>.\n\n    my @array;\n    say (1 .. 1000).iterator.push-all(@array); # All 1000 values are pushed\n\nThe C<Iterator> role implements this method in terms of C<push-at-least>. As in\nthe case of the other C<push-*> methods, it is mainly intended for developers\nimplementing this role. C<push-all> is called when assigning an object with this\nrole to an array, for instance, like in this example:\n\n=begin code\nclass DNA does Iterable does Iterator {\n    has $.chain;\n    has Int $!index = 0;\n\n    method new ($chain where {\n                       $chain ~~ /^^ <[ACGT]>+ $$ / and\n                       $chain.chars %% 3 } ) {\n        self.bless( :$chain );\n    }\n\n    method iterator( ){ self }\n    method pull-one( --> Mu){\n      if $!index < $.chain.chars {\n         my $codon = $.chain.comb.rotor(3)[$!index div 3];\n         $!index += 3;\n         return $codon;\n      } else {\n        return IterationEnd;\n      }\n    }\n\n    method push-all(Iterator:D: $target) {\n        for $.chain.comb.rotor(3) -> $codon {\n            $target.push: $codon;\n        }\n    }\n\n};\n\nmy $b := DNA.new(\"AAGCCT\");\nmy @dna-array = $b;\nsay @dna-array; # OUTPUT: «[(A A G) (C C T)]␤»\n=end code\n\nThe C<push-all> method implemented pushes to the target iterator in lists of\nthree amino acid representations; this is called under the covers when we assign\nC<$b> to C<@dna-array>.\n\n=head2 method push-until-lazy\n\n    method push-until-lazy(Iterator:D: $target --> Mu)\n\nShould produce values until it considers itself to be lazy, and push them onto\nC<$target>.\n\nThe Iterator role implements this method as a no-op if C<is-lazy> returns\na True value, or as a synonym of C<push-all> if not.\n\nThis matters mostly for iterators that have other iterators embedded, some of\nwhich might be lazy, while others aren't.\n\n=head2 method is-deterministic\n\n    method is-deterministic(Iterator:D: --> Bool:D)\n\nShould return C<True> for iterators that, given a source, will always produce\nthe values in the same order.\n\nBuilt-in operations can perform certain optimizations when it is certain that\nvalues will always be produced in the same order.  Some examples:\n\n    say (1..10).iterator.is-deterministic;              # OUTPUT: «True␤»\n    say (1..10).roll(5).iterator.is-deterministic;      # OUTPUT: «False␤»\n    say %(a => 42, b => 137).iterator.is-deterministic; # OUTPUT: «False␤»\n\nThe Iterator role implements this method returning C<True>, indicating an\niterator that will always produce values in the same order.\n\n=head2 method is-monotonically-increasing\n\n    method is-monotonically-increasing(Iterator:D: --> Bool:D)\n\nShould return C<True> for iterators that, given a source, will always produce\nthe values in the increasing value (according to C<cmp> semantics).\n\nBuilt-in operations can perform certain optimizations when it is certain that\nvalues will always be produced in ascending order.  Some examples:\n\n    say (1..10).iterator.is-monotonically-increasing;              # OUTPUT: «True␤»\n    say (1..10).roll(5).iterator.is-monotonically-increasing;      # OUTPUT: «False␤»\n    say %(a => 42, b => 137).iterator.is-monotonically-increasing; # OUTPUT: «False␤»\n\nThe Iterator role implements this method returning C<False>, indicating an\niterator that will B<not> produce values with increasing values.\n\n=head2 method is-lazy\n\n    method is-lazy(Iterator:D: --> Bool:D)\n\nShould return C<True> for iterators that consider themselves lazy, and C<False>\notherwise.\n\nBuilt-in operations that know that they can produce infinitely many values\nreturn C<True> here, for example C<(1..6).roll(*)>.\n\n    say (1 .. 100).iterator.is-lazy; # OUTPUT: «False␤»\n    say (1 .. ∞).iterator.is-lazy; # OUTPUT: «True␤»\n\nThe Iterator role implements this method returning C<False>, indicating a\nnon-lazy iterator.\n\n=head2 method sink-all\n\n    method sink-all(Iterator:D: --> IterationEnd)\n\nShould exhaust the iterator purely for the side-effects of producing the\nvalues, without actually saving them in any way.  Should always return\nC<IterationEnd>.  If there are no side-effects associated with producing a\nvalue, then it can be implemented by a consuming class to be a virtual no-op.\n\n    say (1 .. 1000).iterator.sink-all;  # OUTPUT: «IterationEnd␤»\n\nThe Iterator role implements this method as a loop that calls C<pull-one>\nuntil it is exhausted.\n\n=head2 method skip-one\n\n    method skip-one(Iterator:D: $target --> Mu)\n\nShould skip producing one value. The return value should be truthy if the skip\nwas successful and falsy if there were no values to be skipped:\n\n    my $i = <a b>.iterator;\n    say $i.skip-one; say $i.pull-one; say $i.skip-one\n    # OUTPUT: «1␤b␤0␤»\n\nThe Iterator role implements this method as a call C<pull-one> and returning\nwhether the value obtained was not C<IterationEnd>.\n\n=head2 method skip-at-least\n\n    method skip-at-least(Iterator:D: $target, int $to-skip --> Mu)\n\nShould skip producing C<$to-skip> values. The return value should be truthy if\nthe skip was successful and falsy if there were not enough values to be skipped:\n\n    my $i = <a b c>.iterator;\n    say $i.skip-at-least(2); say $i.pull-one; say $i.skip-at-least(20);\n    # OUTPUT: «1␤c␤0␤»\n\nThe Iterator role implements this method as a loop calling C<skip-one> and\nreturning whether it returned a truthy value sufficient number of times.\n\n=head2 method skip-at-least-pull-one\n\n    method skip-at-least-pull-one(Iterator:D: $target, int $to-skip --> Mu)\n\nShould skip producing C<$to-skip> values and if the iterator is still not\nexhausted, produce and return the next value.  Should return C<IterationEnd>\nif the iterator got exhausted at any point:\n\n    my $i = <a b c>.iterator;\n    say $i.skip-at-least-pull-one(2);\n    say $i.skip-at-least-pull-one(20) =:= IterationEnd;\n    # OUTPUT: «c␤True␤»\n\nThe Iterator role implements this method as calling C<skip-at-least> and\nthen calling C<pull-one> if it was not exhausted yet.\n\n=head1 Predictive iterators\n\nPlease see the L<C<PredictiveIterator>|/type/PredictiveIterator> role if your C<Iterator> can know\nhow many values it can still produce without actually producing them.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Junction.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Junction\n\n=SUBTITLE Logical superposition of values\n\n    class Junction is Mu { }\n\nA junction is an unordered composite value of zero or more values. Junctions\nI<autothread> over many operations, which means that the operation\nis carried out for each junction element (also known as I<eigenstate>), and\nthe result is the junction of the return values of all those operators.\n\nJunctions collapse into a single value in Boolean context, so when used in a\nconditional, a negation or an explicit coercion to Bool through the C<so> or\nC<?> prefix operators. The semantics of this collapse\ndepend on the I<junction type>, which can be C<all>, C<any>, C<one> or\nC<none>.\n\n=begin table\n\n    type |   constructor  |   operator |  True if ...\n    =====+================+============+===========\n    all  |   all          |   &        |   no value evaluates to False\n    any  |   any          |   \\|       |   at least one value evaluates to True\n    one  |   one          |   ^        |   exactly one value evaluates to True\n    none |   none         |            |   no value evaluates to True\n\n=end table\n\nAs the table shows, in order to create junctions you use the command that\nrepresents the type of C<Junction> followed by any object, or else call\nL<C<.all>|/routine/all>, L<C<.none>|/routine/none> or L<C<.one>|/routine/one> on\nthe object.\n\n    say so 3 == (1..30).one;         # OUTPUT: «True␤»\n    say so (\"a\" ^ \"b\" ^ \"c\") eq \"a\"; # OUTPUT: «True␤»\n\nJunctions are very special objects. They fall outside the L<C<Any>|/type/Any> hierarchy,\nbeing only, as any other object, subclasses of L<C<Mu>|/type/Mu>. That enables a feature for\nmost methods: autothreading. Autothreading happens when a junction is bound to a\nparameter of a code object that doesn't accept values of type C<Junction>.\nInstead of producing an error, the signature binding is repeated for each value\nof the junction.\n\nExample:\n\n    my $j = 1|2;\n    if 3 == $j + 1 {\n        say 'yes';\n    }\n\nFirst autothreads over the C«infix:<+>» operator, producing the Junction\nC<2|3>. The next autothreading step is over C«infix:<==>», which produces\nC<False|True>. The C<if> conditional evaluates the junction in Boolean\ncontext, which collapses it to C<True>. So the code prints C<yes\\n>.\n\nThe type of a C<Junction> does I<not> affect the number of items in the\nresultant C<Junction> after autothreading. For example, using a\nL<one|/routine/one> C<Junction> during L<C<Hash>|/type/Hash> key lookup, still\nresults in a C<Junction> with several items. It is only in Boolean context would\nthe type of the C<Junction> come into play:\n\n    my %h = :42foo, :70bar;\n    say    %h{one <foo meow>}:exists; # OUTPUT: «one(True, False)␤»\n    say so %h{one <foo meow>}:exists; # OUTPUT: «True␤»\n    say    %h{one <foo  bar>}:exists; # OUTPUT: «one(True, True)␤»\n    say so %h{one <foo  bar>}:exists; # OUTPUT: «False␤»\n\nNote that the compiler is allowed, but not required, to parallelize\nautothreading (and Junction behavior in general), so it is usually an\nerror to autothread junctions over code with side effects.\n\nAutothreading implies that the function that's autothreaded will also return a\nJunction of the values that it would usually return.\n\n    (1..3).head( 2|3 ).say; # OUTPUT: «any((1 2), (1 2 3))␤»\n\nSince L<C<.head>|/routine/head> returns a list, the autothreaded version returns\na C<Junction> of lists.\n\n    'walking on sunshine'.contains( 'king'&'sun' ).say; # OUTPUT: «all(True, True)␤»\n\nLikewise, L<C<.contains>|/routine/contains> returns a Boolean; thus, the\nautothreaded version returns a C<Junction> of Booleans. In general, all methods\nand routines that take an argument of type C<T> and return type C<TT>, will also\naccept junctions of C<T>, returning junctions of C<TT>.\n\nImplementations are allowed to short-circuit Junctions. For example one or more\nroutine calls (C<a()>, C<b()>, or C<c()>) in the code below might not get\nexecuted at all, if the result of the conditional has been fully determined\nfrom routine calls already performed (only one truthy return value is enough\nto know the entire Junction is true):\n\n=begin code :preamble<sub a(){}; sub b(){}; sub c(){}>\nif a() | b() | c() {\n    say \"At least one of the routines was called and returned a truthy value\"\n}\n=end code\n\nJunctions are meant to be used as matchers in a Boolean context; introspection\nof junctions is not supported. If you feel the urge to introspect a junction,\nuse a L<C<Set>|/type/Set> or a related type instead.\n\nUsage examples:\n\n    my @list = <1 2 \"Great\">;\n    @list.append(True).append(False);\n    my @bool_or_int = grep Bool|Int, @list;\n\n    sub is_prime(Int $x) returns Bool {\n        # 'so' is for Boolean context\n        so $x %% none(2..$x.sqrt);\n    }\n    my @primes_ending_in_1 = grep &is_prime & / 1$ /, 2..100;\n    say @primes_ending_in_1;        # OUTPUT: «[11 31 41 61 71]␤»\n\n    my @exclude = <~ .git>;\n    for dir(\".\") { say .Str if .Str.ends-with(none @exclude) }\n\nSpecial care should be taken when using C<all> with arguments that may\nproduce an empty list:\n\n    my @a = ();\n    say so all(@a) # True, because there are 0 Falses\n\nTo express \"all, but at least one\", you can use C<@a && all(@a)>\n\n    my @a = ();\n    say so @a && all(@a);   # OUTPUT: «False␤»\n\nNegated operators are special-cased when it comes to autothreading.\nC<$a !op $b> is rewritten internally as C<!($a op $b)>. The outer\nnegation collapses any junctions, so the return value always a plain\nL<C<Bool>|/type/Bool>.\n\n    my $word = 'yes';\n    my @negations = <no none never>;\n    if $word !eq any @negations {\n        say '\"yes\" is not a negation';\n    }\n\nNote that without this special-casing, an expression like\nC<$word ne any @words> would always evaluate to C<True> for non-trivial lists\non one side.\n\nFor this purpose, C«infix:<ne>» counts as a negation of C«infix:<eq>».\n\nIn general it is more readable to use a positive comparison operator and\na negated junction:\n\n    my $word = 'yes';\n    my @negations = <no none never>;\n    if $word eq none @negations {\n        say '\"yes\" is not a negation';\n    }\n\n\n=head1 Failures and exceptions\n\nL<C<Failure>|/type/Failure>s are just values like any other, as far as Junctions\nare concerned:\n\n    my $j = +any \"not a number\", \"42\", \"2.1\";\n    my @list = gather for $j -> $e {\n        take $e if $e.defined;\n    }\n    @list.say; # OUTPUT: «[42 2.1]␤»\n\nAbove, we've used prefix C<+> operator on a C<Junction> to coerce\nthe strings inside of it to L<C<Numeric>|/type/Numeric>. Since the operator returns\na L<C<Failure>|/type/Failure> when a L<C<Str>|/type/Str> that doesn't\ncontain a number\ngets coerced to L<C<Numeric>|/type/Numeric>, one of the elements in the C<Junction> is a\nL<C<Failure>|/type/Failure>. Failures do not turn into exceptions until they are used or sunk,\n but we can check for definedness to avoid that. That is what we do in the\n loop that runs over the elements of the junction, adding them to a list only\n  if they are defined.\n\nThe exception I<will> be thrown, if you try to use the L<C<Failure>|/type/Failure> as a\nvalue—just like as if this L<C<Failure>|/type/Failure> were on its own and not part of the\nC<Junction>:\n\n=for code\nmy $j = +any \"not a number\", \"42\", \"2.1\";\ntry say $j == 42;\n$! and say \"Got exception: $!.^name()\";\n# OUTPUT: «Got exception: X::Str::Numeric␤»\n\nNote that if an exception gets thrown when I<any> of the values in a\nC<Junction> get computed, it will be thrown just as if the\nproblematic value were computed on its own and not with a C<Junction>; you can't\njust compute the values that work while ignoring exceptions:\n\n    sub calc ($_) { die when 13 }\n    my $j = any 1..42;\n    say try calc $j; # OUTPUT: «Nil␤»\n\nOnly one value above causes an exception, but the result of the L«C<try>\nblock|/language/exceptions#try_blocks» is still a\nL<C<Nil>|/type/Nil>. A possible way around it is to cheat and evaluate the values\nof the C<Junction> individually and then re-create the C<Junction> from the\nresult:\n\n    sub calc ($_) { die when 13 }\n    my $j = any 1..42;\n    $j = any (gather $j».take).grep: {Nil !=== try calc $_};\n    say so $j == 42; # OUTPUT: «True␤»\n\n=head1 Smartmatching\n\nNote that using C<Junction>s on the right-hand side of C<~~> works\nslightly differently than using Junctions with other operators.\n\nConsider this example:\n\n    say 25 == (25 | 42);    # OUTPUT: «any(True, False)␤» – Junction\n    say 25 ~~ (25 | 42);    # OUTPUT: «True␤»             – Bool\n\nThe reason is that C<==> (and most other operators) are subject to\nauto-threading, and therefore you will get a Junction as a result. On\nthe other hand, C<~~> will call C<.ACCEPTS> on the right-hand-side (in\nthis case on a Junction) and the result will be a L<C<Bool>|/type/Bool>.\n\n=head1 Methods\n\n=head2 method new\n\n    multi method new(Junction: \\values, Str :$type!)\n    multi method new(Junction: Str:D \\type, \\values)\n\nThese constructors build a new junction from the type that defines it and a\nset of values.\n\n    my $j = Junction.new(<Þor Oðinn Loki>, type => \"all\");\n    my $n = Junction.new( \"one\", 1..6 )\n\nThe main difference between the two multis is how the type of the C<Junction>\nis passed as an argument; either positionally as the first argument, or as a\nnamed argument using C<type>.\n\n=head2 method defined\n\n    multi method defined(Junction:D:)\n\nChecks for definedness instead of Boolean values.\n\n    say ( 3 | Str).defined ;   # OUTPUT: «True␤»\n    say (one 3, Str).defined;  # OUTPUT: «True␤»\n    say (none 3, Str).defined; # OUTPUT: «False␤»\n\nL<C<Failure>|/type/Failure>s are also considered non-defined:\n\n    my $foo=Failure.new;\n    say (one 3, $foo).defined; # OUTPUT: «True␤»\n\nSince 6.d, this method will autothread.\n\n=head2 method Bool\n\n    multi method Bool(Junction:D:)\n\nCollapses the C<Junction> and returns a single Boolean value according to the\ntype and the values it holds. Every element is transformed to L<C<Bool>|/type/Bool>.\n\n=for code\nmy $n = Junction.new( \"one\", 1..6 );\nsay $n.Bool;                         # OUTPUT: «False␤»\n\nAll elements in this case are converted to C<True>, so it's false to assert\nthat only one of them is.\n\n=for code\nmy $n = Junction.new( \"one\", <0 1> );\nsay $n.Bool;                         # OUTPUT: «True␤»\n\nJust one of them is truish in this case, C<1>, so the coercion to L<C<Bool>|/type/Bool>\nreturns C<True>.\n\n\n=head2 method Str\n\n    multi method Str(Junction:D:)\n\nAutothreads the C<.Str> method over its elements and returns results as a\nC<Junction>. Output methods that use C<.Str> method\n(L<print|/routine/print> and L<put|/routine/put>) are special-cased to\nautothread junctions, despite being able to accept a L<C<Mu>|/type/Mu> type.\n\n=head2 method iterator\n\n    multi method iterator(Junction:D:)\n\nReturns an iterator over the C<Junction> converted to a L<C<List>|/type/List>.\n\n=head2 method gist\n\n    multi method gist(Junction:D:)\n\nCollapses the C<Junction> and returns a L<C<Str>|/type/Str> composed\nof the type of the junction and the L<gists|/routine/gist> of its components:\n\n    <a 42 c>.all.say; # OUTPUT: «all(a, 42, c)␤»\n\n=head2 method raku\n\n    multi method raku(Junction:D:)\n\nCollapses the C<Junction> and returns a L<C<Str>|/type/Str> composed\nof L<raku|/routine/raku> of its components that L<evaluates|/routine/EVAL> to\nthe equivalent C<Junction> with equivalent components:\n\n    <a 42 c>.all.raku.put; # OUTPUT: «all(\"a\", IntStr.new(42, \"42\"), \"c\")␤»\n\n=head2 infix C<~>\n\n    multi infix:<~>(Str:D $a, Junction:D $b)\n    multi infix:<~>(Junction:D $a, Str:D $b)\n    multi infix:<~>(Junction:D \\a, Junction:D \\b)\n\nThe infix C<~> concatenation can be used to merge junctions into a single one or\nmerge Junctions with strings. The resulting junction will have all elements\nmerged as if they were joined into a nested loop:\n\n=begin code\nmy $odd  = 1|3|5;\nmy $even = 2|4|6;\n\nmy $merged = $odd ~ $even;\nsay $merged; # OUTPUT: «any(12, 14, 16, 32, 34, 36, 52, 54, 56)␤»\n\nsay \"Found 34!\" if 34 == $merged; # OUTPUT: «Found 34!␤»\nmy $prefixed = \"0\" ~ $odd;\nsay \"Found 03\" if \"03\" == $prefixed; # OUTPUT: «Found 03!␤»\n\nmy $postfixed = $odd ~ \"1\";\nsay \"Found 11\" if 11 == $postfixed; # OUTPUT: «Found 11!␤»\n=end code\n\nOn the other hand, the versions of C<~> that use a string as one argument will\njust concatenate the string to every member of the Junction, creating another\nJunction with the same number of elements.\n\n=head1 See Also\n\n=item L<https://perlgeek.de/blog-en/perl-5-to-6/08-junctions.html>\n=item L<https://web.archive.org/web/20190608135817/http://perl6maven.com/perl6-is-a-value-in-a-given-list-of-values>\n=item L<https://perl6advent.wordpress.com/2009/12/13/day-13-junctions/>\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Kernel.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Kernel\n\n=SUBTITLE Kernel related information\n\n    class Kernel does Systemic { }\n\nBuilt-in class for providing kernel related information.  Usually accessed\nthrough the L«C<$*KERNEL>|/language/variables#Dynamic_variables» dynamic\nvariable.\n\n=head1 Methods\n\n=head2 method arch\n\n    method arch\n\nInstance method returning the \"arch\" (as in \"architecture\") information of the\nKernel object.  Dies if the \"arch\" could not be established.\n\n=head2 method archname\n\n    method archname\n\nInstance method returning the concatenation of L<hardware|/routine/hardware> and\nL<name|/routine/name>.\n\n=head2 method bits\n\n    method bits\n\nInstance method returning the number of bits used in the architecture of the\nprocessor.  Usually B<32> or B<64>.\n\n=head2 method cpu-cores\n\n    method cpu-cores(--> Int)\n\nInstance / Class method returning the number of CPU cores that are available.\n\n    say $*KERNEL.cpu-cores; # OUTPUT: «8␤»\n\n=head2 method cpu-usage\n\n    method cpu-usage(--> Int)\n\nInstance / Class method returning the amount of CPU uses since the start of\nthe program (in microseconds).\n\n=head2 method free-memory\n\n    method free-memory(--> Int)\n\nInstance / Class method returning the available memory on the system. When\nusing the JVM, this returns the available memory to the JVM instead. This\nmethod is only available in release v2019.06 and later.\n\n=head2 method total-memory\n\n    method total-memory(--> Int)\n\nInstance / Class method returning the total memory available to the system.\nWhen using the JVM, this returns the total memory available to the JVM instead.\nThis method is only available in release v2019.06 and later.\n\n=head2 method endian\n\n    method endian(--> Endian:D)\n\nClass method that returns the L<C<Endian>|/type/Endian> object associated with\nthe kernel architecture (either C<LittleEndian> or C<BigEndian>).\n\n=head2 method hardware\n\n    method hardware\n\nInstance method returning the hardware information of the Kernel object.  Dies\nif the hardware information could not be established.\n\n    say $*KERNEL.hardware; # OUTPUT: «x86_64␤»\n\n=head2 method hostname\n\n    method hostname\n\nInstance method returning the hostname of the Kernel object.\n\n=head2 method release\n\n    method release\n\nInstance method returning the release information of the Kernel object.  Dies\nif the release information could not be established.\n\n=head2 method signal\n\n    multi method signal(Kernel:D: Str:D $signal --> Int:D)\n    multi method signal(Kernel:D: Signal:D \\signal --> Int:D)\n    multi method signal(Kernel:D: Int:D \\signal --> Int:D)\n\nInstance method returning the C<Signal> numeric code for a given name for the\nKernel object.\n\n    say $*KERNEL.signal(\"INT\"); # OUTPUT: «2␤»\n\n=head2 method signals\n\nInstance method returning a list of C<Signal>s that are supported by the\nkernel represented by the Kernel object.\n\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Label.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Label\n\n=SUBTITLE Tagged location in the source code\n\n    class Label {}\n\nLabels are used in Raku to tag loops so that you can specify\nthe specific one you want to jump to with L«statements such as\nC<last>|/language/control#LABELs». You can use it to jump out of loops\nand get to outer ones, instead of just exiting the current loop or going\nto the previous statement.\n\n=begin code :skip-test<compile time error>\nUSERS:          # the label\nfor @users -> $u {\n    for $u.pets -> $pet {\n        # usage of a label\n        next USERS if $pet.barks;\n    }\n    say \"None of {$u}'s pets barks\";\n}\nsay USERS.^name;        # OUTPUT: «Label␤»\n=end code\n\nThose labels are objects of type C<Label>, as shown in the last statement.\nLabels can be used in any loop construct, as long as they appear right before\nthe loop statement.\n\n=begin code\nmy $x = 0;\nmy $y = 0;\nmy $t = '';\nA: while $x++ < 2 {\n    $t ~= \"A$x\";\n    B: while $y++ < 2 {\n        $t ~= \"B$y\";\n        redo A if $y++ == 1;\n        last A\n    }\n}\nsay $t; # OUTPUT: «A1B1A1A2␤»\n=end code\n\nPutting them on the line before the loop or the same line is optional. C<Label>s\nmust follow the syntax of\nL<ordinary identifiers|/language/syntax#Ordinary_identifiers>,\nalthough traditionally we\nwill use the latin alphabet in uppercase so that they stand out in the source.\nYou can use, however, other alphabets like here:\n\n    駱駝道: while True {\n      say 駱駝道.name;\n      last 駱駝道;\n    }  # OUTPUT: «駱駝道␤»\n\n=head1 Methods\n\n=head2 method name\n\nNot terribly useful, returns the name of the defined label:\n\n    A: while True {\n      say A.name; # OUTPUT: «A␤»\n      last A;\n    }\n\n=head2 method file\n\nReturns the file the label is defined in.\n\n=head2 method line\n\nReturns the line where the label has been defined.\n\n=head2 method Str\n\nConverts to a string including the name, file and line it's been defined in.\n\n=head2 method next\n\n    method next(Label:)\n\nBegin the next iteration of the loop associated with the label.\n\n    MY-LABEL:\n    for 1..10 {\n        next MY-LABEL if $_ < 5;\n        print \"$_ \";\n    }\n\n    # OUTPUT: «5 6 7 8 9 10 »\n\n=head2 method redo\n\n    method redo(Label:)\n\nRepeat the same iteration of the loop associated with the label.\n\n    my $has-repeated = False;\n\n    MY-LABEL:\n    for 1..10 {\n        print \"$_ \";\n        if $_ == 5 {\n            LEAVE $has-repeated = True;\n            redo MY-LABEL unless $has-repeated;\n        }\n    }\n\n    # OUTPUT: «1 2 3 4 5 5 6 7 8 9 10 »\n\n=head2 method last\n\n    method last(Label:)\n\nTerminate the execution of the loop associated with the label.\n\n    MY-LABEL:\n    for 1..10 {\n        last MY-LABEL if $_ > 5;\n        print \"$_ \";\n    }\n\n    # OUTPUT: «1 2 3 4 5 »\n\n=end pod\n"
  },
  {
    "path": "doc/Type/List.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class List\n\n=SUBTITLE Sequence of values\n\n=for code\nmy class List does Iterable does Positional { }\n\nC<List> stores items sequentially and potentially lazily.\n\nIndexes into lists and arrays start at 0 by default.\n\nYou can assign to list elements if they are containers. Use\nArrays to have every value of the list stored in a container.\n\nC<List> implements L<C<Positional>|/type/Positional> and as such provides support for\nL<subscripts|/language/subscripts>.\n\n=head1 Immutability\n\nLists are immutable objects, i.e., neither the number of elements in a list\nnor the elements themselves can be changed. Thus, it is not possible to use\noperations that change the list structure itself such as L<shift|/routine/shift>,\nL<unshift|/routine/unshift>, L<push|/routine/push>, L<pop|/routine/pop>,\nL<splice|/routine/splice>\nand L<binding|/language/operators#Operators>.\n\n=begin code\n(1, 2, 3).shift;      # Error Cannot call 'shift' on an immutable 'List'\n(1, 2, 3).unshift(0); # Error Cannot call 'unshift' on an immutable 'List'\n(1, 2, 3).push(4);    # Error Cannot call 'push' on an immutable 'List'\n(1, 2, 3).pop;        # Error Cannot call 'pop' on an immutable 'List'\n(1, 2, 3)[0]:delete;  # Error Cannot remove elements from a List\n(1, 2, 3)[0] := 0;    # Error Cannot use bind operator with this left-hand side\n(1, 2, 3)[0] = 0;     # Error Cannot modify an immutable Int\n=end code\n\nA C«List» doesn't L«containerize|/language/containers» its elements, but if\nany element happens to be inside a L«C<Scalar>|/type/Scalar» container then\nthe element's contents can be replaced via an assignment.\n\n=begin code\nmy $a = 'z';\nmy $list = ($a, $, 'b');\n\nsay $list[0].VAR.^name; # OUTPUT: «Scalar␤», containerized\nsay $list[1].VAR.^name; # OUTPUT: «Scalar␤», containerized\nsay $list[2].VAR.^name; # OUTPUT: «Str␤», non-containerized\n\n$list[0] = 'a'; # OK!\n$list[1] = 'c'; # OK!\n$list[2] = 'd'; # Error: Cannot modify an immutable List\n=end code\n\n=head1 Items, flattening and sigils\n\nIn Raku, assigning a C<List> to a scalar variable does not lose information.\nThe difference is that iteration generally treats a list (or any other list-like\nobject, like a L<C<Seq>|/type/Seq> or an L<C<Array>|/type/Array>) inside a scalar as a\nsingle element.\n\n    my $s = (1, 2, 3);\n    for $s { }      # one iteration\n    for $s.list { } # three iterations\n\n    my $t = [1, 2, 3];\n    for $t { }      # one iteration\n    for $t.list { } # three iterations\n\n    my @a = 1, 2, 3;\n    for @a { }      # three iterations\n    for @a.item { } # one iteration\n\nThis operation is called I<itemization> or I<putting in an item context>.\nC<.item> does the job for objects, as well as C<$( ... )> and, on array\nvariables, C<$@a>.\n\nLists generally don't interpolate (flatten) into other lists, except\nwhen they are in list context and the single argument to an\noperation such as C<append>:\n\n    my $a = (1, 2, 3);\n    my $nested = ($a, $a);  # two elements\n\n    my $flat = $nested.map({ .Slip });  # six elements, with explicit Slip\n\n    my @b = <a b>;\n    @b.append: $a.list;     # The array variable @b has 5 elements, because\n                            # the list $a is the sole argument to append\n\n    say @b.elems;           # OUTPUT: «5␤»\n\n    my @c = <a b>;\n    @c.append: $a.list, 7;  # The array variable @c has 4 elements, because\n                            # the list $a wasn't the only argument and thus\n                            # wasn't flattened by the append operation\n\n    say @c.elems;           # OUTPUT: «4␤»\n\n    my @d = <a b>;\n    @d.append: $a;          # The array variable @d has 3 elements, because\n                            # $a is in an item context and as far as append is\n                            # concerned a single element\n\n    say @d.elems;           # OUTPUT: «3␤»\n\nThe same flattening behavior applies to all objects that do the\nL<C<Iterable>|/type/Iterable> role, notably L<C<Hash>|/type/Hash>es:\n\n    my %h = a => 1, b => 2;\n    my @b = %h;   say @b.elems;     # OUTPUT: «2␤»\n    my @c = %h, ; say @c.elems;     # OUTPUT: «1␤»\n    my @d = $%h;  say @d.elems;     # OUTPUT: «1␤»\n\nSlurpy parameters (C<*@a>) flatten non-itemized sublists:\n\n    sub fe(*@flat) { @flat.elems }\n    say fe(<a b>, <d e>);           # OUTPUT: «4␤»\n    say fe(<a b>, <d e>.item);      # OUTPUT: «3␤»\n\nX<|Syntax,() (empty list)>\nThe empty list is created with C<()>. Smartmatching against the empty\nlist will check for the absence of elements.\n\n    my @a;\n    for @a, @a.list, @a.Seq -> \\listoid {\n        say listoid ~~ ()\n    }\n    # OUTPUT: «True␤True␤True␤»\n\nRetrieving values from an empty list will always return L<C<Nil>|/type/Nil>:\n\n    say ()[33.rand]; # OUTPUT: «Nil␤»\n\n\nCoercion to L<C<Bool>|/type/Bool> also indicates if the C<List> got any elements.\n\n    my @a;\n    say [@a.elems, @a.Bool, ?@a]; # OUTPUT: «[0 False False]␤»\n    @a.push: 42;\n    say [@a.elems, @a.Bool, ?@a]; # OUTPUT: «[1 True True]␤»\n    say 'empty' unless @a;        # no output\n\n=head1 Methods\n\n=head2 method ACCEPTS\n\n    multi method ACCEPTS(List:D: $topic)\n\nIf C<$topic> is an L<C<Iterable>|/type/Iterable>, returns C<True> or C<False> based\non whether the contents of the two L<C<Iterable>|/type/Iterable>s match. A\nL<C<Whatever>|/type/Whatever> element in the invocant matches anything in the\ncorresponding position of the C<$topic> L<C<Iterable>|/type/Iterable>. A\nL<C<HyperWhatever>|/type/HyperWhatever> matches any number of any elements,\nincluding no elements:\n\n    say (1, 2, 3)       ~~ (1,  *, 3);  # OUTPUT: «True␤»\n    say (1, 2, 3)       ~~ (9,  *, 5);  # OUTPUT: «False␤»\n    say (1, 2, 3)       ~~ (   **, 3);  # OUTPUT: «True␤»\n    say (1, 2, 3)       ~~ (   **, 5);  # OUTPUT: «False␤»\n    say (1, 3)          ~~ (1, **, 3); # OUTPUT: «True␤»\n    say (1, 2, 4, 5, 3) ~~ (1, **, 3); # OUTPUT: «True␤»\n    say (1, 2, 4, 5, 6) ~~ (1, **, 5); # OUTPUT: «False␤»\n    say (1, 2, 4, 5, 6) ~~ (   **   ); # OUTPUT: «True␤»\n    say ()              ~~ (   **   ); # OUTPUT: «True␤»\n\nIn addition, returns C<False> if either the invocant or C<$topic>\nL<is a lazy|/routine/is-lazy> L<C<Iterable>|/type/Iterable>, unless C<$topic> is the same object\nas the invocant, in which case C<True> is returned.\n\nIf C<$topic> is I<not> an L<C<Iterable>|/type/Iterable>, returns the invocant if\nthe invocant has no elements or its first element is a L<C<Match>|/type/Match>\nobject (this behavior powers C<m:g//> smartmatch), or C<False> otherwise.\n\n=head2 routine list\n\n    multi        list(+list)\n    multi method list(List:D:)\n\nThe method just returns the invocant L<self|/routine/self>. The subroutine\nadheres to the L<single argument rule|/language/functions#Slurpy_conventions>:\nif called with a single argument that is a non-L<itemized|/language/mop#VAR>\nL<C<Iterable>|/type/Iterable> it returns a C<List> based on the argument's\nL<iterator|/routine/iterator>; otherwise it just returns the argument list.\n\nFor example:\n\n    my $tuple = (1, 2);         # an itemized List\n    put $tuple.list.raku;       # OUTPUT: «(1, 2)␤»\n    put list($tuple).raku;      # OUTPUT: «($(1, 2),)␤»\n    put list(|$tuple).raku;     # OUTPUT: «(1, 2)␤»\n\nThe last statement uses the L«C<prefix:<|>>|/language/operators#prefix_|»\noperator to flatten the tuple into an argument list, so it is equivalent to:\n\n    put list(1, 2).raku;        # OUTPUT: «(1, 2)␤»\n\nThere are other ways to list the elements of an itemized single argument. For\nexample, you can L«decontainerize|/routine/<>» the argument or use the L<C<@>\nlist contextualizer|/type/Any#index-entry-@_list_contextualizer>:\n\n=begin code :preamble<my $tuple>\nput list($tuple<>).raku;    # OUTPUT: «(1, 2)␤»\nput list(@$tuple).raku;     # OUTPUT: «(1, 2)␤»\n=end code\n\nNote that converting a type object to a list may not do what you expect:\n\n    put List.list.raku;         # OUTPUT: «(List,)␤»\n\nThis is because the C<.list> candidate accepting a type object as the invocant\nis provided by L<C<Any>|/routine/list#(Any)_method_list>. That candidate returns\na list with one element: the type object self. If you're developing a collection\ntype whose type object should be a valid representation of an empty collection,\nyou may want to provide your own candidate for undefined invocants or override\nthe C<Any:> candidates with an \"only\" method. For example:\n\n=begin code\nmy class LinkedList {\n    has $.value;            # the value stored in this node\n    has LinkedList $.next;  # undefined if there is no next node\n\n    method values( --> Seq:D) {\n        my $node := self;\n        gather while $node {\n            take $node.value;\n            $node := $node.next;\n        }\n    }\n\n    method list( --> List:D) {\n        self.values.list;\n    }\n}\n\nmy LinkedList $nodes;       # an empty linked list\nput $nodes.list.raku;       # OUTPUT: «()␤»\n=end code\n\n=head2 routine elems\n\n    sub    elems($list --> Int:D)\n    method elems(List:D: --> Int:D)\n\nReturns the number of elements in the list.\n\n    say (1,2,3,4).elems; # OUTPUT: «4␤»\n\n=head2 routine end\n\n    sub    end($list --> Int:D)\n    method end(List:D: --> Int:D)\n\nReturns the index of the last element.\n\n    say (1,2,3,4).end; # OUTPUT: «3␤»\n\n=head2 routine keys\n\n    sub    keys($list --> Seq:D)\n    method keys(List:D: --> Seq:D)\n\nReturns a sequence of indexes into the list (e.g.,\nC<0...(@list.elems-1)>).\n\n    say (1,2,3,4).keys; # OUTPUT: «(0 1 2 3)␤»\n\n=head2 routine values\n\n    sub    values($list --> Seq:D)\n    method values(List:D: --> Seq:D)\n\nReturns a sequence of the list elements, in order.\n\n    say (1,2,3,4).^name;        # OUTPUT: «List␤»\n    say (1,2,3,4).values.^name; # OUTPUT: «Seq␤»\n\n=head2 routine kv\n\n    sub    kv($list --> Seq:D)\n    method kv(List:D: --> Seq:D)\n\nReturns an interleaved sequence of indexes and values. For example\n\n    say <a b c>.kv; # OUTPUT: «(0 a 1 b 2 c)␤»\n\n=head2 routine pairs\n\n    sub    pairs($list --> Seq:D)\n    method pairs(List:D: --> Seq:D)\n\nReturns a sequence of pairs, with the indexes as keys and the list values as\nvalues.\n\n    say <a b c>.pairs;   # OUTPUT: «(0 => a 1 => b 2 => c)␤»\n\n=head2 routine antipairs\n\n    method antipairs(List:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> of pairs, with the values as keys and the indexes as\nvalues, i.e. the direct opposite to L<pairs|/type/List#routine_pairs>.\n\n    say <a b c>.antipairs;  # OUTPUT: «(a => 0 b => 1 c => 2)␤»\n\n=head2 routine invert\n\n    method invert(List:D: --> Seq:D)\n\nAssumes every element of the List is a L<C<Pair>|/type/Pair>.  Returns all elements as a\nL<C<Seq>|/type/Seq> of L<C<Pair>|/type/Pair>s where the keys and values have been exchanged.\nIf the value of a L<C<Pair>|/type/Pair> is an L<C<Iterable>|/type/Iterable>, then it will expand the values\nof that L<C<Iterable>|/type/Iterable> into separate pairs.\n\n    my $l = List.new('a' => (2, 3), 'b' => 17);\n    say $l.invert;   # OUTPUT: «(2 => a 3 => a 17 => b)␤»\n\n=head2 routine join\n\n    sub    join($separator, *@list)\n    method join(List:D: $separator = \"\")\n\nTreats the elements of the list as strings by calling\nL<C<.Str>|/type/Mu#method_Str> on each of them, interleaves them with\nC<$separator> and concatenates everything into a single string.\n\nExample:\n\n    say join ', ', <a b c>;             # OUTPUT: «a, b, c␤»\n\nThe method form also allows you to omit the separator:\n\n    say <a b c>.join;               # OUTPUT: «abc␤»\n\nNote that the method form does not flatten sublists:\n\n    say (1, <a b c>).join('|');     # OUTPUT: «1|a b c␤»\n\nThe subroutine form behaves slurpily, flattening all arguments after\nthe first into a single list:\n\n    say join '|', 1, <a b c>;       # OUTPUT: «1|a|b|c␤»\n\nIn this case, the list C«<a b c>» is I<slurped> and flattened, unlike what\nhappens when C<join> is invoked as a method.\n\nIf one of the elements of the list happens to be a L<C<Junction>|/type/Junction>, then C<join>\nwill also return a L<C<Junction>|/type/Junction> with concatenation done as much as possible:\n\n    say (\"a\"|\"b\",\"c\",\"d\").join;     # OUTPUT: «any(acd,bcd)␤»\n\n=head2 routine map\n\n    multi method map(\\SELF: &block)\n    multi        map(&code, +values)\n\nExamples applied to lists are included here for the purpose of illustration.\n\nFor a list, it invokes C<&code> for each element and gathers the return values\nin a sequence and returns it. This happens lazily, i.e. C<&code> is only invoked\nwhen the return values are accessed.Examples:\n\n=for code\nsay ('hello', 1, 22/7, 42, 'world').map: { .^name } # OUTPUT: «(Str Int Rat Int Str)␤»\nsay map *.Str.chars, 'hello', 1, 22/7, 42, 'world'; # OUTPUT: «(5 1 8 2 5)␤»\n\nC<map> inspects the arity of the code object, and tries to pass as many\narguments to it as expected:\n\n    sub b($a, $b) { \"$a before $b\" };\n    say <a b x y>.map(&b).join(', ');   # OUTPUT: «a before b, x before y␤»\n\niterates the list two items at a time.\n\nNote that C<map> does not flatten embedded lists and arrays, so\n\n    ((1, 2), <a b>).map({ .join(',')})\n\npasses C<(1, 2)> and C«<a b>» in turn to the block, leading to a total of\ntwo iterations and the result sequence C<\"1,2\", \"a,b\">.\n\nIf C<&code> is a L<C<Block>|/type/Block> loop phasers will be executed and\nloop control statements will be treated as in loop control flow. Please\nnote that C<return> is executed in the context of its definition. It is\nnot the return statement of the block but the surrounding Routine. Using\na L<C<Routine>|/type/Routine> will also handle loop control statements and\nloop phasers. Any L<C<Routine>|/type/Routine> specific control statement or phaser will\nbe handled in the context of that L<C<Routine>|/type/Routine>.\n\n    sub s {\n        my &loop-block = {\n            return # return from sub s\n        };\n        say 'hi';\n        (1..3).map: &loop-block;\n        say 'oi‽' # dead code\n    };\n    s\n    # OUTPUT: «hi␤»\n\n=head2 method flatmap\n\n    method flatmap(List:D: &code --> Seq:D)\n\nConvenience method, analogous to L<C<.map(&block)>|#routine_map>L<C<.flat>|/type/Iterable#method_flat>.\n\n=head2 method gist\n\n    multi method gist(List:D: --> Str:D)\n\nReturns the string containing the parenthesized \"gist\" of the List,\nB<listing up to the first 100> elements, separated by space, appending an\nellipsis if the List has more than 100 elements. If List\nL«C<is-lazy>|/routine/is-lazy», returns string C«'(...)'»\n\n=begin code\nput (1, 2, 3).gist;   # OUTPUT: «(1 2 3)␤»\nput (1..∞).List.gist; # OUTPUT: «(...)␤»\n\nput (1..200).List.gist;\n# OUTPUT:\n# (1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26\n# 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49\n# 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72\n# 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95\n# 96 97 98 99 100 ...)\n=end code\n\n=head2 routine grep\n\n    sub    grep(Mu $matcher, *@elems, :$k, :$kv, :$p, :$v --> Seq:D)\n    method grep(List:D:  Mu $matcher, :$k, :$kv, :$p, :$v --> Seq:D)\n\nReturns a sequence of elements against which C<$matcher> smartmatches.\nThe elements are returned in the order in which they appear in the original\nlist.\n\nExamples:\n\n    say ('hello', 1, 22/7, 42, 'world').grep: Int;              # OUTPUT: «(1 42)␤»\n    say grep { .Str.chars > 3 }, 'hello', 1, 22/7, 42, 'world'; # OUTPUT: «(hello 3.142857 world)␤»\n\n\nNote that if you want to grep for elements that do not match, you can\nuse a C<none>-L<C<Junction>|/type/Junction>:\n\n    say <a b 6 d 8 0>.grep(none Int);           # OUTPUT: «(a b d)␤»\n    say <a b c d e f>.grep(none /<[aeiou]>/);   # OUTPUT: «(b c d f)␤»\n\nAnother option to grep for elements that do not match a regex is to\nuse a block:\n\n    say <a b c d e f>.grep({! /<[aeiou]>/})     # OUTPUT: «(b c d f)␤»\n\nThe reason the example above works is because a regex in Boolean context applies\nitself to C<$_>. In this case, C<!> boolifies the C«/<[aeiou]>/» regex and\nnegates the result. Smartmatching against a L<C<Callable>|/type/Callable> (in this\ncase a L<C<Block>|/type/Block>) returns the value returned from that callable, so\nthe boolified result of a regex is then used to decide whether the current value\nshould be kept in the result of a grep.\n\nThe optional named parameters C<:k>, C<:kv>, C<:p>, C<:v> provide the same\nfunctionality as on slices:\n\n=item k\n\nOnly return the index values of the matching elements in order.\n\n=item kv\n\nReturn both the index and matched elements in order.\n\n=item p\n\nReturn the index and the matched element as a L<C<Pair>|/type/Pair>, in order.\n\n=item v\n\nOnly return the matched elements (same as not specifying any named parameter\nat all).\n\nExamples:\n\n    say ('hello', 1, 22/7, 42, 'world').grep: Int, :k;\n    # OUTPUT: «(1 3)␤»\n    say grep { .Str.chars > 3 }, :kv, 'hello', 1, 22/7, 42, 'world';\n    # OUTPUT: «(0 hello 2 3.142857 4 world)␤»\n    say grep { .Str.chars > 3 }, :p, 'hello', 1, 22/7, 42, 'world';\n    # OUTPUT: «(0 => hello 2 => 3.142857 4 => world)␤»\n\n=head2 routine first\n\n    sub    first(Mu $matcher, *@elems, :$k, :$kv, :$p, :$end)\n    method first(List:D:  Mu $matcher?, :$k, :$kv, :$p, :$end)\n\nReturns the first item of the list which smartmatches against C<$matcher>,\nreturns L<C<Nil>|/type/Nil> when no values match.  The optional named parameter C<:end>\nindicates that the search should be from the B<end> of the list, rather than\nfrom the start.\n\nExamples:\n\n    say (1, 22/7, 42, 300).first: * > 5;                  # OUTPUT: «42␤»\n    say (1, 22/7, 42, 300).first: * > 5, :end;            # OUTPUT: «300␤»\n    say ('hello', 1, 22/7, 42, 'world').first: Complex;   # OUTPUT: «Nil␤»\n\nThe optional named parameters C<:k>, C<:kv>, C<:p> provide the same\nfunctionality as on slices:\n\n=item k\n\nReturn the index value of the matching element.  Index is always counted from\nthe beginning of the list, regardless of whether the C<:end> named parameter\nis specified or not.\n\n=item kv\n\nReturn both the index and matched element.\n\n=item p\n\nReturn the index and the matched element as a L<C<Pair>|/type/Pair>.\n\nExamples:\n\n    say (1, 22/7, 42, 300).first: * > 5, :k;        # OUTPUT: «2␤»\n    say (1, 22/7, 42, 300).first: * > 5, :p;        # OUTPUT: «2 => 42␤»\n    say (1, 22/7, 42, 300).first: * > 5, :kv, :end; # OUTPUT: «(3 300)␤»\n\nIn method form, the C<$matcher> can be omitted, in which case the first\navailable item (or last if C<:end> is set) will be returned. See also\nL«C<head>|/routine/head» and L«C<tail>|/routine/tail» methods.\n\n=head2 method head\n\n    multi method head(Any:D:) is raw\n    multi method head(Any:D: Callable:D $w)\n    multi method head(Any:D: $n)\n\nThis method is directly inherited from L<C<Any>|/type/Any>, and it returns the B<first> C<$n>\nitems of the list, an empty list if C<$n> <= 0, or the first element with no\nargument. The version that takes a L<C<Callable>|/type/Callable> uses a L<C<WhateverCode>|/type/WhateverCode> to specify\nall elements, starting from the first, but the last ones.\n\nExamples:\n\n    say <a b c d e>.head ;     # OUTPUT: «a␤»\n    say <a b c d e>.head(2);   # OUTPUT: «(a b)␤»\n    say <a b c d e>.head(*-3); # OUTPUT: «(a b)␤»\n\n=head2 method tail\n\n    multi method tail(List:D:)\n    multi method tail(List:D: $n --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> containing the B<last> C<$n> items of the list.\nReturns an empty L<C<Seq>|/type/Seq> if C<$n> <= 0.  Defaults to the last element if\nno argument is specified. Throws an exception if the list is lazy.\n\nExamples:\n\n=for code\nsay <a b c d e>.tail(*-3);# OUTPUT: «(d e)␤»\nsay <a b c d e>.tail(2);  # OUTPUT: «(d e)␤»\nsay <a b c d e>.tail;     # OUTPUT: «e␤»\n\nIn the first case, C<$n> is taking the shape of a L<C<WhateverCode>|/type/WhateverCode> to indicate\nthe number of elements from the beginning that will be excluded. C<$n> can be\neither a Callable, in which case it will be called with the value C<0>, or\nanything else that can be converted to a number, in which case it will use\nthat as the number of elements in the output L<C<Seq>|/type/Seq>.\n\n    say <a b c d e>.tail( { $_ - 2 } ); # OUTPUT: «(c d e)␤»\n\n=head2 routine categorize\n\n    multi method categorize()\n    multi method categorize(Whatever)\n    multi method categorize($test, :$into!, :&as)\n    multi method categorize($test, :&as)\n    multi        categorize($test, +items, :$into!, *%named )\n    multi        categorize($test, +items, *%named )\n\nThese methods are directly inherited from L<C<Any>|/type/Any>; see\nL<C<Any.categorize>|/type/Any#routine_categorize> for more examples.\n\nThis routine transforms a list of values into a hash representing the\ncategorizations of those values according to C<$test>, which is called once for\nevery element in the list; each hash key represents one possible categorization\nfor one or more of the incoming list values, and the corresponding hash value\ncontains an array of those list values categorized by the C<$test>, acting like\na mapper, into the category of the associated key.\n\nNote that, unlike L<classify|/routine/classify>, which assumes that the return\nvalue of the mapper is a single value, C<categorize> always assumes that the\nreturn value of the mapper is a list of categories that are appropriate to the\ncurrent value.\n\nExample:\n\n    sub mapper(Int $i) returns List {\n        $i %% 2 ?? 'even' !! 'odd',\n        $i.is-prime ?? 'prime' !! 'not prime'\n    }\n    say categorize &mapper, (1, 7, 6, 3, 2);\n    # OUTPUT: «{even => [6 2], not prime => [1 6], odd => [1 7 3], prime => [7 3 2]}␤»\n\n=head2 routine classify\n\n    multi method classify($test, :$into!, :&as)\n    multi method classify($test, :&as)\n    multi        classify($test, +items, :$into!, *%named )\n    multi        classify($test, +items, *%named )\n\nTransforms a list of values into a hash representing the classification\nof those values; each hash key represents the classification for one or\nmore of the incoming list values, and the corresponding hash value\ncontains an array of those list values classified into the category of\nthe associated key. C<$test> will be an expression that will produce the\nhash keys according to which the elements are going to be classified.\n\nExample:\n\n    say classify { $_ %% 2 ?? 'even' !! 'odd' }, (1, 7, 6, 3, 2);\n    # OUTPUT: «{even => [6 2], odd => [1 7 3]}␤»\n    say ('hello', 1, 22/7, 42, 'world').classify: { .Str.chars };\n    # OUTPUT: «{1 => [1], 2 => [42], 5 => [hello world], 8 => [3.142857]}␤»\n\nIt can also take C<:as> as a named parameter, transforming the value\nbefore classifying it:\n\n    say <Innie Minnie Moe>.classify( { $_.chars }, :as{ lc $_ });\n    # OUTPUT: «{3 => [moe], 5 => [innie], 6 => [minnie]}␤»\n\nThis code is classifying by number of characters, which is the\nexpression that has been passed as C<$test> parameter, but the C<:as>\nblock lowercases it before doing the transformation. The named parameter\nC<:into> can also be used to classify I<into> a newly defined variable:\n\n    <Innie Minnie Moe>.classify( { $_.chars }, :as{ lc $_ }, :into( my %words{Int} ) );\n    say %words; # OUTPUT: «{3 => [moe], 5 => [innie], 6 => [minnie]}␤»\n\nWe are declaring the scope of C<%words{Int}> on the fly, with keys that\nare actually integers; it gets created with the result of the\nclassification.\n\n=head2 method Bool\n\n    method Bool(List:D: --> Bool:D)\n\nReturns C<True> if the list has at least one element, and C<False>\nfor the empty list.\n\n    say ().Bool;  # OUTPUT: «False␤»\n    say (1).Bool; # OUTPUT: «True␤»\n\n=head2 method Str\n\n    method Str(List:D: --> Str:D)\n\nStringifies the elements of the list and joins them with spaces\n(same as C<.join(' ')>).\n\n    say (1,2,3,4,5).Str; # OUTPUT: «1 2 3 4 5␤»\n\n=head2 method Int\n\n    method Int(List:D: --> Int:D)\n\nReturns the number of elements in the list (same as C<.elems>).\n\n    say (1,2,3,4,5).Int; # OUTPUT: «5␤»\n\n=head2 method Numeric\n\n    method Numeric(List:D: --> Int:D)\n\nReturns the number of elements in the list (same as C<.elems>).\n\n    say (1,2,3,4,5).Numeric; # OUTPUT: «5␤»\n\n=head2 method Capture\n\n    method Capture(List:D: --> Capture:D)\n\nReturns a L<C<Capture>|/type/Capture> where each L<C<Pair>|/type/Pair>, if any, in the\n<C<List> has been converted to a named argument (with the\nL<key|/type/Pair#method_key> of the L<C<Pair>|/type/Pair> stringified). All other\nelements in the C<List> are converted to positional arguments in the order they\nare found, i.e. the first non pair item in the list becomes the first positional\nargument, which gets index C<0>, the second non pair item becomes the second\npositional argument, getting index C<1> etc.\n\n    my $list = (7, 5, a => 2, b => 17);\n    my $capture = $list.Capture;\n    say $capture.keys;                                # OUTPUT: «(0 1 a b)␤»\n    my-sub(|$capture);                                # OUTPUT: «7, 5, 2, 17␤»\n\n    sub my-sub($first, $second, :$a, :$b) {\n        say \"$first, $second, $a, $b\"\n    }\n\nA more advanced example demonstrating the returned L<C<Capture>|/type/Capture> being matched\nagainst a L<C<Signature>|/type/Signature>.\n\n    my $list = (7, 5, a => 2, b => 17);\n    say so $list.Capture ~~ :($ where * == 7,$,:$a,:$b); # OUTPUT: «True␤»\n\n    $list = (8, 5, a => 2, b => 17);\n    say so $list.Capture ~~ :($ where * == 7,$,:$a,:$b); # OUTPUT: «False␤»\n\n=head2 routine pick\n\n    multi        pick($count, *@list --> Seq:D)\n    multi method pick(List:D: $count --> Seq:D)\n    multi method pick(List:D: --> Mu)\n    multi method pick(List:D: Callable $calculate --> Seq:D)\n\nIf C<$count> is supplied: Returns C<$count> elements chosen at random\nand without repetition from the invocant. If C<*> is passed as C<$count>,\nor C<$count> is greater than or equal to the size of the list, then all\nelements from the invocant list are returned in a random sequence; i.e. they\nare returned shuffled.\n\nIn I<method> form, if C<$count> is omitted: Returns a single random item from\nthe list, or Nil if the list is empty\n\nExamples:\n\n    say <a b c d e>.pick;           # OUTPUT: «b␤»\n    say <a b c d e>.pick: 3;        # OUTPUT: «(c a e)␤»\n    say <a b c d e>.pick: *;        # OUTPUT: «(e d a b c)␤»\n\nAs of the 2021.06 release of the Rakudo compiler, it is also possible to\nspecify C<**> (aka L<C<HyperWhatever>|/type/HyperWhatever>) as the count.\n\nIn that case, C<.pick> will start picking again on the original list\nafter it has been exhausted, again and again, indefinitely.\n\n    say <a b c>.pick(**).head(10);  # OUTPUT: «((a c b c a b b c a b))␤»\n\n=head2 routine roll\n\n    multi        roll($count, *@list --> Seq:D)\n    multi method roll(List:D: $count --> Seq:D)\n    multi method roll(List:D: --> Mu)\n\nIf C<$count> is supplied: Returns a sequence of C<$count> elements, each\nrandomly selected from the list. Each random choice is made independently, like\na separate die roll where each die face is a list element. If C<*> is passed as\nC<$count> returns a lazy, infinite sequence of randomly chosen elements from the\noriginal list.\n\nIf C<$count> is omitted: Returns a single random item from the list, or\nNil if the list is empty\n\nExamples:\n\n    say <a b c d e>.roll;       # 1 random letter\n    say <a b c d e>.roll: 3;    # 3 random letters\n    say roll 8, <a b c d e>;    # 8 random letters\n\n    my $random-digits := (^10).roll(*);\n    say $random-digits[^15];    # 15 random digits\n\n=head2 routine eager\n\n    multi method eager(List:D: --> List:D)\n\nEvaluates all elements in the C<List> eagerly, and returns them as a C<List>.\n\n    my  \\ll = (lazy 1..5).cache;\n\n    say ll[];     # OUTPUT: «(...)␤»\n    say ll.eager  # OUTPUT: «(1 2 3 4 5)␤»\n\n=head2 routine reverse\n\n    multi        reverse(*@list  --> Seq:D)\n    multi method reverse(List:D: --> Seq:D)\n\nReturns a L«C<Seq>|/type/Seq» with the same elements in reverse order.\n\nNote that C<reverse> always refers to reversing elements of a list;\nto reverse the characters in a string, use L<flip|/routine/flip>.\n\nExamples:\n\n    say <hello world!>.reverse;     # OUTPUT: «(world! hello)␤»\n    say reverse ^10;                # OUTPUT: «(9 8 7 6 5 4 3 2 1 0)␤»\n\n=head2 routine rotate\n\n    multi        rotate(@list,  Int:D $n = 1 --> Seq:D)\n    multi method rotate(List:D: Int:D $n = 1 --> Seq:D)\n\nReturns a L«C<Seq>|/type/Seq» with the list elements rotated to the left\nwhen C<$n> is positive or to the right otherwise.\n\nExamples:\n\n    say <a b c d e>.rotate(2);   # OUTPUT: (c d e a b)\n    say <a b c d e>.rotate(-1);  # OUTPUT: (e a b c d)\n\nB<Note>: Before Rakudo release 2020.06 a new C<List> was returned instead\nof a L<C<Seq>|/type/Seq>.\n\n=head2 routine sort\n\n    multi        sort(*@elems      --> Seq:D)\n    multi        sort(&custom-routine-to-use, *@elems --> Seq:D)\n    multi method sort(List:D:      --> Seq:D)\n    multi method sort(List:D: &custom-routine-to-use  --> Seq:D)\n\nSorts the list, smallest element first. By default\nL«C«infix:<cmp>»|/routine/cmp» is used for comparing list elements.\n\nIf C<&custom-routine-to-use> is provided, and it accepts two arguments,\nit is invoked for pairs of list elements, and should return\nC<Order::Less>, C<Order::Same> or C<Order::More>.\n\nIf C<&custom-routine-to-use> accepts only one argument, the list\nelements are sorted according to C<<custom-routine-to-use($a) cmp\ncustom-routine-to-use($b)>>. The return values of\nC<&custom-routine-to-use> are cached, so that C<&custom-routine-to-use>\nis only called once per list element.\n\nExamples:\n\n    say (3, -4, 7, -1, 2, 0).sort;                  # OUTPUT: «(-4 -1 0 2 3 7)␤»\n    say (3, -4, 7, -1, 2, 0).sort: *.abs;           # OUTPUT: «(0 -1 2 3 -4 7)␤»\n    say (3, -4, 7, -1, 2, 0).sort: { $^b leg $^a }; # OUTPUT: «(7 3 2 0 -4 -1)␤»\n\nAdditionally, if C<&custom-routine-to-use> returns a C<List>, elements\nwill be sorted based upon multiple values with subsequent values in the\nC<List> being used to break the tie if the comparison between the prior\nelements evaluate to C<Order::Same>.\n\n    my @resistance = (\n        %( first-name => 'Kyle',  last-name => 'Reese'  ),\n        %( first-name => 'Sarah', last-name => 'Connor' ),\n        %( first-name => 'John',  last-name => 'Connor' ),\n    );\n    .say for @resistance.sort: { .<last-name>, .<first-name> };\n\n    #`(\n    OUTPUT:\n      {first-name => John, last-name => Connor}\n      {first-name => Sarah, last-name => Connor}\n      {first-name => Kyle, last-name => Reese}\n    )\n\nThis sorting can be based on characteristics of a single element:\n\n=begin code\nsay <ddd aaa bbb bb ccc c>.sort( {.chars, .Str} );\n# OUTPUT: «(c bb aaa bbb ccc ddd)␤»\n=end code\n\nIn this case, elements of the array are sorted in ascending order\naccording first to the string length (C<.chars>) and second to the\nactual alphabetical order C<.Str>) if the length is exactly the same.\n\nAny number of criteria can be used in this:\n=begin code\nsay <01 11 111 2 20 02>.sort( { .Int, .comb.sum, .Str } );\n# OUTPUT: «(01 02 2 11 20 111)␤»\n=end code\n\nCalling the C<sort> sub without any arguments has become a runtime error as of\nrelease 2022.07 of the Rakudo compiler:\n\n=begin code\nsort;   # ERROR: «Must specify something to sort␤»\n=end code\n\nAs of release 2023.08 of the Rakudo compiler it is also possible to specify\na C<:k> named argument.  This will cause the result to be a list of\nB<indices> of the sorting process.\n\n    say <a c b d e>.sort(:k); # OUTPUT: «(0 2 1 3 4)␤»\n    say sort <a c b d e>, :k; # OUTPUT: «(0 2 1 3 4)␤»\n\n=head2 routine reduce\n\n    multi method reduce(Any:D: &with)\n    multi        reduce (&with, +list)\n\nReturns a single \"combined\" value from a list of arbitrarily many values, by\niteratively applying a routine which knows how to combine I<two> values. In\naddition to the subroutine and the list, an initial value can be provided to\ninitialize the reduction, which ends up being the return value if the list is\nempty. Thus C<reduce f, init, list> combines the elements of the list from left\nto right, as is shown in the following pseudocode:\n\n=for code :lang<Pseudo>\nresult0 = init\nresult1 = f(result0, list[0])\nresult2 = f(result1, list[1])\n...\nresultn = f(resultn-1, list[n-1])\n\nC<resultn> is the final result for an n-element list.\n\n    say reduce &infix:<+>, (1, 2, 3); # OUTPUT: «6␤»\n    say (1, 2, 3).reduce: &infix:<+>; # OUTPUT: «6␤»\n    say reduce &max, (5, 9, 12, 1);   # OUTPUT: «12␤»\n\nIf C<list> contains just a single element, the operator is applied to that\nsingle element if possible; if not, it returns the element itself.\n\n    say reduce &infix:<->, (10,);     # OUTPUT: «10␤»\n\nWhen the list contains no elements, an exception is thrown, unless C<&with>\nis an I<operator> with a known identity value (e.g., the identity value of\nC«infix:<+>» is 0). For this reason, you're advised to prefix the input list\nwith an initial value (or explicit identity value):\n\n    my \\strings = \"One good string!\", \"And one another good string!\";\n    say reduce { $^a ~ $^b }, '', |strings;               # like strings.join\n\n    my \\numbers = 1, 2, 3, 4, 5;\n    say reduce { $^a > $^b ?? $^a !! $^b }, 0, |numbers; # like numbers.max\n\n    sub count-and-sum-evens( (Int \\count, Int \\sum), Int \\x ) {\n        x %% 2 ?? (count+1, sum+x) !! (count, sum)\n    }\n\n    say reduce &count-and-sum-evens, (0, 0), |numbers;    # OUTPUT: «(2 6)␤»\n\nIn the last example, since C<reduce> only supports one initial value we use a\nC<List> with two values, which is by itself a single value. The\nC<count-and-sum-evens> subroutine takes two positional values: a\nC<List> of two L<C<Int>|/type/Int>s and an L<C<Int>|/type/Int>, and return a C<List> storing the count\nand sum of the even integers accumulated.\n\nIf C<&with> is the code object of an I<operator>, its\ninherent identity value and associativity is respected - in other words,\nC<(VAL1, VAL2, VAL3).reduce(&infix:<OP>)> is the same as C<VAL1 OP VAL2 OP VAL3>\neven for operators which aren't left-associative:\n\n    # Raise 2 to the 81st power, because 3 to the 4th power is 81\n    (2,3,4).reduce(&infix:<**>).lsb.say;  # OUTPUT: «81␤»\n    (2**(3**4)).lsb.say;                  # OUTPUT: «81␤»\n    (2**3**4).lsb.say;                    # OUTPUT: «81␤»\n\n    # Subtract 4 from -1, because 2 minus 3 is -1\n    (2,3,4).reduce(&infix:<->).say;       # OUTPUT: «-5␤»\n    ((2-3)-4).say;                        # OUTPUT: «-5␤»\n    (2-3-4).say;                          # OUTPUT: «-5␤»\n\nSince reducing with an infix operator is a common thing to do, the\nL<reduction metaoperator|/language/operators#Reduction_metaoperators> C<[ ]>\nprovides a syntactic shortcut. Thus, instead of passing the operator's code\nobject to C<reduce>, just pass the operator directly to C<[ ]>. To use a\nuser-defined subroutine instead, provide an additional layer of square brackets\naround the subroutine's code object:\n\n    say [*] (1, 2, 3, 4);       # OUTPUT: «24␤»\n    say [min] (4, 2, 1, 3);     # OUTPUT: «1␤»\n\n    sub mult { $^a * $^b };\n    say [[&mult]] (1, 2, 3, 4); # OUTPUT: «24␤»\n\nSemantically, all the following do the same thing:\n\n    my \\numbers = 1, 2, 3, 4, 5;\n    say reduce { $^a + $^b }, 0, |numbers;\n    say reduce * + *, 0, |numbers;\n    say reduce &[+], numbers; # operator does not need explicit identity value\n    say [+] numbers;\n\nSince C<reduce> is an implicit loop that iterates over with its I<reducing> subroutine,\nit responds to C<next>, C<last> and C<redo> statements inside C<&with>:\n\n    sub last-after-seven { last if $^a > 7; $^a + $^b };\n    say (2, 3, 4, 5).reduce: &last-after-seven; # OUTPUT: «9␤»\n\nWhether C<reduce> accumulates the elements starting from the left or from the right\ndepends on the operator. In the functional programming world, this operation is\ngenerally called a L<fold|https://en.wikipedia.org/wiki/Fold_%28higher-order_function%29#Folds_on_lists>.\nWith a right-associative operator it is a I<right fold>, otherwise (and usually)\nit is a I<left fold>. In Raku, you can specify the associativity of an operator\nwith the L<C«is assoc»|/language/functions#index-entry-is_assoc> trait.\n\n    sub infix:<foo>($a, $b) is assoc<right> { \"($a, $b)\" }\n    say [foo] 1, 2, 3, 4; # OUTPUT: «(1, (2, (3, 4)))␤»\n\n    sub infix:<bar>($a, $b) is assoc<left> { \"($a, $b)\" }\n    say [bar] 1, 2, 3, 4; # OUTPUT: «(((1, 2), 3), 4)␤»\n\nB<Practical example 1:> In this example, we generate a random-ish math\nformula (e.g., \"(4 + ((3 * x) + 11) / 6))\") using C<reduce>.\n\n    my @ops = [Z] (<+ - * />, 1..20)».roll(4);\n\n    say ('x', |@ops).reduce: -> $formula, [$op, $number] {\n        Bool.pick ?? \"($formula $op $number)\"\n                  !! \"($number $op $formula)\"\n    }\n\nB<Practical example 2:> Suppose we have a polynomial represented as a list of\ninteger coefficients, c[n-1], c[n-2], ..., c[0], where c[i] is the coefficient\nof xi. We can evaluate it using C<map> and C<reduce> as follows:\n\n    sub evaluate(List:D \\c where c.all ~~ Int, Rat:D \\x --> Rat:D) {\n        my \\xi = (c.elems ^... 0).map: -> \\i { x ** i }; # [x^(n-1), ..., x^0]\n        my \\axi = [+] c Z* xi;                           # [c[n-1]*x^(n-1), ..., c[*]x^0]\n        [+] axi;                                         # sum of axi\n    }\n\n    my \\c = 2, 3, 1;       # 2x² + 3x + 1\n    say evaluate c, 3.0;   # OUTPUT: «28␤»\n    say evaluate c, 10.0;  # OUTPUT: «231␤»\n\n=head2 routine produce\n\n    multi        produce(&with, *@values)\n    multi method produce(List:D: &with)\n\nGenerates a list of all intermediate \"combined\" values along with the final\nresult by iteratively applying a function which knows how to combine I<two>\nvalues.\n\nIf C<@values> contains just a single element, a list containing that element\nis returned immediately. If it contains no elements, an exception is thrown,\nunless C<&with> is an I<operator> with a known identity value.\n\nIf C<&with> is the function object of an I<operator>, its\ninherent identity value and associativity is respected - in other words,\nC<(VAL1, VAL2, VAL3).produce(&[OP])> is the same as C<VAL1 OP VAL2 OP VAL3> even\nfor operators which aren't left-associative:\n\n    # Raise 2 to the 81st power, because 3 to the 4th power is 81\n    [2,3,4].produce(&[**]).say;        # OUTPUT: «(4 81 2417851639229258349412352)␤»\n    say produce &[**], (2,3,4);        # OUTPUT: «(4 81 2417851639229258349412352)␤»\n    say [\\**] (2,3,4);                 # OUTPUT: «(4 81 2417851639229258349412352)␤»\n\n    # Subtract 4 from -1, because 2 minus 3 is -1\n    [2,3,4].produce(&[-]).say;         # OUTPUT: «(2 -1 -5)␤»\n    say produce &[-], (2,3,4);         # OUTPUT: «(2 -1 -5)␤»\n    say [\\-] (2,3,4);                  # OUTPUT: «(2 -1 -5)␤»\n\nA triangle metaoperator C<[\\ ]> provides a syntactic shortcut for\nproducing with an infix operator:\n\n    # The following all do the same thing...\n    my @numbers = (1,2,3,4,5);\n    say produce { $^a + $^b }, @numbers;\n    say produce * + *, @numbers;\n    say produce &[+], @numbers; # operator does not need explicit identity\n    say [\\+] @numbers;          # most people write it this way\n\nThe visual picture of a triangle C<[\\> is not accidental. To produce a\ntriangular list of lists, you can use a \"triangular comma\":\n\n    [\\,] 1..5;\n    # (\n    # (1)\n    # (1 2)\n    # (1 2 3)\n    # (1 2 3 4)\n    # (1 2 3 4 5)\n    # )\n\nSince C<produce> is an implicit loop, it responds to C<next>, C<last> and\nC<redo> statements inside C<&with>:\n\n    say (2,3,4,5).produce: { last if $^a > 7; $^a + $^b }; # OUTPUT: «(2 5 9)␤»\n\n=head2 routine combinations\n\n    multi        combinations($from, $of = 0..*             --> Seq:D)\n    multi method combinations(List:D: Int() $of             --> Seq:D)\n    multi method combinations(List:D: Iterable:D $of = 0..* --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> with all C<$of>-combinations of the invocant list.\nC<$of> can be a numeric L<C<Range>|/type/Range>, in which case combinations of the\nrange of item numbers it represents will be returned (i.e. C<2.6 .. 4> will\nreturn 2-, 3-, and 4-item combinations). Otherwise, C<$of> is coerced to an\nL<C<Int>|/type/Int>.\n\n    .say for <a b c>.combinations: 2;\n    # OUTPUT:\n    # (a b)\n    # (a c)\n    # (b c)\n\nAbove, there are three possible ways to combine the 2-items lists from the\noriginal list, which is what we receive in the output. See\nL<permutations|/routine/permutations> if you want permutations instead of\ncombinations.\n\nWith L<C<Range>|/type/Range> argument, we get both three 2-item combinations and\none 3-item combination:\n\n    .say for <a b c>.combinations: 2..3;\n    # OUTPUT:\n    # (a b)\n    # (a c)\n    # (b c)\n    # (a b c)\n\nIf C<$of> is negative or is larger than there are items in the given list, an\nempty list will be returned. If C<$of> is zero, a 1-item list containing an\nempty list will be returned (there's exactly 1 way to pick no items).\n\nThe subroutine form is equivalent to the method form called on the first\nargument (C<$from>), with the exception that if C<$from> is not an\nL<C<Iterable>|/type/Iterable>, it gets coerced to an L<C<Int>|/type/Int> and combinations are\nmade from a L<C<Range>|/type/Range> constructed with C<0..^$from> instead:\n\n    .say for combinations 3, 2\n    # OUTPUT:\n    # (0 1)\n    # (0 2)\n    # (1 2)\n\nB<Note:> some implementations may limit the maximum value of\nnon-L<C<Iterable>|/type/Iterable> C<$from>. On Rakudo, 64-bit systems have a limit\nof C<2³¹-1> and 32-bit systems have a limit of C<2²⁸-1>.\n\n=head2 routine permutations\n\n    multi        permutations(Int()    $from --> Seq:D)\n    multi        permutations(Iterable $from --> Seq:D)\n    multi method permutations(List:D:        --> Seq:D)\n\nReturns all possible permutations of a list as a L<C<Seq>|/type/Seq> of lists:\n\n    .say for <a b c>.permutations;\n    # OUTPUT:\n    # (a b c)\n    # (a c b)\n    # (b a c)\n    # (b c a)\n    # (c a b)\n    # (c b a)\n\nC<permutations> treats all elements as unique, thus C<(1, 1, 2).permutations>\nreturns a list of 6 elements, even though there are only three distinct\npermutations, due to first two elements being the same.\n\nThe subroutine form behaves the same as the method form, computing permutations\nfrom its first argument C<$from>. If C<$from> is not an\nL<C<Iterable>|/type/Iterable>, coerces C<$from> to an L<C<Int>|/type/Int> and picks from a\nL<C<Range>|/type/Range> constructed with C<0..^$from>:\n\n    .say for permutations 3;\n    # OUTPUT:\n    # (0 1 2)\n    # (0 2 1)\n    # (1 0 2)\n    # (1 2 0)\n    # (2 0 1)\n    # (2 1 0)\n\n=head2 routine rotor\n\n    method rotor(+@cycle, Bool() :$partial --> Seq:D)\n\nReturns a sequence of lists, where each sublist is made up of elements of the\ninvocant.\n\nIn the simplest case, C<@cycle> contains just one integer, in which case the\ninvocant list is split into sublists with as many elements as the integer\nspecifies. If C<:$partial> is True, the final chunk is included even if it\ndoesn't satisfy the length requirement:\n\n    say ('a'..'h').rotor(3).join('|');              # OUTPUT: «a b c|d e f␤»\n    say ('a'..'h').rotor(3, :partial).join('|');    # OUTPUT: «a b c|d e f|g h␤»\n\nIf the element of C<@cycle> is a L<C<Pair>|/type/Pair> instead, the key of the\npair specifies the length of the return sublist, and the value the gap between\nsublists; negative gaps produce overlap:\n\n    say ('a'..'h').rotor(2 => 1).join('|');         # OUTPUT: «a b|d e|g h␤»\n    say ('a'..'h').rotor(3 => -1).join('|');        # OUTPUT: «a b c|c d e|e f g␤»\n\nIf C<@cycle> contains more than element, C<rotor> cycles through it to find\nthe number of elements for each sublist:\n\n    say ('a'..'h').rotor(2, 3).join('|');           # OUTPUT: «a b|c d e|f g␤»\n    say ('a'..'h').rotor(1 => 1, 3).join('|');      # OUTPUT: «a|c d e|f␤»\n\nCombining multiple cycles and C<:partial> also works:\n\n    say ('a'..'h').rotor(1 => 1, 3 => -1, :partial).join('|');\n    # OUTPUT: «a|c d e|e|g h␤»\n\nSee L<this blog post for more elaboration on rotor|http://blogs.perl.org/users/zoffix_znet/2016/01/perl-6-rotor-the-king-of-list-manipulation.html>.\n\nFrom language version 6.e onward, there is also a L<subroutine|/language/functions#Subroutines> C<rotor>\n(early implementation exists in Rakudo compiler 2022.02+):\n\n=for code\nmulti rotor(Int:D $batch, \\thing, Bool() :$partial --> Seq:D)\n=for code :skip-test<actual sig is **@cycle-and-thing but only due to Rakudo limitation>\nmulti rotor(**@cycle, \\thing, Bool() :$partial --> Seq:D)\n\nTechnically, having a L<slurpy|/language/signatures#Slurpy_parameters> C<**@cycle>\nbefore the positional parameter C<\\thing> is not possible,\nso the actual signature of the second multi is different in Rakudo.\nIn practice, however, things work as you would expect from the signatures given here:\n\n=for code :solo :preamble<use v6.e.PREVIEW;>\nsay rotor(3, 'a'..'h').join('|');             # OUTPUT: «a b c|d e f␤»\nsay rotor(3, 'a'..'h', :partial).join('|');   # OUTPUT: «a b c|d e f|g h␤»\nsay rotor(2 => 1, 'a'..'h').join('|');        # OUTPUT: «a b|d e|g h␤»\nsay rotor(3 => -1, 'a'..'h').join('|');       # OUTPUT: «a b c|c d e|e f g␤»\nsay rotor(1 => 1, 3 => -1, 'a'..'h', :partial).join('|');\n# OUTPUT: «a|c d e|e|g h␤»\n\n=head2 method batch\n\n    multi method batch(Int:D $batch --> Seq)\n    multi method batch(Int:D :$elems --> Seq)\n\nReturns a sequence of lists, wherein each list with the exception of the last\none is guaranteed to comprise a number of elements equal to the batch size\nspecified by C<$batch> or C<$elems>, respectively. If the invocant has a number\nof elements that is not an integer multiple of the batch size, the last list in\nthe returned sequence will contain any remaining elements and thus have fewer\nthan C<$batch> or C<$elems> elements. Accordingly, C<.batch($batch)> is\nshorthand for C<.rotor($batch, :partial)>.\n\n=head2 routine cross\n\n    sub cross(+@e, :&with --> Seq:D)\n\nComputes the cross-product of two or more lists or L<C<Iterable>|/type/Iterable>s.\nThis returns a sequence of lists where the first item in each list is an item\nfrom the first iterable, the second is from the second given iterable, etc.\nEvery item will be paired with every other item in all the other lists.\n\n    say cross(<a b c>, <d e f>).map(*.join).join(\",\")\n    # OUTPUT: «ad,ae,af,bd,be,bf,cd,ce,cf␤»\n\nThe C<cross> routine has an infix synonym as well, named L«C<X>|/language/operators#infix_X».\n\n    say (<a b c> X <d e f>).map(*.join).join(\",\")\n    # output is the same as the previous example\n\nIf the optional C<with> parameter is passed, it is used as a reduction operation\nto apply to each of the cross product items.\n\n    say cross([1, 2, 3], [4, 5, 6], :with(&infix:<*>)).join(\",\");\n    # OUTPUT: «4,5,6,8,10,12,12,15,18␤»\n\nThe C<X> operator can be combined with another operator as a\nmetaoperator to perform a reduction as well:\n\n    say ([1, 2, 3] X* [4, 5, 6]).join(\",\")\n    # same output as the previous example\n\n=head2 routine zip\n\n    sub zip(+@e, :&with --> Seq:D)\n\nBuilds a 'list of lists', returned as a sequence, from multiple input lists or\nother L<C<Iterable>|/type/Iterable>s.\n\nC<zip> iterates through each of the input lists synchronously, 'Zipping' them\ntogether, so that elements are grouped according to their input list index, in\nthe order that the lists are provided.\n\n    say zip(<a b c>, <d e f>, <g h i>);\n    # OUTPUT: «((a d g) (b e h) (c f i))␤»\n\nC<zip> has an infix synonym, the L«C<Z> operator|/language/operators#infix_Z».\n\n    say <a b c> Z <d e f> Z <g h i>;                   # same output\n\n\nC<zip> can provide input to a for loop :\n\n    for <a b c> Z <d e f> Z <g h i> -> [$x,$y,$z] {say ($x,$y,$z).join(\",\")}\n    # OUTPUT: «a,d,g␤b,e,h␤c,f,i␤»\n\n, or more succinctly:\n\n    say .join(\",\") for zip <a b c>, <d e f>, <g h i>;  # same output\n\nNote, that if the input lists have an unequal number of elements, then\nC<zip> terminates once the shortest input list is exhausted, and trailing\nelements from longer input lists are discarded.\n\n    say <a b c> Z <d e f m n o p> Z <g h i>;\n    # ((a d g) (b e h) (c f i))\n\nIn cases where data clipping is possible, but undesired, then consider using\nL<roundrobin|/routine/roundrobin> instead of C<zip>.\n\nThe optional C<with> parameter will additionally reduce the zipped lists. For\nexample, the following multiplies corresponding elements together to return a\nsingle list of products.\n\n    .say for zip <1 2 3>, [1, 2, 3], (1, 2, 3), :with(&infix:<*>);\n    # OUTPUT: «1␤8␤27␤»\n\nThe C<Z> form can also be used to perform reduction by implicitly\nsetting the C<with> parameter with a metaoperator :\n\n    .say for <1 2 3> Z* [1, 2, 3] Z* (1, 2, 3);        # same output\n\n=head2 routine roundrobin\n\n    sub roundrobin(+list-of-lists --> Seq)\n\nBuilds a 'list of lists', returned as a sequence, from multiple input lists or\nother L<C<Iterable>|/type/Iterable>s. C<roundrobin> returns an identical result to\nthat of L<zip|/type/List#routine_zip>, except when the input lists are allowed\nto have an unequal number of elements.\n\n    say roundrobin <a b c>, <d e f>, <g h i>;\n    # OUTPUT: «((a d g) (b e h) (c f i))␤»\n\n    say .join(\",\") for roundrobin([1, 2], [2, 3], [3, 4]);\n    # OUTPUT: «1,2,3␤2,3,4␤»\n\nC<roundrobin> does not terminate once one or more of the input lists become\nexhausted, but proceeds until all elements from all lists have been processed.\n\n    say roundrobin <a b c>, <d e f m n o p>, <g h i j>;\n    # OUTPUT: «((a d g) (b e h) (c f i) (m j) (n) (o) (p))␤»\n\n    say .join(\",\") for roundrobin([1, 2], [2, 3, 57, 77], [3, 4, 102]);\n    # OUTPUT: «1,2,3␤2,3,4␤57,102␤77␤»\n\nTherefore no data values are lost due in the 'zipping' operation. A record of\nwhich input list provided which element cannot be gleaned from the resulting\nsequence, however.\n\nC<roundrobin> can be useful in combining messy data to the point where a manual\npost-processing step can then be undertaken.\n\n    sub roundrobin(+list-of-lists, :$slip --> Seq)\n\nAs of release 2022.02 of the Rakudo compiler, it is also possible to specify\na C<:slip> named argument.  If specified with a true value, will\nL<slip|/language/list#Slips> the produced values.\n\n    say roundrobin <a b c>, <d e f m n o p>, <g h i j>, :slip;\n    # OUTPUT: «(a d g b e h c f i m j n o p)␤»\n\n=head2 routine sum\n\n    sub    sum($list  )\n    method sum(List:D:)\n\nReturns the sum of all elements in the list or 0 if the list is empty.\nThrows an exception if an element can not be coerced into Numeric.\n\n    say (1, 3, pi).sum;       # OUTPUT: «7.14159265358979␤»\n    say (1, \"0xff\").sum;      # OUTPUT: «256␤»\n    say sum(0b1111, 5);       # OUTPUT: «20␤»\n\nIf the list includes a L<C<Junction>|/type/Junction>, the result will accordingly be a\nL<C<Junction>|/type/Junction>:\n\n=for code\nsay ( 1|2, 3).sum;            # OUTPUT: «any(4, 5)␤»\n\nWhen called on native integer arrays, it is also possible to specify\na C<:wrap> named parameter.  This will add the values as native integers,\nwrapping around if they exceed the size of a native integer.  If you are\nsure you will not exceed that value, or if you don't mind, using C<:wrap>\nwill make the calculation about 20x as fast.\n\n=for code :preamble<my @a>\nmy int @a = ^1_000_000;\nsay @a.sum(:wrap);        # OUTPUT: «499999500000␤»\n\n=head2 method fmt\n\n    method fmt($format = '%s', $separator = ' ' --> Str:D)\n\nReturns a string where each element in the list has been formatted according\nto C<$format> and where each element is separated by C<$separator>.  If the\nlist contains nested sub-lists, then C<fmt> will flatten them before\nformatting each element.  Thus, C<fmt> will treat C<[1, 2, [3, 4]]> as a list\nwith 4 elements rather than 3.\n\nFor more information about formats strings, see L<sprintf|/routine/sprintf>.\n\n    my @a = 8..11;\n    say @a.fmt('%03d', ',');  # OUTPUT: «008,009,010,011␤»\n\n=head2 method from\n\nAssumes the list contains L«C<Match> objects|/type/Match» and returns the\nvalue of C<.from> called on the first element of the list.\n\n    'abcdefg' ~~ /(c)(d)/;\n    say $/.list.from;         # OUTPUT: «2␤»\n\n    \"abc123def\" ~~ m:g/\\d/;\n    say $/.list.from;         # OUTPUT: «3␤»\n\n=head2 method to\n\n    \"abc123def\" ~~ m:g/\\d/;\n    say $/.to; # OUTPUT: «6␤»\n\nAssumes the C<List> contains L«C<Match>|/type/Match»es, such as the\nC<$/> variable being a C<List>, when using C<:g> modifier in regexes. Returns the\nvalue of C<.to> called on the last element of the list.\n\n=head2 method sink\n\n     method sink(--> Nil) { }\n\nIt does nothing, and returns L<C<Nil>|/type/Nil>, as the definition clearly shows.\n\n    sink [1,2,Failure.new(\"boo!\"),\"still here\"]; # OUTPUT: «»\n\n=head2 method Set\n\nIn general, creates a set which has as members elements of the list.\n\n    say <æ ß þ €>.Set;  # OUTPUT: «Set(ß æ þ €)␤»\n\nHowever, there might be some unexpected changes in case the list includes\nnon-scalar data structures. For instance, with L<C<Pair>|/type/Pair>s:\n\n    my @a = (:42a, :33b);\n    say @a;                # OUTPUT: «[a => 42 b => 33]␤»\n    say @a.Set;            # OUTPUT: «Set(a b)␤»\n\nThe set will be composed of the C<key>s of the Pair whose corresponding value\nis not 0, eliminating all the values. Please check the\nL<C<Set> documentation|/type/Set#Creating_Set_objects> for more examples and a\nmore thorough explanation.\n\n=head1 Operators\n\n=head2 infix C<cmp>\n\n    multi infix:<cmp>(List @a, List @b)\n\nEvaluates C<Lists> by comparing element C<@a[$i]> with C<@b[$i]> (for some\nC<Int $i>, beginning at 0) and returning C<Order::Less>, C<Order::Same>, or\nC<Order::More> depending on if and how the values differ. If the operation\nevaluates to C<Order::Same>, C<@a[$i + 1]> is compared with C<@b[$i + 1]>. This\nis repeated until one is greater than the other or all elements are exhausted.\n\nIf the C<List>s are of different lengths, at most only C<$n> comparisons will be\nmade (where C<$n = @a.elems min @b.elems>). If all of those comparisons evaluate\nto C<Order::Same>, the final value is selected based upon which C<List> is\nlonger.\n\n    say (1, 2, 3) cmp (1, 2, 3);   # OUTPUT: «Same␤»\n    say (4, 5, 6) cmp (4, 5, 7);   # OUTPUT: «Less␤»\n    say (7, 8, 9) cmp (7, 8, 8);   # OUTPUT: «More␤»\n\n    say (1, 2)    cmp (1, 2, 3);   # OUTPUT: «Less␤»\n    say (1, 2, 3) cmp (1, 2);      # OUTPUT: «More␤»\n    say (9).List  cmp (^10).List;  # OUTPUT: «More␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Lock/Async.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Lock::Async\n\n=SUBTITLE A non-blocking, non-re-entrant, mutual exclusion lock\n\n    class Lock::Async {}\n\nA C<Lock::Async> instance provides a mutual exclusion mechanism: when the lock\nis held, any other code wishing to C<lock> must wait until the holder calls\nC<unlock> on it, which helps against all kinds of issues resulting from data\nbeing read and modified simultaneously from different threads.\n\nUnlike L<C<Lock>|/type/Lock>, which provides a traditional OS-backed mutual\nexclusion mechanism, C<Lock::Async> works with the high-level concurrency\nfeatures of Raku. The C<lock> method returns a L<C<Promise>|/type/Promise>,\nwhich will be kept when the lock is available. This L<C<Promise>|/type/Promise> can be used with\nnon-blocking C<await>. This means that a thread from the thread pool need not be\nconsumed while waiting for the C<Lock::Async> to be available, and the code\ntrying to obtain the lock will be resumed once it is available.\n\nThe result is that it's quite possible to have many thousands of outstanding\nC<Lock::Async> lock requests, but just a small number of threads in the\npool. Attempting that with a traditional L<C<Lock>|/type/Lock> would not go so\nwell!\n\nThere is no requirement that a C<Lock::Async> is locked and unlocked by the\nsame physical thread, meaning it is possible to do a non-blocking C<await>\nwhile holding the lock. The flip side of this is C<Lock::Async> is not\nre-entrant.\n\nWhile C<Lock::Async> works in terms of higher-level Raku concurrency\nmechanisms, it should be considered a building block. Indeed, it lies at\nthe heart of the L<C<Supply>|/type/Supply> concurrency model. Prefer to structure programs\nso that they communicate results rather than mutate shared data structures,\nusing mechanisms like L<C<Promise>|/type/Promise>, L<C<Channel>|/type/Channel>\nand L<C<Supply>|/type/Supply>.\n\n=head1 Methods\n\n=head2 method lock\n\n    method lock(Lock::Async:D: --> Promise:D)\n\nReturns a L<C<Promise>|/type/Promise> that will be kept when the lock is\navailable. In the case that the lock is already available, an already\nkept L<C<Promise>|/type/Promise> will be returned. Use C<await> to wait for the lock to\nbe available in a non-blocking manner.\n\n    my $l = Lock::Async.new;\n    await $l.lock;\n\nPrefer to use L<protect|/type/Lock/Async#method_protect> instead of\nexplicit calls to C<lock> and C<unlock>.\n\n=head2 method unlock\n\n    method unlock(Lock::Async:D: --> Nil)\n\nReleases the lock. If there are any outstanding C<lock> L<C<Promise>|/type/Promise>s,\nthe one at the head of the queue will then be kept, and potentially\ncode scheduled on the thread pool (so the cost of calling C<unlock>\nis limited to the work needed to schedule another piece of code that\nwants to obtain the lock, but not to execute that code).\n\n    my $l = Lock::Async.new;\n    await $l.lock;\n    $l.unlock;\n\nPrefer to use L<protect|/type/Lock/Async#method_protect> instead of\nexplicit calls to C<lock> and C<unlock>. However, if wishing to use\nthe methods separately, it is wise to use a C<LEAVE> block to ensure\nthat C<unlock> is reliably called. Failing to C<unlock> will mean that\nnobody can ever C<lock> this particular C<Lock::Async> instance again.\n\n    my $l = Lock::Async.new;\n    {\n        await $l.lock;\n        LEAVE $l.unlock;\n    }\n\n=head2 method protect\n\n    method protect(Lock::Async:D: &code)\n\nThis method reliably wraps code passed to C<&code> parameter with a\nlock it is called on.  It calls C<lock>, does an C<await> to wait for\nthe lock to be available, and reliably calls C<unlock> afterwards,\neven if the code throws an exception.\n\nNote that the C<Lock::Async> itself needs to be\ncreated outside the portion of the code that gets threaded and it\nneeds to protect. In the first example below,\nC<Lock::Async> is first created and assigned to\nC<$lock>, which is then used I<inside> the L<C<Promise>|/type/Promise>s\ncode to protect the sensitive code. In the second example, a mistake is\nmade, the C<Lock::Async> is created right inside the\nL<C<Promise>|/type/Promise>, so the code ends up with a bunch of different\nlocks, created in a bunch of threads, and thus they don't actually\nprotect the code we want to protect. Modifying an Array I<simultaneously>\nfrom different in the second example is not safe and leads to memory errors.\n\n=begin code :preamble<my @writers>\n# Compute how many prime numbers there are in first 10 000 of them\n# using 50 threads\nmy @primes = 0 .. 10_000;\nmy @results;\nmy @threads;\n\n# Right: $lock is instantiated outside the portion of the\n# code that will get threaded and be in need of protection,\n# so all threads share the lock\nmy $lock = Lock::Async.new;\nfor ^50 -> $thread {\n    @threads.push: start {\n        $lock.protect: {\n            my $from = $thread * 200;\n            my $to = ($thread + 1) * 200;\n            @results.append: @primes[$from..$to].map(*.is-prime);\n        }\n    }\n}\n\n# await for all threads to finish calculation\nawait Promise.allof(@writers);\n# say how many prime numbers we found\nsay \"We found \" ~ @results.grep(*.value).elems ~ \" prime numbers\";\n=end code\n\nThe example below demonstrates the wrong approach: without proper locking\nthis code will work most of the time, but occasionally will result\nin bogus error messages or low-level memory errors:\n\n=begin code :preamble<my @threads;my @results; my @primes>\n# !!! WRONG !!! Lock::Async is instantiated inside threaded area,\n# so all the 20 threads use 20 different locks, not syncing with\n# each other\nfor ^50 -> $thread {\n    @threads.push: start {\n        my $lock = Lock::Async.new;\n        $lock.protect: {\n            my $from = $thread * 200;\n            my $to = ($thread + 1) * 200;\n            @results.append: @primes[$from..$to].map(*.is-prime);\n        }\n    }\n}\n=end code\n\n=head2 method protect-or-queue-on-recursion\n\n    method protect-or-queue-on-recursion(Lock::Async:D: &code)\n\nWhen calling L<protect|/type/Lock/Async#method_protect> on a C<Lock::Async>\ninstance that is already locked, the method is forced to block until the lock\ngets unlocked. C<protect-or-queue-on-recursion> avoids this issue by either\nbehaving the same as L<protect|/type/Lock/Async#method_protect> if the lock is\nunlocked or the lock was locked by something outside the caller chain,\nreturning L<C<Nil>|/type/Nil>, or queueing the call to C<&code> and returning a L<C<Promise>|/type/Promise>\nif the lock had already been locked at another point in the caller chain.\n\n    my Lock::Async $lock .= new;\n    my Int         $count = 0;\n\n    # The lock is unlocked, so the code runs instantly.\n    $lock.protect-or-queue-on-recursion({\n        $count++\n    });\n\n    # Here, we have caller recursion. The outer call only returns a Promise\n    # because the inner one does. If we try to await the inner call's Promise\n    # from the outer call, the two calls will block forever since the inner\n    # caller's Promise return value is just the outer's with a then block.\n    $lock.protect-or-queue-on-recursion({\n        $lock.protect-or-queue-on-recursion({\n            $count++\n        }).then({\n            $count++\n        })\n    });\n\n    # Here, the lock is locked, but not by anything else on the caller chain.\n    # This behaves just like calling protect would in this scenario.\n    for 0..^2 {\n        $lock.protect-or-queue-on-recursion({\n            $count++;\n        });\n    }\n\n    say $count; # OUTPUT: 5\n\n=head2 method with-lock-hidden-from-recursion-check\n\n    method with-lock-hidden-from-recursion-check(&code)\n\nTemporarily resets the Lock::Async recursion list so that it no longer includes\nthe lock this method is called on and runs the given C<&code> immediately if\nthe call to the method occurred in a caller chain where\nL<protect-or-queue-on-recursion|/type/Lock/Async#method_protect-or-queue-on-recursion>\nhas already been called and the lock has been placed on the recursion list.\n\n    my Lock::Async $lock .= new;\n    my Int         $count = 0;\n\n    $lock.protect-or-queue-on-recursion({\n        my Int $count = 0;\n\n        # Runs instantly.\n        $lock.with-lock-hidden-from-recursion-check({\n            $count++;\n        });\n\n        # Runs after the outer caller's protect-or-queue-on-recursion call has\n        # finished running.\n        $lock.protect-or-queue-on-recursion({\n            $count++;\n        }).then({\n            say $count; # OUTPUT: 2\n        });\n\n        say $count; # OUTPUT: 1\n    });\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Lock/ConditionVariable.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Lock::ConditionVariable\n\n=SUBTITLE Condition variables used in locks\n\n    class Lock::ConditionVariable {}\n\nCondition variables are used in L<C<Lock>|/type/Lock>s to wait for a\nparticular condition to become true. You will normally not create one from\nscratch, but call L<C<Lock.condition>|/type/Lock#method_condition> to acquire\none on a particular L<C<Lock>|/type/Lock>.\n\n=head1 Methods\n\n=head2 method wait\n\n    multi method wait( --> Nil )\n    multi method wait( &predicate --> Nil )\n\nWithout any predicate, it waits on the condition variable itself; with a\npredicate, waits until the code returns a truish value.\n\n=begin code\n    my $times = 100;\n    my $tried;\n    my $failed;\n    for ^$times {\n        my $l = Lock.new;\n        my $c = $l.condition;\n        my $now1;\n        my $now2;\n        my $counter = 0;\n        my $t1 = Thread.start({\n            $l.protect({\n                $c.wait( { $counter != 0 } );\n                $now1 = now;\n            });\n        });\n\n        my $t2 = Thread.start({\n            $l.protect({\n                $counter++;\n                $c.signal();\n            });\n        });\n\n        $t1.join();\n        $now2 = now;\n        $t2.join();\n\n        $tried++;\n        last if $failed = ( !$now1.defined or $now1 > $now2 );\n    }\n=end code\n\nThe condition we obtain from the C<$l> lock is awaited using a predicate, in\nthis case, check if the counter is still zero. When it takes another value,\nthe program flow continues in the next instruction.\n\n=head2 method signal\n\n    method signal()\n\nIf and only if there are any threads that have previously waited on the\ncondition variable, it unblocks at least one of them. Let's see how it works\nin this example:\n\n=begin code\nconstant ITEMS = 100;\nfor 1..15 -> $iter {\n    my $lock = Lock.new;\n    my $cond = $lock.condition;\n    my $todo = 0;\n    my $done = 0;\n    my @in = 1..ITEMS;\n    my @out = 0 xx ITEMS;\n\n    for 1..ITEMS -> $i {\n        my $in = $i;\n        my $out := @out[$i];\n        Thread.start( {\n                    $out = $in * 10;\n                    $lock.protect( {\n                        $done++;\n                        $cond.signal if $done == $todo;\n                    } );\n        } );\n        $todo++;\n    }\n    $lock.protect( {\n        $cond.wait({  $done == $todo } );\n    });\n    say @out;\n}\n=end code\n\nWe are repeating 15 times the same operation: start 100 threads, every one of\nwhich modify a single element in an array. We C<protect> the modification of\na global variable, C<$done>, and use C<signal> to wake up another thread to\ndo its thing. This outputs the first elements of the generated arrays.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Lock.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Lock\n\n=SUBTITLE A low-level, re-entrant, mutual exclusion lock\n\n    class Lock {}\n\nA C<Lock> is a low-level concurrency control construct. It provides\nmutual exclusion, meaning that only one thread may hold the lock at a\ntime. Once the lock is unlocked, another thread may then lock it.\n\nA C<Lock> is typically used to protect access to one or more pieces\nof state. For example, in this program:\n\n    my $x = 0;\n    my $l = Lock.new;\n    await (^10).map: {\n        start {\n            $l.protect({ $x++ });\n        }\n    }\n    say $x;         # OUTPUT: «10␤»\n\nThe C<Lock> is used to protect operations on C<$x>. An increment is\nnot an atomic operation; without the lock, it would be possible for\ntwo threads to both read the number 5 and then both store back the\nnumber 6, thus losing an update. With the use of the C<Lock>, only\none thread may be running the increment at a time.\n\nA C<Lock> is re-entrant, meaning that a thread that holds the lock can\nlock it again without blocking. That thread must unlock the same number\nof times before the lock can be obtained by another thread (it works by\nkeeping a recursion count).\n\nIt's important to understand that there is no direct connection between\na C<Lock> and any particular piece of data; it is up to the programmer\nto ensure that the C<Lock> is held during all operations that involve the\ndata in question. The C<OO::Monitors> module, while not a complete solution\nto this problem, does provide a way to avoid dealing with the lock explicitly\nand encourage a more structured approach.\n\nThe C<Lock> class is backed by operating-system provided constructs, and\nso a thread that is waiting to acquire a lock is, from the point of view\nof the operating system, blocked.\n\nCode using high-level Raku concurrency constructs should avoid using\nC<Lock>. Waiting to acquire a C<Lock> blocks a real L<C<Thread>|/type/Thread>, meaning\nthat the thread pool (used by numerous higher-level Raku concurrency\nmechanisms) cannot use that thread in the meantime for anything else.\n\nAny C<await> performed while a C<Lock> is held will behave in a blocking\nmanner; the standard non-blocking behavior of C<await> relies on the\ncode following the `await` resuming on a different L<C<Thread>|/type/Thread> from the\npool, which is incompatible with the requirement that a C<Lock> be\nunlocked by the same thread that locked it. See\nL<C<Lock::Async>|/type/Lock::Async>\nfor an alternative mechanism that does not have this shortcoming. Other than\nthat, the main difference is that C<Lock> mainly maps to operating system\nmechanisms, while L<C<Lock::Async>|/type/Lock::Async> uses Raku primitives to achieve similar\neffects. If you're doing low-level stuff (native bindings) and/or actually\nwant to block real OS threads, use C<Lock>. However, if you want a\nnon-blocking mutual exclusion and don't need recursion and are running code\non the Raku thread pool, use Lock::Async.\n\nBy their nature, C<Lock>s are not composable, and it is possible to\nend up with hangs should circular dependencies on locks occur. Prefer\nto structure concurrent programs such that they communicate results\nrather than modify shared data structures, using mechanisms like\nL<C<Promise>|/type/Promise>, L<C<Channel>|/type/Channel> and L<C<Supply>|/type/Supply>.\n\n\n=head1 Methods\n\n=head2 method protect\n\n    multi method protect(Lock:D: &code)\n\nObtains the lock, runs C<&code>, and releases the lock afterwards. Care\nis taken to make sure the lock is released even if the code is left through\nan exception.\n\nNote that the C<Lock> itself needs to be created outside the portion\nof the code that gets threaded and it needs to protect. In the first\nexample below, C<Lock> is first created and assigned to C<$lock>,\nwhich is then used I<inside> the L<C<Promise>|/type/Promise>s to protect\nthe sensitive code. In the second example, a mistake is made: the\nC<Lock> is created right inside the L<C<Promise>|/type/Promise>, so the code ends up\nwith a bunch of separate locks, created in a bunch of threads, and\nthus they don't actually protect the code we want to protect.\n\n    # Right: $lock is instantiated outside the portion of the\n    # code that will get threaded and be in need of protection\n    my $lock = Lock.new;\n    await ^20 .map: {\n        start {\n            $lock.protect: {\n                print \"Foo\";\n                sleep rand;\n                say \"Bar\";\n            }\n        }\n    }\n\n    # !!! WRONG !!! Lock is created inside threaded area!\n    await ^20 .map: {\n        start {\n            Lock.new.protect: {\n                print \"Foo\"; sleep rand; say \"Bar\";\n            }\n        }\n    }\n\n=head2 method lock\n\n    method lock(Lock:D:)\n\nAcquires the lock. If it is currently not available, waits for it.\n\n    my $l = Lock.new;\n    $l.lock;\n\nSince a C<Lock> is implemented using OS-provided facilities, a thread\nwaiting for the lock will not be scheduled until the lock is available\nfor it. Since C<Lock> is re-entrant, if the current thread already holds\nthe lock, calling C<lock> will simply bump a recursion count.\n\nWhile it's easy enough to use the C<lock> method, it's more difficult to\ncorrectly use L<C<unlock>|/type/Lock#method_unlock>. Instead, prefer to\nuse the L<C<protect>|/type/Lock#method_protect> method instead, which\ntakes care of making sure the C<lock>/C<unlock> calls always both occur.\n\n=head2 method unlock\n\n    method unlock(Lock:D:)\n\nReleases the lock.\n\n    my $l = Lock.new;\n    $l.lock;\n    $l.unlock;\n\nIt is important to make sure the C<Lock> is always released, even if\nan exception is thrown. The safest way to ensure this is to use the\nL<C<protect>|/type/Lock#method_protect> method, instead of explicitly\ncalling C<lock> and C<unlock>. Failing that, use a C<LEAVE> phaser.\n\n\n    my $l = Lock.new;\n    {\n        $l.lock;\n        LEAVE $l.unlock;\n    }\n\n=head2 method condition\n\n    method condition(Lock:D: )\n\nReturns a condition variable as a L<C<Lock::ConditionVariable>|/type/Lock::ConditionVariable> object.\nCheck\nL<this article|https://web.stanford.edu/~ouster/cgi-bin/cs140-spring14/lecture.php?topic=locks> or\nL<the Wikipedia|https://en.wikipedia.org/wiki/Monitor_%28synchronization%29>\nfor background on condition variables and how they relate to locks and mutexes.\n\n    my $l = Lock.new;\n    $l.condition;\n\nYou should use a condition over a lock when you want an interaction with it\nthat is a bit more complex than simply acquiring or releasing the lock.\n\n=begin code\nconstant ITEMS = 100;\nmy $lock = Lock.new;\nmy $cond = $lock.condition;\nmy $todo = 0;\nmy $done = 0;\nmy @in = 1..ITEMS;\nmy @out = 0 xx ITEMS;\n\nloop ( my $i = 0; $i < @in; $i++ ) {\n    my $in := @in[$i];\n    my $out := @out[$i];\n    Thread.start( {\n      my $partial = $in² +1;\n      if $partial.is-prime {\n          $out = $partial but \"Prime\";\n      } else {\n          $out = $partial;\n      }\n      $lock.protect( {\n         $done++;\n         $cond.signal if $done == $todo;\n      } );\n    } );\n    $todo++;\n}\n$lock.protect( {\n    $cond.wait({  $done == $todo } );\n});\n\nsay @out.map: { $_.^roles > 2 ?? $_.Num ~ \"*\" !! $_ };\n# OUTPUT: «2* 5* 10 17* 26 37* 50 65 82 101* … »\n=end code\n\nIn this case, we use the condition variable C<$cond> to wait until all\nnumbers have been generated and checked and also to C<.signal> to another\nthread to wake up when the particular thread is done.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Macro.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Macro\n\n=SUBTITLE Compile-time routine\n\n    class Macro is Routine { }\n\nA macro is a Routine whose invocation typically happens during\nparsing. By returning an L<C<AST>|/type/AST>, a macro can inject code into\nthe calling location.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Map.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class Map\n\n=SUBTITLE Immutable mapping from strings to values\n\n    class Map does Associative does Iterable { }\n\nA C<Map> is an immutable mapping from string keys to values of arbitrary\ntypes. It serves as a base class for L<C<Hash>|/type/Hash>, which is mutable.\n\nIn list context a C<Map> behaves as a list of L<C<Pair>|/type/Pair> objects.\n\nNote that the order in which keys, values and pairs are retrieved is\ngenerally arbitrary, but the C<keys>, C<values> and C<pairs> methods\nreturn them always in the same order when called on the same object.\n\n    my %e := Map.new('a', 1, 'b', 2);\n    say %e.keys;    # can print «a b␤» or «b a␤»\n    say %e.values;  # prints «1 2␤» if the previous line\n                    # printed «a b␤», «2 1␤» otherwise\n\n\nTo retrieve a value from the Map by key, use the C<{ }> postcircumfix\noperator:\n\n    my %map is Map = 'a', 1, 'b', 2;\n    say %map{'a'};      # OUTPUT: «1␤»\n    say %map{ 'a', 'b' }; # OUTPUT: «(1 2)␤»\n\nTo check whether a given key is stored in a Map, modify the access\nwith the C<:exists> adverb:\n\n    my $map = Map.new('a', 1, 'b', 2);\n    my $key = 'a';\n    if $map{$key}:exists {\n        say \"$map{} has key $key\";\n    }\n\nBeing an immutable instance, it is not possible to add keys after\na C<Map> has been initialized:\n\n   my $m = Map.new( 'a', 1, 'b', 2 );\n   $m{ 'c' } = 'foo'; # WRONG!\n                      # Cannot modify an immutable Str\n\nUnlike its mutable companion type L<C<Hash>|/type/Hash>, a Map cannot be parameterized by key or value types.\n\n=head1 Methods\n\n=head2 method new\n\n    method new(*@args)\n\nCreates a new Map from a list of alternating keys and values, with\nL<the same semantics|/language/hashmap#Hash_assignment> as described\nin the L<Hashes and maps|/language/hashmap> documentation, but also\naccepts L<C<Pair>|/type/Pair>s instead of separate keys and values. Use the\nL<grouping operator|/language/operators#term_(_)> or quote the key to\nensure that a literal pair is not interpreted as a named argument.\n\n    my %h = Map.new('a', 1, 'b', 2);\n\n    # WRONG: :b(2) interpreted as named argument\n    say Map.new('a', 1, :b(2)).keys; # OUTPUT: «(a)␤»\n\n    # RIGHT: :b(2) interpreted as Pair because of extra parentheses\n    say Map.new( ('a', 1, :b(2)) ).keys.sort; # OUTPUT: «(a b)␤»\n\n    # RIGHT: 'b' => 2 always creates a Pair\n    say Map.new('a', 1, 'b' => 2).keys.sort; # OUTPUT: «(a b)␤»\n\nA shorthand syntax for creating Maps is provided:\n\n    my %h is Map = 'a', 1, 'b', 2;\n\n=head2 method elems\n\n    method elems(Map:D: --> Int:D)\n\nReturns the number of pairs stored in the Map.\n\n    my %map = Map.new('a', 1, 'b', 2);\n    say %map.elems; # OUTPUT: «2␤»\n\n=head2 method ACCEPTS\n\n    multi method ACCEPTS(Map:D: Positional $topic)\n    multi method ACCEPTS(Map:D: Cool:D     $topic)\n    multi method ACCEPTS(Map:D: Regex      $topic)\n    multi method ACCEPTS(Map:D: Any        $topic)\n\nUsed in smartmatching if the right-hand side is a C<Map>.\n\nIf the topic is list-like (L<C<Positional>|/type/Positional>), returns True if\nany of the list elements exist as a key in the Map.\n\nIf the topic is of type L<C<Cool>|/type/Cool> (strings, integers etc.),\nreturns True if the topic exists as a key.\n\nIf the topic is a regex, returns True if any of the keys match\nthe regex.\n\nAs a fallback, the topic is coerced to a list, and the L<C<Positional>|/type/Positional>\nbehavior is applied.\n\n\n=head2 method gist\n\n    method gist(Map:D: --> Str:D)\n\nReturns the string containing the \"gist\" of the C<Map>,\nsorts the pairs and lists B<up to the first 100>,\nappending an ellipsis if the C<Map> has more than 100 pairs.\n\n=head2 method keys\n\n    method keys(Map:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> of all keys in the Map.\n\n    my $m = Map.new('a' => (2, 3), 'b' => 17);\n    say $m.keys; # OUTPUT: «(a b)␤»\n\n=head2 method values\n\n    method values(Map:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> of all values in the Map.\n\n    my $m = Map.new('a' => (2, 3), 'b' => 17);\n    say $m.values; # OUTPUT: «((2 3) 17)␤»\n\n=head2 method pairs\n\n    method pairs(Map:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> of all pairs in the Map.\n\n    my $m = Map.new('a' => (2, 3), 'b' => 17);\n    say $m.pairs; # OUTPUT: «(a => (2 3) b => 17)␤»\n\n=head2 method antipairs\n\n    method antipairs(Map:D: --> Seq:D)\n\nReturns all keys and their respective values as a L<C<Seq>|/type/Seq> of L<C<Pair>|/type/Pair>s\nwhere the keys and values have been exchanged, i.e. the opposite of method\nL<pairs|/type/Map#method_pairs>. Unlike the\nL<C<invert>|/type/Map#method_invert> method, there is no attempt to expand list\nvalues into multiple pairs.\n\n    my $m = Map.new('a' => (2, 3), 'b' => 17);\n    say $m.antipairs;                        # OUTPUT: «((2 3) => a 17 => b)␤»\n\n=head2 method invert\n\n    method invert(Map:D: --> Seq:D)\n\nReturns all keys and their respective values as a L<C<Seq>|/type/Seq> of L<C<Pair>|/type/Pair>s\nwhere the keys and values have been exchanged. The difference between C<invert>\nand L<C<antipairs>|/type/Map#method_antipairs> is that C<invert> expands list\nvalues into multiple pairs.\n\n    my $m = Map.new('a' => (2, 3), 'b' => 17);\n    say $m.invert;                          # OUTPUT: «(2 => a 3 => a 17 => b)␤»\n\n=head2 method kv\n\n    method kv(Map:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> of keys and values interleaved.\n\n    Map.new('a', 1, 'b', 2).kv  # (a 1 b 2)\n\n=head2 method list\n\n    multi method list(Map:D: --> List:D)\n\nReturns a L<C<List>|/type/List> of L<C<Pair>|/type/Pair> objects of all keys and values in the Map.\n\n    my $m = Map.new('a' => (2, 3), 'b' => 17);\n    say $m.list;                            # OUTPUT: «(b => 17 a => (2 3))␤»\n\n=head2 method sort\n\n    multi method sort(Map:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> of L<C<Pair>|/type/Pair> objects, which are the pairs of\nthe hash, sorted by key. Equivalent to C<%hash.sort: *.key>\n\n    # These are equivalent:\n    say Map.new(<c 3 a 1 b 2>).sort;        # OUTPUT: «(a => 1 b => 2 c => 3)␤»\n    say Map.new(<c 3 a 1 b 2>).sort: *.key; # OUTPUT: «(a => 1 b => 2 c => 3)␤»\n\nSee L<Any.sort|/type/Any#method_sort> for additional available candidates.\n\n=head2 method Int\n\n    method Int(Map:D: --> Int:D)\n\nReturns the number of pairs stored in the C<Map> (same as C<.elems>).\n\n    my $m = Map.new('a' => 2, 'b' => 17);\n    say $m.Int;                                       # OUTPUT: «2␤»\n\n=head2 method Numeric\n\n    method Numeric(Map:D: --> Int:D)\n\nReturns the number of pairs stored in the C<Map> (same as C<.elems>).\n\n    my $m = Map.new('a' => 2, 'b' => 17);\n    say $m.Numeric;                                   # OUTPUT: «2␤»\n\n=head2 method Bool\n\n    method Bool(Map:D: --> Bool:D)\n\nReturns C<True> if the invocant contains at least one key/value pair.\n\n    my $m = Map.new('a' => 2, 'b' => 17);\n    say $m.Bool;                                      # OUTPUT: «True␤»\n\n=head2 method Capture\n\n    method Capture(Map:D:)\n\nReturns a L<C<Capture>|/type/Capture> where each key, if any, has been converted\nto a named argument with the same value as it had in the original C<Map>.\nThe returned L<C<Capture>|/type/Capture> will not contain any positional arguments.\n\n    my $map = Map.new('a' => 2, 'b' => 17);\n    my $capture = $map.Capture;\n    my-sub(|$capture);                                # OUTPUT: «2, 17␤»\n\n    sub my-sub(:$a, :$b) {\n        say \"$a, $b\"\n    }\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Match.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Match\n\n=SUBTITLE Result of a successful regex match\n\n    class Match is Capture is Cool does NQPMatchRole {}\n\nC<Match> objects are the result of a successful regex match, including\nany zero-width match. They store a reference to the original string (C<.orig>),\npositional and named captures, the positions of the start and end of the match\nin the original string, and a payload referred to as I<AST> (abstract syntax\ntree), which can be used to build data structures from complex regexes and\ngrammars.\n\nThe last match is also stored in the X<C<$¢>|Variables,$¢> C<Match> object, which is\nlexically scoped to the regex, that is, only available from within the regular\nexpression, as shown here:\n\n    my $c;\n    'abc' ~~ /.$${ $c = $¢ }/;\n    say $c; # OUTPUT: «｢c｣␤»\n\nIn this example we are running the code among curly braces when the match\noccurs,\nin this case the last letter in the string (actually, the last, indicated by the\ndouble C<$>, character); C<$c> gets the value of the cursor C<$¢>, which\ncontains the C<Match>; when used with C<say>, the C<Match> is stringified by\ncalling C<.Str> on it. This C<$¢> offers a way of capturing the Match inside a\nregular expression; outside, you need to use L<C<$/>|/syntax/$$SOLIDUS>\n\n    my $c; 'camelia' ~~ /<[ l m ]> {$c = $¢}/;\n    say $c; # OUTPUT: «｢m｣␤»\n    say $/; # OUTPUT: «｢m｣␤»\n\nB<Note>: This feature works only from Raku release 2018.02. It would have\nreturned L<C<Nil>|/type/Nil> with any previous version. Alternatively and prior to that\nversion, you could use C<$/> which, inside the regex, has the same value:\n\n    '123' ~~ / (\\d) { say $0; say $/; } \\d+ /; # OUTPUT: «｢1｣␤｢1｣␤ 0 => ｢1｣␤»\n\nThe main difference between C<$/> and C<$¢> is scope: the latter only has a\nvalue inside the regex:\n\n=begin code\n'123' ~~ / (\\d) { say $/; say $¢; } \\d+ /; # OUTPUT: «｢1｣␤ 0 => ｢1｣␤｢1｣␤ 0 => ｢1｣␤»\nsay \"¢ → \", $¢, \"/ is $/\"; ; # OUTPUT: «¢ → Nil/ is 123␤»\n=end code\n\nSubmatches are also C<Match> objects (or lists of C<Match> objects,\nif the corresponding regex was quantified), so each match object\ncan be seen as the root of a tree of match objects.\n\nA C<Match> object can also hold the result of a match in progress\n(while the grammar engine is running), in which case the C<pos> method\nreturns the current position. This view on C<Match> objects is only visible\nif you call code from within a regex.\n\nB<Note (deprecated)>: There is a synonym for this class, X<C<Cursor>|Reference,Cursor>,\n defined as:\n\n        my constant Cursor = Match\n\nInitially, it was used to keep track of initial position in regex matches. In\ncurrent versions, it's an alias for C<Match>.\n\n=head1 Methods\n\n=head2 method pos\n\nReturns the current position as a string index into C<Match.target> for a regex match\nI<in progress>:\n\n    my $a = 'abcdef';\n    $a ~~ /b. {say $/.pos }../;     # OUTPUT: «3␤»\n\nYou should not use this method on a finished C<Match>, as the output can be\nimplementation specific or is, in any case, unspecified.\n\n=head2 method target\n\n    method target()\n\nReturns a string representation of the object against which the regex matches. This is the value that the regex engine works with internally.\n\n    my $a = \"þor\" ~~ /o/;\n    say $a.target # OUTPUT: «þor␤»\n\n=head2 method chars\n\n    method chars()\n\nReturns the numbers of characters in the matched string or 0 if there's been\nno match.\n\nReturns the same as C<.Str.chars>.\n\n=head2 method clone\n\n    method clone()\n\nClones the C<Match> object.\n\n=head2 method orig\n\n    method orig()\n\nReturns the original input to the regex engine, which is usually a string,\nbut doesn't need to be (could be anything that can be coerced to a string):\n\n    42 ~~ /.+/;\n    say $/.orig;            # OUTPUT: «42␤»\n    say $/.orig.^name;      # OUTPUT: «Int␤»\n\nSee L<method target|#method target> for a close equivalent that always returns a string.\n\n=head2 method from\n\n    method from()\n\nReturns the index of the starting position of the match.\n\n=head2 method to\n\n    method to()\n\nReturns the index of the position next to the end of the match. It will\nreturn the match position if the end of the match is negative, and L<C<Nil>|/type/Nil> if\nthere has been no match.\n\n=head2 method made\n\n    method made()\n\nReturns the payload that was set with L<C<make>|/routine/make>.\n\n=head2 routine make\n\n    method make(Match:D: Mu $payload)\n    sub make(Mu $payload)\n\nSets the C<.ast> attribute, which will be retrieved using C<.made>.\n\n    $/.make(\"your payload here\");\n\nThat is, it stores an arbitrary payload into the C<Match> object that can later\nbe retrieved via L«C<.made>|/routine/made» method. Since the sub form\noperates, by default, on C<$/>, that example is equivalent to:\n\n    make(\"your payload here\");\n\nThis is typically used in a L<grammar|/language/grammars>'s actions class\nmethods, where a piece of data is stored by one method and then later retrieved\nby another. It's up to you what data you store. It could be a tree node, L<result\nof a calculation|/language/grammars#Proto_regexes>, a type object, or a list of\nvalues.\n\nThe sub form operates on the current Match C<$/>, which can be a convenient shortcut:\n\n    method my-action ($/) {\n        make \"foo: $/\";\n    }\n\n=head2 method actions\n\n    method actions(Match:D: --> Mu)\n\nReturns the actions object (if any was set; else L<C<Mu>|/type/Mu>) that the\ngrammar used from which this Match object was created.\n\n=head2 method ast\n\nAlias for L<method made|#method made>.\n\n=head2 method Bool\n\n    method Bool(Capture:D: --> Bool:D)\n\nReturns C<True> on successful and C<False> on unsuccessful matches. Please note\nthat any zero-width match can also be successful.\n\n    say 'abc' ~~ /^/;                   # OUTPUT: «｢｣␤»\n    say $/.from, ' ',  $/.to, ' ', ?$/; # OUTPUT: «0 0 True␤»\n\n=head2 method Str\n\n    method Str(Match:D: --> Str:D)\n\nReturns the matched text.\n\n    \"abc123def\" ~~ /\\d+/;\n    say $/.Str;               # OUTPUT: «123␤»\n\n=head2 method Int\n\n    method Int(Match:D: --> Int:D)\n\nTries to convert stringified result of the matched text into Int.\n\n    say ('12345' ~~ /234/).Int;       # OUTPUT: «234␤»\n    say ('12345' ~~ /234/).Int.^name; # OUTPUT: «Int␤»\n    # the next line produces a warning about using Nil (result of a no match) in numeric context\n    say ('one-two' ~~ /234/).Int;     # OUTPUT: «0␤» # because Nil.Int returns 0\n\n=head2 method caps\n\nReturns a list of pairs, with the index or submatch name as key and\nthe submatches as values. The list is ordered by starting position\nof the submatches.\n\n=head2 method chunks\n\nReturns a list of pairs, with the index or submatch name as key and\nthe submatches as values. The list is ordered by starting position\nof the submatches.\n\nThose parts of the string that were not matched by submatches are\ninterleaved with the other pairs, with the string C<~> as key.\n\n=head2 method list\n\nReturns a list of positional submatches.\n\n=head2 method hash\n\nReturns a hash of named submatches.\n\n=head2 method prematch\n\n    method prematch(Match:D: --> Str:D)\n\nReturns the part of the original string leading up to the match.\n\n    'abcdefg' ~~ /cd/;\n    say $/.prematch;          # OUTPUT: «ab␤»\n\n    # will return a list of three match objects\n    \"abc123def\" ~~ m:g/\\d/;\n    say $/.[1].prematch;      # OUTPUT: «abc1␤»\n\n=head2 method postmatch\n\n    method postmatch(Match:D: --> Str:D)\n\nReturns the part of the original string following the match.\n\n    'abcdefg' ~~ /cd/;\n    say $/.postmatch;         # OUTPUT: «efg␤»\n\n    # will return a list of three match objects\n    \"abc123def\" ~~ m:g/\\d/;\n    say $/.[1].postmatch;     # OUTPUT: «3def␤»\n\n=head2 method replace-with\n\n    multi method replace-with(Match:D: Str() $replacement --> Str:D)\n\nReturns the invocant string where the C«Match» object is replaced by\nC«$replacement».\n\n    my Str $some-string = \"Some foo\";\n    my Match $match = $some-string.match(/foo/);\n    my $another-string = $match.replace-with(\"string\"); # «Some string»\n\n=head2 infix eqv\n\n    multi infix:<eqv>(Match:D \\a, Match:D \\b)\n\nReturns C<True> if the attributes C<pos>, C<from> and C<orig> for C<a> and C<b>\nare equal, and if C<made>, C<Capture::list> and C<Capture::hash> are either the\nsame or both undefined.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/AttributeContainer.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"metamodel\")\n\n=TITLE role Metamodel::AttributeContainer\n\n=SUBTITLE Metaobject that can hold attributes\n\n    role Metamodel::AttributeContainer {}\n\nI<Warning>: this role is part of the Rakudo implementation, and is not\na part of the language specification.\n\nClasses, roles and grammars can have attributes. Storage and introspection of\nattributes is implemented by this role.\n\n=head1 Methods\n\n=head2 method add_attribute\n\n    method add_attribute($obj, $attribute)\n\nAdds an attribute. C<$attribute> must be an object that supports the\nmethods C<name>,  C<type> and C<package>, which are called without arguments.\nIt can for example be of L<type Attribute|/type/Attribute>.\n\n=head2 method attributes\n\n    method attributes($obj)\n\nReturns a list of attributes. For most Raku types, these will be objects of\nL<type Attribute|/type/Attribute>.\n\n=head2 method set_rw\n\n    method set_rw($obj)\n\nMarks a type whose attributes default to having a write accessor. For example\nin\n\n    class Point is rw {\n        has $.x;\n        has $.y;\n    }\n\nThe C<is rw> trait on the class calls the C<set_rw> method on the metaclass,\nmaking all the attributes implicitly writable, so that you can write;\n\n=begin code :preamble<class Point {}>\nmy $p = Point.new(x => 1, y => 2);\n$p.x = 42;\n=end code\n\n=head2 method rw\n\n    method rw($obj)\n\nReturns a true value if L<method set_rw|#method set_rw> has been called on\nthis object, that is, if new public attributes are writable by default.\n\n=begin comment\n\nTODO: compose_attributes, get_attribute_for_usage\n\nAlso TODO: describe :local, :excl, :all options of method attributes\n\n=end comment\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/C3MRO.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"metamodel\")\n\n=TITLE role Metamodel::C3MRO\n\n=SUBTITLE Metaobject that supports the C3 method resolution order\n\n    role Metamodel::C3MRO { }\n\nI<Warning>: this role is part of the Rakudo implementation, and is not\na part of the language specification.\n\nL<Metamodel|/language/mop> role for the\nL<I<C3> method resolution order (MRO)|https://en.wikipedia.org/wiki/Multiple_inheritance>.\n.\nI<Note>: this method,\nalong with almost the whole metamodel, is part of the Rakudo implementation.\n\nThe I<method resolution order> for a type is a flat list of types including the\ntype itself, and (recursively) all super classes. It determines in which order\nthe types will be visited for determining which method to call with a given\nname, or for finding the next method in a chain with\nL<nextsame|/language/functions#sub_nextsame>,\nL<callsame|/language/functions#sub_callsame>,\nL<nextwith|/language/functions#sub_nextwith> or\nL<callwith|/language/functions#sub_callwith>.\n\n=begin code\nclass CommonAncestor { };   # implicitly inherits from Any\nclass Child1 is CommonAncestor { }\nclass Child2 is CommonAncestor { }\nclass GrandChild2 is Child2 { }\nclass Weird is Child1 is GrandChild2 { };\n\nsay Weird.^mro; # OUTPUT: «(Weird) (Child1) (GrandChild2) (Child2) (CommonAncestor) (Any) (Mu)␤»\n=end code\n\nC3 is the default resolution order for classes and grammars in Raku.\nNote that roles generally do not appear in the method resolution order (unless\nthey are punned into a class, from which another type inherits), because\nmethods are copied into classes at role application time.\n\n=head1 Methods\n\n=head2 method compute_mro\n\n    method compute_mro($type)\n\nComputes the method resolution order.\n\n=head2 method mro\n\n    method mro($type)\n\nReturns a list of types in the method resolution order, even those that are\nmarked C<is hidden>.\n\n    say Int.^mro;   # OUTPUT: «((Int) (Cool) (Any) (Mu))␤»\n\n=head2 method mro_unhidden\n\n    method mro_unhidden($type)\n\nReturns a list of types in method resolution order, excluding those that are\nmarked with C<is hidden>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/ClassHOW.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"metamodel\")\n\n=TITLE class Metamodel::ClassHOW\n\n=SUBTITLE Metaobject representing a Raku class.\n\n=for code :skip-test<TWEAK>\n    class Metamodel::ClassHOW\n        does Metamodel::Naming\n        does Metamodel::Documenting\n        does Metamodel::Versioning\n        does Metamodel::Stashing\n        does Metamodel::AttributeContainer\n        does Metamodel::MethodContainer\n        does Metamodel::PrivateMethodContainer\n        does Metamodel::MultiMethodContainer\n        does Metamodel::RoleContainer\n        does Metamodel::MultipleInheritance\n        does Metamodel::DefaultParent\n        does Metamodel::C3MRO\n        does Metamodel::MROBasedMethodDispatch\n        does Metamodel::MROBasedTypeChecking\n        does Metamodel::Trusting\n        does Metamodel::BUILDPLAN\n        does Metamodel::Mixins\n        does Metamodel::ArrayType\n        does Metamodel::BoolificationProtocol\n        does Metamodel::REPRComposeProtocol\n        does Metamodel::Finalization\n            { }\n\nI<Warning>: this class is part of the Rakudo implementation, and is not\na part of the language specification.\n\nC<Metamodel::ClassHOW> is the metaclass behind the C<class> keyword.\n\n    say so Int.HOW ~~ Metamodel::ClassHOW;    # OUTPUT: «True␤»\n    say Int.^methods(:all).pick.name;         # OUTPUT: «random Int method name␤»\n\n=head1 Methods\n\n=head2 method add_fallback\n\n    method add_fallback($obj, $condition, $calculator)\n\nInstalls a method fallback, that is, add a way to call methods that weren't\nstatically added.\n\nBoth C<$condition> and C<$calculator> must be callables that receive the\ninvocant and the method name once a method is called that can't be found in\nthe method cache.\n\nIf C<$condition> returns a true value,\nC<$calculator> is called with the same arguments, and must return the code\nobject to be invoked as the method, and is added to the method cache.\n\nIf C<$condition> returns a false value, the\nnext fallback (if any) is tried, and if none matches, an exception\nL<of type X::Method::NotFound|/type/X::Method::NotFound> is thrown.\n\nUser-facing code (that is, code not dabbling with metaclasses) should use\nmethod C<FALLBACK> instead.\n\n=head2 method can\n\n    method can($obj, $method-name)\n\nGiven a method name, it returns a L<C<List>|/type/List> of methods that are\navailable with this name.\n\n    class A      { method x($a) {} };\n    class B is A { method x()   {} };\n    say B.^can('x').elems;              # OUTPUT: «2␤»\n    for B.^can('x') {\n        say .arity;                     # OUTPUT: «1, 2␤»\n    }\n\nIn this example, class C<B> has two possible methods available with name C<x>\n(though a normal method call would only invoke the one installed in C<B>\ndirectly). The one in C<B> has arity 1 (i.e. it expects one argument, the\ninvocant (C<self>)), and the one in C<A> expects 2 arguments (C<self> and\nC<$a>).\n\n=head2 method lookup\n\n    method lookup($obj, $method-name --> Method:D)\n\nReturns the first matching L<C<Method>|/type/Method> with the provided name. If no\nmethod was found, returns a VM-specific sentinel value (typically a low-level\nNULL value) that can be tested for with a test for\nL<definedness|/routine/defined>. It is potentially faster than C<.^can> but does\nnot provide a full list of all candidates.\n\n=begin code\n    say Str.^lookup('Int').raku; # OUTPUT: «method Int (Str:D $: *%_) { #`(Method|39910024) ... }␤»\n\n    for <uppercase  uc> {\n        Str.^lookup: $^meth andthen .(\"foo\").say\n            orelse \"method `$meth` not found\".say\n    }\n    # OUTPUT:\n    # method `uppercase` not found\n    # FOO\n=end code\n\n=head2 method compose\n\n      method compose($obj)\n\nA call to C<compose> brings the metaobject and thus the class it represents\ninto a fully functional state, so if you construct or modify a class, you must\ncall the compose method before working with the class.\n\nIt updates the method cache, checks that all methods that are required by\nroles are implemented, does the actual role composition work, and sets up\nthe class to work well with language interoperability.\n\n=head2 method new_type\n\n    method (:$name, :$repr = 'P6opaque', :$ver, :$auth)\n\nCreates a new type from the metamodel, which we can proceed to build\n\n    my $type = Metamodel::ClassHOW.new_type(name => \"NewType\",\n                                            ver => v0.0.1,\n                                            auth => 'github:raku' );\n    $type.HOW.add_method($type,\"hey\", method { say \"Hey\" });\n    $type.hey;     # OUTPUT: «Hey␤»\n    $type.HOW.compose($type);\n    my $instance = $type.new;\n    $instance.hey; # OUTPUT: «Hey␤»\n\nWe add a single method by using\nL<Higher Order Workings|/language/mop#HOW> methods, and\nthen we can use\nthat method directly as class method; we can then C<compose> the type, following\nwhich we can create already an instance, which will behave in the exact same\nway.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/ConcreteRoleHOW.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"metamodel\")\n\n=TITLE role Metamodel::ConcreteRoleHOW\n\n=SUBTITLE Provides an implementation of a concrete instance of a role\n\n=for code :skip-test<TWEAK>\n    class Metamodel::ConcreteRoleHOW\n        does Metamodel::Naming\n        does Metamodel::Versioning\n        does Metamodel::PrivateMethodContainer\n        does Metamodel::MethodContainer\n        does Metamodel::MultiMethodContainer\n        does Metamodel::AttributeContainer\n        does Metamodel::RoleContainer\n        does Metamodel::MultipleInheritance\n        does Metamodel::ArrayType\n        does Metamodel::Concretization {}\n\nI<Warning>: this class is part of the Rakudo implementation, and is not\na part of the language specification.\n\nYou can use this to build roles, in the same way that C<ClassHOW> can be used to\nbuild classes:\n\n=for code\nmy $a = Metamodel::ConcreteRoleHOW.new_type(name => \"Bar\");\n$a.^compose;\nsay $a.^roles; # OUTPUT: «(Mu)␤»\n\nThe main difference with\nL<C<ClassHOW.new_type>|/type/Metamodel::ClassHOW#method_new_type> is that you\ncan mix-in roles in this newly created one.\n\nI<Warning>: this class is part of the Rakudo implementation, and is not\na part of the language specification.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/CurriedRoleHOW.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"metamodel\")\n\n=TITLE role Metamodel::CurriedRoleHOW\n\n=SUBTITLE Support for parameterized roles that have not been instantiated\n\n=for code :skip-test<TWEAK>\n    class Metamodel::CurriedRoleHOW\n        does Metamodel::Naming\n        does Metamodel::TypePretense\n        does Metamodel::RolePunning {}\n\nI<Warning>: this class is part of the Rakudo implementation, and is not\na part of the language specification.\n\nSometimes, we see references to roles that provide parameters but\ndo not fully resolve them. For example, in:\n\n=for code :preamble<role R[::Type] {}; class Type {}>\nclass C does R[Type] { }\n\nWe need to represent C<R[T]>, but we cannot yet fully specialize the\nrole because we don't have the first parameter at hand. We may also\nrun into the issue where we have things like:\n\n=for code :preamble<role R[::T] {}; class T {}; my $x>\nsub foo(R[T] $x) { ... }\nif $x ~~ R[T] { ... }\n\nWhere we clearly want to talk about a partial parameterization of a\nrole and actually want to do so in a way distinct from a particular\ninstantiation of it. This metaobject represents those \"partial types\"\nas both a way to curry on your way to a full specialization, but also\nas a way to do type-checking or punning.\n\nThis class will show up in parameterized roles. For instance:\n\n=begin code\nrole Zipi[::T] {\n    method zape { \"Uses \" ~ T.^name };\n}\nrole Zipi[::T, ::Y] {\n    method zape { \"Uses \" ~ T.^name ~ \" and \" ~ Y.^name };\n}\nfor Zipi[Int], Zipi[Int,Str] -> $role {\n    say $role.HOW;\n    say $role.new().zape;\n}\n# OUTPUT:\n# Perl6::Metamodel::CurriedRoleHOW.new\n# Uses Int\n# Perl6::Metamodel::CurriedRoleHOW.new\n# Uses Int and Str\n=end code\n\nSince there are several variants of C<Zipi>, providing a parameter I<curries>\nit, but it's still up to the compiler to find out the actual realization taking\ninto account the C<ParametricRoleGroup>, so these (partially instantiated) roles\nshow up as C<Metamodel::CurriedRoleHOW> as shown in the example; even if there's\na single parameter an instantiated role will also be of the same type:\n\n    role Zape[::T] {};\n    say Zape[Int].HOW; #: «Perl6::Metamodel::CurriedRoleHOW.new␤»\n\nCurried roles L<pretend to be|/type/Metamodel::TypePretense> of types\nL<C<Mu>|/type/Mu>, L<C<Any>|/type/Any>, and L<C<Cool>|/type/Cool>, and\nL<delegate|/type/Metamodel::MethodDelegation> methods to L<C<Any>|/type/Any>.\n\nI<Note>: As with most of the C<Metamodel> classes, this one is mainly for illustration\npurposes and is not intended for the end user to instantiate.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/DefiniteHOW.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"metamodel\")\n\n=TITLE class Metamodel::DefiniteHOW\n\n=SUBTITLE Metaobject for type definiteness\n\n=for code :skip-test<breaks the metamodel>\n    class Metamodel::DefiniteHOW\n        does Metamodel::Documenting\n            { }\n\nI<Warning>: this class is part of the Rakudo implementation, and is not\na part of the language specification.\n\nType objects may be given a I<type smiley>, which is a suffix that\ndenotes their definiteness:\n\n=begin code\nsay Any:D.^name; # OUTPUT: «Any:D␤»\nsay Any:U.^name; # OUTPUT: «Any:U␤»\nsay Any:_.^name; # OUTPUT: «Any␤»\n=end code\n\nDespite sharing a type with L<C<Any>|/type/Any>, C<Any:U> and C<Any:D> in particular\nhave different type-checking behaviors from it:\n\n=begin code\nsay Any ~~ Any:D;     # OUTPUT: «False␤»\nsay Any ~~ Any:U;     # OUTPUT: «True␤»\nsay Any ~~ Any:_;     # OUTPUT: «True␤»\nsay Any.new ~~ Any:D; # OUTPUT: «True␤»\nsay Any.new ~~ Any:U; # OUTPUT: «False␤»\nsay Any.new ~~ Any:_; # OUTPUT: «True␤»\n=end code\n\nThis happens because C<Any:D> and C<Any:U> are not created with\nL<C<Metamodel::ClassHOW>|/type/Metamodel::ClassHOW> like you might expect\nL<C<Any>|/type/Any> type objects to be, but C<Metamodel::DefiniteHOW> instead. This\nHOW defines the behavior for definite type objects such as these.\n\nThe following type declaration:\n\n=for code\nmy Any constant Definite = Any:D;\n\nIs roughly equivalent to this code using the methods of\nC<Metamodel::DefiniteHOW>:\n\n=for code\nmy Any constant Definite = Metamodel::DefiniteHOW.new_type: base_type => Any, definite => 1;\n\n=head1 Methods\n\n=head2 method new_type\n\n    method new_type(:$base_type!, :$definite!)\n\nCreates a new definite type given a base type and definiteness.\nC<$definite> should either be C<1> for C<:D> types or C<0> for C<:U>\ntypes.\n\n=head2 method name\n\n    method name($definite_type)\n\nReturns the name of a definite type.\n\n=head2 method shortname\n\n    method shortname($definite_type)\n\nReturns the shortname of a definite type.\n\n=head2 method base_type\n\n    method base_type($definite_type)\n\nReturns the base type for a definite type:\n\n=for code\nsay Any:D.^base_type.^name; # OUTPUT: «Any␤»\n\n=head2 method definite\n\n    method definite($definite_type)\n\nReturns C<1> if the definite type given is a C<:D> type or C<0> if it is\na C<:U> type.\n\n=head2 method nominalize\n\n    method nominalize($obj)\n\nProduces a nominal type object for a definite type. This is its base\ntype, which may also get nominalized if it has the C<nominalizable>\narchetype.\n\n=head2 method find_method\n\n    method find_method($definite_type, $name)\n\nLooks up a method on the base type of a definite type.\n\n=head2 method type_check\n\n    method type_check($definite_type, $checkee)\n\nPerforms a type-check of a definite type against C<$checkee>. This will\ncheck if C<$checkee> is of its base type, returning C<True> if they\nmatch or C<False> otherwise. This metamethod can get called when a\ndefinite type is on the left-hand side of a smartmatch, for instance.\n\n=head2 method accepts_type\n\n    method accepts_type($definite_type, $checkee)\n\nPerforms a type-check of C<$checkee> against a definite type. This will\ncheck if C<$checkee> is of its base type and matches its definiteness,\nreturning C<True> if they match or C<False> otherwise.  This metamethod\ncan get called when the definite type is on the right-hand side of a\nsmartmatch, for instance.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/Documenting.rakudoc",
    "content": "=begin pod :kind<Type> :subkind<role> :category<metamodel>\n\n=TITLE role Metamodel::Documenting\n\n=SUBTITLE Metarole for documenting types.\n\n    role Metamodel::Documenting { }\n\nI<Warning>: this role is part of the Rakudo implementation, and is not\na part of the language specification.\n\nType declarations may include declarator blocks (C<#|> and C<#=>), which allow\nyou to set the type's documentation. This can then be accessed through the\nC<WHY> method on objects of that type:\n\n=begin code\n#|[Documented is an example class for Metamodel::Documenting's documentation.]\nclass Documented { }\n#=[Take a look at my WHY!]\n\nsay Documented.WHY;\n# OUTPUT:\n# Documented is an example class for Metamodel::Documenting's documentation.\n# Take a look at my WHY!\n=end code\n\nC<Metamodel::Documenting> is what implements this behavior for types.\nThis example can be rewritten to use its methods explicitly like so:\n\n=begin code\nBEGIN {\n    our Mu constant Documented = Metamodel::ClassHOW.new_type: :name<Documented>;\n    Documented.HOW.compose: Documented;\n    Documented.HOW.set_why: do {\n        my Pod::Block::Declarator:D $pod .= new;\n        $pod._add_leading:  \"Documented is an example class for Metamodel::Documenting's documentation.\";\n        $pod._add_trailing: \"Take a look at my WHY!\";\n        $pod\n    };\n}\n\nsay Documented.HOW.WHY;\n# OUTPUT:\n# Documented is an example class for Metamodel::Documenting's documentation.\n# Take a look at my WHY!\n=end code\n\nIt typically isn't necessary to handle documentation for types directly\nthrough their HOW like this, as C<Metamodel::Documenting>'s methods are\nexposed through L<C<Mu>|/type/Mu> via its C<WHY> and C<set_why> methods,\nwhich are usable on types in most cases.\n\n=head1 Methods\n\n=head2 method set_why\n\n    method set_why($why)\n\nSets the documentation for a type to C<$why>.\n\n=head2 method WHY\n\n    method WHY()\n\nReturns the documentation for a type.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/EnumHOW.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"metamodel\")\n\n=TITLE class Metamodel::EnumHOW\n\n=SUBTITLE Metaobject representing a Raku enum.\n\n=for code :skip-test<TWEAK>\n    class Metamodel::EnumHOW\n        does Metamodel::Naming\n        does Metamodel::Documenting\n        does Metamodel::Stashing\n        does Metamodel::AttributeContainer\n        does Metamodel::MethodContainer\n        does Metamodel::MultiMethodContainer\n        does Metamodel::RoleContainer\n        does Metamodel::BaseType\n        does Metamodel::MROBasedMethodDispatch\n        does Metamodel::MROBasedTypeChecking\n        does Metamodel::BUILDPLAN\n        does Metamodel::BoolificationProtocol\n        does Metamodel::REPRComposeProtocol\n        does Metamodel::Mixins\n            { }\n\nI<Warning>: this class is part of the Rakudo implementation, and is not\na part of the language specification.\n\nC<Metamodel::EnumHOW> is the metaclass behind the C<enum> keyword.\n\n    enum Numbers <1 2>;\n    say Numbers.HOW ~~ Metamodel::EnumHOW; # OUTPUT: «True␤»\n\nThe following enum declaration:\n\n    our Int enum Error <Warning Failure Exception Sorrow Panic>;\n\nIs roughly equivalent to this code using C<Metamodel::EnumHOW>'s methods:\n\n    BEGIN {\n        my constant Error = Metamodel::EnumHOW.new_type: :name<Error>, :base_type(Int);\n        Error.^add_role: Enumeration;\n        Error.^add_role: NumericEnumeration;\n        Error.^compose;\n        for <Warning Failure Exception Sorrow Panic>.kv -> Int $v, Str $k {\n            # Note: Enumeration.pred and .succ will not work when adding enum\n            # values as pairs. They should be instances of the enum itself, but\n            # this isn't possible to do without nqp.\n            Error.^add_enum_value: $k => $v;\n            OUR::{$k} := Error.^enum_from_value: $v;\n        }\n        Error.^compose_values;\n        OUR::<Error> := Error;\n    }\n\n=head1 Methods\n\n=head2 method new_type\n\n    method new_type(:$name!, :$base_type?, :$repr = 'P6opaque', :$is_mixin)\n\nCreates a new type object for an enum. C<$name> is the enum name, C<$base_type>\nis the type given when the enum is declared using a scoped declaration (if any),\nand C<$repr> is the type representation passed to the enum using the C<repr>\ntrait. C<$is_mixin> is unused.\n\n=head2 method add_parent\n\n    method add_parent($obj, $parent)\n\nSets the base type of an enum. This can only be used if no base type was passed\nto C<.new_type>.\n\n=head2 method set_export_callback\n\n    method set_export_callback($obj, $callback)\n\nSets the enum's export callback, which is invoked when calling\nC<.compose_values>. This is called when applying the C<export> trait to an\nenum. C<$callback> should be a routine of some sort, taking no arguments, that\nhandles exporting the enum's values.\n\n=head2 method export_callback\n\n    method export_callback($obj)\n\nReturns the export callback set by C<.set_export_callback>.\n\n=head2 method compose\n\n    method compose($obj, :$compiler_services)\n\nCompletes a type object for an enum. This is when any roles done by the enum\nare mixed in. This needs to be called before any enum values can be added using\nC<.add_enum_value>.\n\n=head2 method is_composed\n\n    method is_composed($obj)\n\nReturns 1 if the enum is composed, otherwise returns 0.\n\n=head2 method compose_values\n\n    method compose_values($obj)\n\nCalls the export callback set by C<.set_export_callback> and removes it from\nstate. This should be called after adding the enum's values using\nC<.add_enum_value>.\n\n=head2 method set_composalizer\n\n    method set_composalizer($c)\n\nSets the composalizer for an enum, which produces a type that can be mixed in\nwith another. C<$c> should be a routine of some that has the following\nsignature:\n\n    :($type, $name, @enum_values)\n\n=head2 method composalizer\n\n    method composalizer($obj)\n\nReturns the composalizer set by C<.set_composalizer>.\n\n=head2 method add_enum_value\n\n    method add_enum_value($obj, $value)\n\nAdds a value to this enum. C<$value> should be an instance of the enum itself,\nas type L<C<Enumeration>|/type/Enumeration>.\n\n=head2 method enum_values\n\n    method enum_values($obj)\n\nReturns the values for the enum.\n\n    enum Numbers <10 20>;\n    say Numbers.^enum_values;                   # OUTPUT: {10 => 0, 20 => 1}\n\n=head2 method elems\n\n    method elems($obj)\n\nReturns the number of values.\n\n    enum Numbers <10 20>;\n    say Numbers.^elems;                         # OUTPUT: 2\n\n=head2 method enum_from_value\n\n    method enum_from_value($obj, $value)\n\nGiven a value of the enum's base type, return the corresponding enum.\n\n    enum Numbers <10 20>;\n    say Numbers.^enum_from_value(0);            # OUTPUT: 10\n\n=head2 method enum_value_list\n\n    method enum_value_list($obj)\n\nReturns a list of the enum values.\n\n    enum Numbers <10 20>;\n    say Numbers.^enum_value_list;               # OUTPUT: (10 20)\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/Finalization.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"metamodel\")\n\n=TITLE role Metamodel::Finalization\n\n=SUBTITLE Metaobject supporting object finalization\n\nX<|Reference,DESTROY metamodel>\n\n    role Metamodel::Finalization { ... }\n\nI<Warning>: this role is part of the Rakudo implementation, and is not\na part of the language specification.\n\nThis role takes care that C<DESTROY> submethods are called (if they\nexist) when an object is garbage-collected.\n\n=head1 Methods\n\n=head2 method setup_finalization\n\n    method setup_finalization($obj)\n\nCollects the C<DESTROY> submethods from this class and all its\nsuperclasses, and marks the class as needing action on garbage\ncollection.\n\nA metamodel for a kind that implements finalization semantics must call\nthis method at type composition time.\n\n=head2 method destroyers\n\n    method destroyers($obj --> List:D)\n\nReturns a list of all finalization methods.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/MROBasedMethodDispatch.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"metamodel\")\n\n=TITLE role Metamodel::MROBasedMethodDispatch\n\n=SUBTITLE Metaobject that supports resolving inherited methods\n\n    role Metamodel::MROBasedMethodDispatch { }\n\nI<Warning>: this role is part of the Rakudo implementation, and is not\na part of the language specification.\n\nThis role implements locating methods based on the method resolution order of\nrelated (usually \"super\"/\"parent\") types.\n\n=head1 Methods\n\n=head2 method find_method\n\n    method find_method($obj, $name, :$no_fallback, *%adverbs)\n\nGiven a method name, it returns the method object of that name which is closest\nin the method resolution order (MRO). If no method can be found, it returns a\nVM-specific sentinel value (typically a low-level NULL value) that can be tested\nfor with a test for L<definedness|/routine/defined>:\n\n=begin code\nfor <uppercase  uc> {\n    Str.^find_method: $^meth andthen .(\"foo\").say\n        orelse \"method `$meth` not found\".say\n}\n# OUTPUT:\n# method `uppercase` not found\n# FOO\n=end code\n\nIf C<:no_fallback> is supplied, fallback methods are not considered.\n\n=head2 method find_method_qualified\n\n    method find_method_qualified($obj, $type, $name)\n\nGiven a method name and a type, returns the method from that type. This is\nused in calls like\n\n=for code :skip-test<code chunk for illustration>\nself.SomeParentClass::the_method();\n\n=head2 method can\n\n    method can($obj, $name)\n\nReturns the list of methods of that name the object can do.\n\n=head2 method publish_method_cache\n\n    method publish_method_cache($obj)\n\nWalk MRO and add methods to cache, unless another method lower in the class\nhierarchy \"shadowed\" it.\n\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/MethodContainer.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"metamodel\")\n\n=TITLE role Metamodel::MethodContainer\n\n=SUBTITLE Metaobject that supports storing and introspecting methods\n\n    role Metamodel::MethodContainer {}\n\nI<Warning>: this role is part of the Rakudo implementation, and is not\na part of the language specification.\n\nRoles, classes, grammars and enums can contain methods. This role implements\nthe API around storing and introspecting them.\n\n    say .name for Int.^methods(:all);\n\n    # don't do that, because it changes type Int globally.\n    # just for demonstration purposes.\n    Int.^add_method('double', method ($x:) { 2 * $x });\n    say 21.double; # OUTPUT: «42␤»\n\n=head1 Methods\n\n=head2 method add_method\n\n    method add_method($obj, $name, $code)\n\nAdds a method to the metaclass, to be called with name C<$name>.\nThis should only be done before a type is composed.\n\n=head2 method methods\n\n    method methods($obj, :$all, :$local)\n\nReturns a list of public methods available on the class (which includes\nmethods from superclasses and roles). By default this stops at the classes\nL<C<Cool>|/type/Cool>, L<C<Any>|/type/Any> or L<C<Mu>|/type/Mu>; to really get all methods, use the C<:all> adverb.\nIf C<:local> is set, only methods declared directly in the class are returned.\n\n    class A {\n        method x() { };\n    }\n\n    say A.^methods();                   # x\n    say A.^methods(:all);               # x infinite defined ...\n\nThe returned list contains objects of type L<C<Method>|/type/Method>, which you can\nuse to introspect their signatures and call them.\n\nSome introspection method-look-alikes like L<C<WHAT>|/language/mop#WHAT> will\nnot show up, although they are present in any Raku object. They are handled\nat the grammar level and will likely remain so for bootstrap reasons.\n\n=head2 method method_table\n\n    method method_table($obj --> Hash:D)\n\nReturns a hash where the keys are method names, and the values are\nL<C<Method>|/type/Method>s. Note that the keys are the names by which the methods\ncan be called, not necessarily the names by which the methods know themselves.\n\n=head2 method lookup\n\n    method lookup($obj, $name --> Method)\n\nReturns the first matching L<C<Method>|/type/Method> object of the provided C<$name>\nor C<(Mu)> if no method object was found. The search for a matching method object\nis done by following the L<mro|/type/Metamodel::C3MRO> of C<$obj>. Note that\nC<lookup> is supposed to be used for introspection, if you're after something\nwhich can be invoked you probably want to use L<find_method|/routine/find_method>\ninstead.\n\n    say 2.5.^lookup(\"sqrt\").raku;      # OUTPUT: «method sqrt (Rat $: *%_) ...␤»\n    say Str.^lookup(\"BUILD\").raku;     # OUTPUT: «submethod BUILD (Str $: :$value = \"\", *%_ --> Nil) ...␤»\n    say Int.^lookup(\"does-not-exist\"); # OUTPUT: «(Mu)␤»\n\nThe difference between C<find_method> and C<lookup> are that C<find_method> will\nuse a default candidate for parametric roles, whereas C<lookup> throws an exception\nin this case, and that C<find_method> honors C<FALLBACK> methods, which C<lookup>\ndoes not.\n\n=begin comment\n\nTODO: submethod_table, declares_method, cache, cache_get, cache_add\n\n=end comment\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/MethodDelegation.rakudoc",
    "content": "=begin pod :kind<Type> :subkind<role> :category<metamodel>\n\n=TITLE role Metamodel::MethodDelegation\n\n=SUBTITLE Metarole for delegating method dispatch\n\n    role Metamodel::MethodDelegation { }\n\nI<Warning>: this role is part of the Rakudo implementation, and is not\na part of the language specification.\n\nMethods of L<C<Any>|/type/Any> and L<C<Mu>|/type/Mu> can be invoked on roles, despite them not\nactually having these types as parents:\n\n=begin code\nrole Role { }\n\nsay Role.raku;                             # OUTPUT: «Role␤»\nsay Role.^pun.^parents(:all).map(*.^name); # OUTPUT: «()␤»\n=end code\n\nC<Metamodel::MethodDelegation> is the metarole responsible for this\nbehavior. Using the metamethods this provides, metaobjects can delegate\nmethod dispatch to another type object. This can be useful when\nimplementing types that shouldn't store methods of their own through\nL<C<Metamodel::MethodContainer>|/type/Metamodel::MethodContainer>, but\nshould still support method dispatch somehow.\n\nAll this metarole does is provide an interface for storing a type object\nto delegate methods to and provide a default C<find_method> method for\ndelegating method lookups to that type object if no other method lookup\nbehavior for it exists; any other behavior related to methods is left up\nto the metaclasses that do this metarole to implement themselves.\n\nBecause method delegation is a property of the metaclass for a HOW, not\nHOWs themselves, the C<delegate_methods_to> and\nC<delegating_methods_to> metamethods this metarole provides must be\ninvoked directly through a metaclass or HOW, not with C<.^> syntax:\n\n=for code :preamble<role Role { }>\nsay Role.HOW.delegating_methods_to.^name; # OUTPUT: «Any␤»\n\nThis metarole is commonly used in combination with\nL<C<Metamodel::TypePretense>|/type/Metamodel::TypePretense>.\n\n=head1 Methods\n\n=head2 method delegate_methods_to\n\n    method delegate_methods_to($type)\n\nDelegates methods to C<$type>. This should be a type object, but may be\nany object with a C<find_method> metamethod technically.\n\n=head2 method delegating_methods_to\n\n    method delegating_methods_to()\n\nReturns the type object a metaobject is delegating methods to.\n\n=head2 method find_method\n\n    method find_method($obj, $name)\n\nLooks up a method on the type object this metaobject is delegating\nmethod dispatch to.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/Mixins.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"metamodel\")\n\n=TITLE role Metamodel::Mixins\n\n=SUBTITLE Metaobject for generating mixins\n\n    role Metamodel::Mixins {}\n\nI<Warning>: this role is part of the Rakudo implementation, and is not a\npart of the language specification.\n\nUsing the C<does> and C<but> infix operators, I<mixins> of a base object\nand an arbitrary number of roles (or another object) can be created.\nThese are objects whose types have properties of both operands' types.\nRespectively, these rebless the existing object to have the generated\nmixin type and clone said object with said mixin type:\n\n=begin code\nclass Billboard {\n    has Str:D $.advertisement is required;\n\n    method vandalism(::?CLASS:D: --> Str:D) { ... }\n\n    multi method Str(::?CLASS:D: --> Str:D) { $!advertisement }\n\n    role Vandalized[Str:D :$vandalism] {\n        method vandalism(::?CLASS:D: --> Str:D) { $vandalism }\n\n        multi method Str(::?CLASS:D: --> Str:D) { $vandalism }\n    }\n}\n\nmy Str:D $advertisement = Q:to/ADVERTISEMENT/.chomp;\nBrilliant Solutions: sane and knowledgeable consultants.\nWe have been providing excellent services since 1972!\nADVERTISEMENT\nmy Str:D $vandalism = Q:to/VANDALISM/.chomp;\n          S       s  s ne     k          l   o   l     .\nWe    e  ee            e  e  e    e    e      e     !\nVANDALISM\n\nmy Billboard:D $billboard .= new: :$advertisement;\nsay $billboard eq $advertisement; # OUTPUT: «True␤»\n\nmy Billboard:D $draft = $billboard but Billboard::Vandalized[:$vandalism];\nsay $draft eq $vandalism; # OUTPUT: «True␤»\n\n$billboard does Billboard::Vandalized[:$vandalism];\nsay $billboard eq $vandalism; # OUTPUT: «True␤»\n=end code\n\nOptionally, mixins may have a I<mixin attribute>. This occurs when only\none role having only one public attribute gets mixed into an object.  If\na mixin attribute exists on a resulting mixin's type, it can be\ninitialized by C<but> or C<does> using its C<value> named parameter.\nThis makes it possible for mixins to not only have composable methods,\nbut composable state as well. Using this feature, the example above can\nbe rewritten so billboards can be vandalized more than once without\nneeding to generate more mixins by making C<Billboard::Vandalism>'s\nC<$vandalism> named parameter a L<rw|/type/Attribute#trait_is_rw>\nmixin attribute instead:\n\n=begin code\nclass Billboard {\n    has Str:D $.advertisement is required;\n\n    method vandalism(::?CLASS:D: --> Str:D) { ... }\n\n    multi method Str(::?CLASS:D: --> Str:D) { $!advertisement }\n\n    role Vandalized {\n        has Str:D $.vandalism is required is rw;\n\n        multi method Str(::?CLASS:D: --> Str:D) { $!vandalism }\n    }\n}\n\nmy Str:D $advertisement = Q:to/ADVERTISEMENT/.chomp;\nBrilliant Solutions: sane and knowledgeable consultants.\nWe have been providing excellent services since 1972!\nADVERTISEMENT\nmy Str:D $vandalism = Q:to/VANDALISM/.chomp;\n          S       s  s ne     k          l   o   l     .\nWe    e  ee            e  e  e    e    e      e     !\nVANDALISM\nmy Str:D $false-alarm = Qs:to/FALSE-ALARM/.chomp;\n$vandalism\n⬆️ This is just one of our namesakes we at Brilliant Solutions have been\nhelping people like you create since 1972!\nFALSE-ALARM\n\nmy Billboard:D $billboard .= new: :$advertisement;\nsay $billboard eq $advertisement; # OUTPUT: «True␤»\n\n$billboard does Billboard::Vandalized :value($vandalism);\nsay $billboard eq $vandalism; # OUTPUT: «True␤»\n\n$billboard.vandalism = $false-alarm;\nsay $billboard eq $false-alarm; # OUTPUT: «True␤»\n=end code\n\nC<Metamodel::Mixins> is the metarole that implements the behavior of\nsaid mixins. Formally, mixins are objects whose HOW inherits from a base\ncomposable metaobject and applies an arbitrary number of roles,\nresulting in an object whose HOW has a combination of their properties.\nIn particular, the metamethods this metarole provides are used to\nimplement the behavior of the C<but> and C<does> infix operators, but\nthese also support introspection related to mixins. For example, the\nwork done by C<but> when invoked with an object and one role can be\nwritten explicitly using the C<mixin> metamethod provided:\n\n=begin code\nclass Foo { }\nrole Bar { }\n\nsay Foo.new but Bar;     # OUTPUT: «Foo+{Bar}.new␤»\nsay Foo.new.^mixin(Bar); # OUTPUT: «Foo+{Bar}.new␤»\n=end code\n\n=for comment\nTODO: document what a HOW needs in order to support mixins. What\nbehavior the composable archetype handles and what is required in order\nfor a HOW to be considered composable is all that's strictly necessary\nto document before this would be reasonable to do, but documentation for\nsome of the additional metaroles needed, like\nMetamodel::LanguageRevision, would be useful to have as well.\n\n=head1 Methods\n\n=head2 method set_is_mixin\n\n    method set_is_mixin($obj)\n\nMarks C<$obj> as being a mixin.\n\n=head2 method is_mixin\n\n    method is_mixin($obj)\n\nReturns C<1> If C<$obj> has been marked as being a mixin with\nC<set_is_mixin>, otherwise returns C<0>.\n\n=head2 method set_mixin_attribute\n\n    method set_mixin_attribute($obj, $attr)\n\nSets the mixin attribute for C<$obj> to C<$attr> (which should be an\nL<C<Attribute>|/type/Attribute> instance).\n\n=head2 method mixin_attribute\n\n    method mixin_attribute($obj)\n\nReturns the mixin attribute for C<$obj> set with\nC<set_mixin_attribute>.\n\n=head2 method setup_mixin_cache\n\n    method setup_mixin_cache($obj)\n\nSets up caching of mixins for C<$obj>. After this metamethod has been\ncalled, calls to C<mixin> will not create a new type for mixins of\nC<$obj> given the same list of roles more than once. This should be\ncalled at some point before composition.\n\n=head2 method flush_cache\n\n    method flush_cache($obj)\n\nNo-op.\n\n=head2 method generate_mixin\n\n    method generate_mixin($obj, @roles)\n\nCreates a new mixin metaobject that inherits from C<$obj> and does each\nof the roles in C<@roles>. This is then composed and has its mixin\nattribute set (if any exists) before getting returned.\n\nWhile this generates a new mixin type, this doesn't actually mix it into\nC<$obj>; if that is what you intend to do, use the L<mixin|/routine/mixin> metamethod\ninstead.\n\n=head2 method mixin\n\n    method mixin($obj, *@roles, :$needs-mixin-attribute)\n\nGenerates a new mixin type by calling C<generate_mixin> with C<$obj> and\nC<@roles>. If C<$obj> is composed, the mixin cache of C<$obj> will be checked\nfor any existing mixin for these beforehand. If C<$obj> is an instance of a\ntype, this will return C<$obj> reblessed with the mixin generated, otherwise\nthis will return the mixin itself.\n\nIf C<$needs-mixin-attribute> is C<True>, this will throw an exception if\nno mixin attribute exists on the mixin generated before returning.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/MultipleInheritance.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"metamodel\")\n\n=TITLE role Metamodel::MultipleInheritance\n\n=SUBTITLE Metaobject that supports multiple inheritance\n\n    role Metamodel::MultipleInheritance {}\n\nI<Warning>: this role is part of the Rakudo implementation, and is not\na part of the language specification.\n\nClasses, roles and grammars can have parent classes, that is, classes to which\nmethod lookups fall back to, and to whose type the child class conforms to.\n\nThis role implements the capability of having zero, one or more parent (or\nI<super>) classes.\n\nIn addition, it supports the notion of I<hidden> classes, whose methods are\nexcluded from the normal dispatching chain, so that for example C<nextsame>\nignores it.\n\nThis can come in two flavors: methods from a class marked as C<is hidden>\nare generally excluded from dispatching chains, and C<class A hides B> adds\nC<B> as a parent class to C<A>, but hides it from the method resolution order,\nso that L<mro_unhidden|/type/Metamodel::C3MRO#method_mro_unhidden> skips it.\n\n=head1 Methods\n\n=head2 method add_parent\n\n    method add_parent($obj, $parent, :$hides)\n\nAdds C<$parent> as a parent type. If C<$hides> is set to a true value, the\nparent type is added as a hidden parent.\n\nC<$parent> must be a fully\nL<composed|/language/mop#Composition_time_and_static_reasoning> typed.\nOtherwise an exception of type L<C<X::Inheritance::NotComposed>|/type/X::Inheritance::NotComposed>\nis thrown.\n\n=head2 method ^parents\n\n    method ^parents($obj, :$all, :$tree)\n\nReturns the list of parent classes. By default it stops at L<C<Cool>|/type/Cool>, L<C<Any>|/type/Any> or\nL<C<Mu>|/type/Mu>, which you can suppress by supplying the C<:all> adverb. With C<:tree>,\na nested list is returned.\n\n    class D { };\n    class C1 is D { };\n    class C2 is D { };\n    class B is C1 is C2 { };\n    class A is B { };\n\n    say A.^parents(:all).raku;\n    # OUTPUT: «(B, C1, C2, D, Any, Mu)␤»\n    say A.^parents(:all, :tree).raku;\n    # OUTPUT: «[B, ([C1, [D, [Any, [Mu]]]], [C2, [D, [Any, [Mu]]]])]␤»\n\n=head2 method hides\n\n    method hides($obj)\n\nReturns a list of all hidden parent classes.\n\n=head2 method hidden\n\n    method hidden($obj)\n\nReturns a true value if (and only if) the class is marked with the trait C<is\nhidden>.\n\n=head2 method set_hidden\n\n    method set_hidden($obj)\n\nMarks the type as hidden.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/Naming.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"metamodel\")\n\n=TITLE role Metamodel::Naming\n\n=SUBTITLE Metaobject that supports named types\n\n    role Metamodel::Naming { }\n\nI<Warning>: this role is part of the Rakudo implementation, and is not\na part of the language specification.\n\nL<Metamodel|/language/mop> role for (optionally) named things, like classes,\nroles and enums.\n\n=head1 Methods\n\n=head2 method name\n\n    method name($type)\n\nReturns the name of the metaobject, if any.\n\n    say 42.^name;       # OUTPUT: «Int␤»\n\n=head2 method set_name\n\n    method set_name($type, $new_name)\n\nSets the new name of the metaobject.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/PackageHOW.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"metamodel\")\n\n=TITLE class Metamodel::PackageHOW\n\n=SUBTITLE Metaobject representing a Raku package.\n\n    class Metamodel::PackageHOW\n      does Metamodel::Naming\n      does Metamodel::Documenting\n      does Metamodel::Stashing\n      does Metamodel::TypePretense\n      does Metamodel::MethodDelegation { }\n\nI<Warning>: this class is part of the Rakudo implementation, and is not\na part of the language specification.\n\nC<Metamodel::PackageHOW> is the metaclass behind the C<package> keyword.\n\n    package P {};\n    say P.HOW; # OUTPUT: «Perl6::Metamodel::PackageHOW.new␤»\n\n=head1 Methods\n\n=head2 method archetypes\n\n     method archetypes()\n\nReturns the archetypes for this model, that is, the properties a metatype can\nimplement.\n\n=head2 method new\n\n     method new(*%named)\n\nCreates a new C<PackageHOW>.\n\n=head2 method new_type\n\n    method new_type(:$name = '<anon>', :$repr, :$ver, :$auth)\n\nCreates a new package, with optional representation, version and auth field.\n\n=head2 compose\n\n    method compose($obj, :$compiler_services)\n\nSets the metapackage as composed.\n\n=head2 is_composed\n\n    method is_composed($obj)\n\nReturns the composed status of the metapackage.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/ParametricRoleGroupHOW.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"metamodel\")\n\n=TITLE role Metamodel::ParametricRoleGroupHOW\n\n=SUBTITLE Represents a group of roles with different parameterizations\n\n:for code :solo\n    class Metamodel::ParametricRoleGroupHOW\n        does Metamodel::Naming\n        does Metamodel::Documenting\n        does Metamodel::Stashing\n        does Metamodel::TypePretense\n        does Metamodel::RolePunning\n        does Metamodel::BoolificationProtocol {}\n\nI<Warning>: this role is part of the Rakudo implementation, and is not\na part of the language specification.\n\nA C<ParametricRoleGroupHOW> groups a set of C<ParametricRoleHOW>, every one of them representing a single role declaration with their own parameter sets.\n\n=for code\n(role Zape[::T] {}).HOW.say; # OUTPUT: «Perl6::Metamodel::ParametricRoleHOW.new␤»\nZape.HOW.say ; # OUTPUT: «Perl6::Metamodel::ParametricRoleGroupHOW.new␤»\n\nC<ParametricRoleHOW>s need to be added to this kind of group:\n\n=for code\nmy \\zape := Metamodel::ParametricRoleGroupHOW.new_type( name => \"zape\");\nmy \\zipi := Metamodel::ParametricRoleHOW.new_type( name => \"zipi\", group => zape);\nsay zipi.HOW; # OUTPUT: «Perl6::Metamodel::ParametricRoleHOW.new␤»\n\nRole groups L<pretend to be|/type/Metamodel::TypePretense> of types\nL<C<Mu>|/type/Mu>, L<C<Any>|/type/Any>, and L<C<Cool>|/type/Cool>, and\nL<delegate|/type/Metamodel::MethodDelegation> methods to L<C<Any>|/type/Any>.\n\nI<Note>: As with most of the C<Metamodel> classes, this one is mainly for illustration\npurposes and is not intended for the end user to instantiate.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/ParametricRoleHOW.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"metamodel\")\n\n=TITLE role Metamodel::ParametricRoleHOW\n\n=SUBTITLE Represents a non-instantiated, parameterized, role.\n\n=for code :skip-test<TWEAK>\nclass Metamodel::ParametricRoleHOW\n    does Metamodel::Naming\n    does Metamodel::Documenting\n    does Metamodel::Versioning\n    does Metamodel::MethodContainer\n    does Metamodel::PrivateMethodContainer\n    does Metamodel::MultiMethodContainer\n    does Metamodel::AttributeContainer\n    does Metamodel::RoleContainer\n    does Metamodel::MultipleInheritance\n    does Metamodel::Stashing\n    does Metamodel::TypePretense\n    does Metamodel::RolePunning\n    does Metamodel::ArrayType {}\n\nI<Warning>: this class is part of the Rakudo implementation, and is not\na part of the language specification.\n\nA C<Metamodel::ParametricRoleHOW> represents a non-instantiated, possibly\nparameterized, role:\n\n=for code\n(role Zape[::T] {}).HOW.say;# OUTPUT: «Perl6::Metamodel::ParametricRoleHOW.new␤»\n(role Zape {}).HOW.say; # OUTPUT: «Perl6::Metamodel::ParametricRoleHOW.new␤»\n\nAs usual, C<.new_type> will create a new object of this class.\n\n=for code\nmy \\zipi := Metamodel::ParametricRoleHOW.new_type( name => \"zape\", group => \"Zape\");\nsay zipi.HOW; # OUTPUT: «Perl6::Metamodel::ParametricRoleHOW.new␤»\n\nThe extra C<group> argument will need to be used to integrate it in a parametric\nrole group, which will need to be defined in advance.\n\nRoles L<pretend to be|/type/Metamodel::TypePretense> of types L<C<Mu>|/type/Mu>,\nL<C<Any>|/type/Any>, and L<C<Cool>|/type/Cool>, and L<delegate|/type/Metamodel::MethodDelegation>\nmethods to L<C<Any>|/type/Any>.\n\nI<Note>: As with most of the C<Metamodel> classes, this one is mainly for illustration\npurposes and is not intended for the end user to instantiate.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/Primitives.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"metamodel\")\n\n=TITLE class Metamodel::Primitives\n\n=SUBTITLE Metaobject that supports low-level type operations\n\n    class Metamodel::Primitives {}\n\nC<Metamodel::Primitives> provides low-level operations for working with types,\nwhich are otherwise only available as implementation-dependent directives. These\nprimitives are available as class methods.\n\nHere is an example that steals the metamodel instance from the\nL<C<Int>|/type/Int> class to create a custom type (usually you would create your\nown metaclass if you mess with something as low-level), which allows calling\nof just one method called C<why>:\n\n    my Mu $type := Metamodel::Primitives.create_type(Int.HOW, 'P6opaque');\n    $type.^set_name('why oh why?');\n    my %methods =  why => sub ($) { say 42 };\n    Metamodel::Primitives.install_method_cache($type, %methods, :authoritative);\n    $type.why;      # 42\n    $type.list;\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Method::NotFound: Method 'list' not found for invocant of class 'why oh why?'␤»\n\nEvery metaobject has the capacity to hold a parameterization cache. This is\ndistinct from the C<parameterize> metamethod backing parameterization syntax.\nFor example, a package can be parametric in this low-level sense:\n\n    package Cache {\n        our sub parameterize(+args) is raw {\n            Metamodel::Primitives.parameterize_type: $?PACKAGE, args\n        }\n\n        sub noop(Mu, Mu \\args) is raw {\n            args\n        }\n\n        BEGIN Metamodel::Primitives.set_parameterizer: $?PACKAGE, &noop;\n    }\n\n=head1 Methods\n\n=head2 method create_type\n\n    method create_type(Mu $how, $repr = 'P6opaque')\n\nCreates and returns a new type from a metaobject C<$how> and a representation\nname.\n\n=head2 method set_package\n\n    method set_package(Mu $type, $package)\n\nSets the package associated with the type.\n\n=head2 method install_method_cache\n\n    method install_method_cache( Mu $type, %cache, :$authoritative = True)\n\nInstalls a method cache, that is, a mapping from method names to code objects.\nIf C<:authoritative> is missing, or set to C<True>, then calls of methods that\ndo not exist in the cache will throw an exception of type\nL<C<X::Method::NotFound>|/type/X::Method::NotFound>. If C<:authoritative> is set\nto C<False>, the usual fallback mechanism are tried.\n\n=head2 method configure_type_checking\n\n    method configure_type_checking( Mu $type, @cache, :$authoritative = True, :$call_accepts = False )\n\nConfigures the type checking for C<$type>. C<@cache> is a list of known types\nagainst which C<$type> checks positively (so in a classical class-based system,\nthe type itself and all recursive superclasses). If C<:authoritative> is missing\nor C<True>, this type will fail checks against all types not in C<@cache>. If\nC<:call_accepts> is True, the method L<ACCEPTS|/routine/ACCEPTS> will be called\nfor type checks against this type.\n\n=head2 method configure_destroy\n\n    method configure_destroy(Mu $type, $destroy)\n\nConfigures whether C<DESTROY> methods are called (if present) when the garbage\ncollector collects an object of this type (if C<$destroy> is set to a true\nvalue). This comes with a performance overhead, so should only be set to a\ntrue value if necessary.\n\n=head2 method compose_type\n\n    method compose_type(Mu $type, $configuration)\n\nComposes C<$type> (that is, finalizes it to be ready for instantiation). See\nL<https://github.com/Raku/nqp/blob/master/docs/6model/repr-compose-protocol.markdown>\nfor what C<$configuration> can contain (until we have better docs, sorry).\n\n=head2 method rebless\n\n    method rebless(Mu $object, Mu $type)\n\nChanges C<$object> to be of type C<$type>. This only works if C<$type>\ntype-checks against the current type of C<$object>, and if the storage of\nC<$object> is a subset of that of C<$type>. N<As of Raku 2019.11, this method\n requires\nL<special arrangements|https://github.com/rakudo/rakudo/issues/3414#issuecomment-573251877>.>\n\n=head2 method is_type\n\n    method is_type(Mu \\obj, Mu \\type --> Bool:D)\n\nType-checks C<obj> against C<type>\n\n=head2 method set_parameterizer\n\n    method set_parameterizer(Mu \\obj, &parameterizer --> Nil)\n\nInitializes the parameterization cache for a metaobject. This incorporates the\nC<&parameterize> routine to produce parameterizations to be cached. This is\nassumed to carry a signature compatible with C<:(Mu $root, List:D $args)>,\nC<$root> being the base metaobject for the parameterization, C<$args> being the\ntype arguments' object buffer.\n\n=head2 method parameterize_type\n\n    method parameterize_type(Mu \\obj, +parameters --> Mu)\n\nParameterizes a metaobject prepared by C<set_parameterizer> with C<parameters>.\nThe resulting metaobject is cached by literal object comparisons with C<=:=>\nfor each element of C<parameters>. I<Containers tend to invalidate any match>.\n\n=head2 method type_parameterized\n\n    method type_parameterized(Mu \\obj --> Mu)\n\nReturns the base metaobject from a parameterization given its resulting C<obj>.\nReturns L<C<Mu>|/type/Mu> if none was ever performed.\n\n=head2 method type_parameters\n\n    method type_parameters(Mu \\obj --> List:D)\n\nReturns the type arguments' object buffer from a parameterization given its\nresulting C<obj>. Dies if none was ever performed.\n\n=head2 method type_parameter_at\n\n    method type_parameter_at(Mu \\obj, Int:D \\idx --> Mu) is raw\n\nReturns a particular object from a parameterization given its resulting C<obj>\nand an index, skipping the L<C<List>|/type/List>-building step of C<type_parameters>. Dies if\nnone was ever performed.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/PrivateMethodContainer.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"metamodel\")\n\n=TITLE role Metamodel::PrivateMethodContainer\n\n=SUBTITLE Metaobject that supports private methods\n\n    role Metamodel::PrivateMethodContainer { ... }\n\nI<Warning>: this role is part of the Rakudo implementation, and is not\na part of the Raku language specification.\n\nIn Raku, classes, roles and grammars can have private methods, that is,\nmethods that are only callable from within it, and are not inherited by\ntypes derived by inheritance.\n\n    class A {\n        # the ! declares a private method\n        method !double($x) {\n            say 2 * $x;\n        }\n        method call-double($y) {\n            # call with ! instead of .\n            self!double($y);\n        }\n    }\n\nFor the purposes of dispatching and scoping, private methods are closer\nto subroutines than to methods. However they share access to C<self> and\nattributes with methods.\n\n=head1 Methods\n\n=head2 method add_private_method\n\n=for code\nmethod add_private_method($obj, $name, $code)\n\nAdds a private method C<$code> with name C<$name>.\n\n=head2 method private_method_table\n\n=for code\nmethod private_method_table($obj)\n\nReturns a hash of C«name => &method_object»\n\n=head2 method private_methods\n\n=for code\nmethod private_methods($obj)\n\nReturns a list of private method names.\n\n=head2 method private_method_names\n\n=for code\nmethod private_method_names($obj)\n\nAlias to C<private_methods>.\n\n=head2 method find_private_method\n\n=for code\nmethod find_private_method($obj, $name)\n\nLocates a private method. Otherwise, returns L<C<Mu>|/type/Mu> if it doesn't\nexist.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/RoleContainer.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"metamodel\")\n\n=TITLE role Metamodel::RoleContainer\n\n=SUBTITLE Metaobject that supports holding/containing roles\n\n    role Metamodel::RoleContainer {}\n\nI<Warning>: this role is part of the Rakudo implementation, and is not\na part of the language specification.\n\nImplements the ability to hold roles to be held for composition.\n\n=for code :preamble<role SomeRole {}>\nclass A does SomeRole {}\n\nroughly corresponds to\n\n=for code :preamble<role SomeRole {}>\nclass A {\n    BEGIN A.^add_role(SomeRole);\n}\n\n=head1 Methods\n\n=head2 method add_role\n\n    method add_role($obj, Mu $role)\n\nAdds the C<$role> to the list of roles to be composed.\n\n=head2 method roles_to_compose\n\n    method roles_to_compose($obj --> List:D)\n\nreturns a list of roles added with C<add_role>, which are to be composed\nat type composition time.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/RolePunning.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"metamodel\")\n\n=TITLE role Metamodel::RolePunning\n\n=SUBTITLE Metaobject that supports I<punning> of roles.\n\n    role Perl6::Metamodel::RolePunning {}\n\nI<Warning>: this role is part of the Rakudo implementation, and is not\na part of the language specification.\n\nImplements the ability to create objects from C<Role>s without the intermediate\nneed to use a class. Not intended to be used directly (will in fact error if\nit's C<use>d), but via punning of roles, as below. This is also Rakudo specific\nand not part of the spec.\n\n=for code\nrole A {\n    method b {\n      return \"punned\"\n    }\n};\nmy $a = A.new;\nsay $a.b; # OUTPUT: «punned␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/Stashing.rakudoc",
    "content": "=begin pod :kind<Type> :subkind<role> :category<metamodel>\n\n=TITLE role Metamodel::Stashing\n\n=SUBTITLE Metarole for type stashes\n\n    role Metamodel::Stashing { }\n\nI<Warning>: this role is part of the Rakudo implementation, and is not\na part of the language specification.\n\nTypes may have a stash associated with them, which is a named hash\ncontaining our-scoped symbols for that type's package. When this is\nthe case, they can be used like namespaces; you can get their stash\nusing their C<WHO> property or with the C<::> dispatch operator:\n\n=begin code\nmodule Nested {\n    module Namespace {\n        constant Symbol = $?MODULE;\n    }\n}\n\nsay Nested::Namespace::Symbol;         # OUTPUT: «(Namespace)␤»\nsay Nested.WHO<Namespace>.WHO<Symbol>; # OUTPUT: «(Namespace)␤»\n=end code\n\nC<Metamodel::Stashing> is the metarole that handles creating and\nsetting a stash object for types. Types used with this metarole are\nexpected to support naming, so when writing custom HOWs that do it,\nensure they also do L<C<Metamodel::Naming>|/type/Metamodel::Naming>.\n\n=head1 Methods\n\n=head2 method add_stash\n\n    method add_stash($type_obj)\n\nCreates and sets a stash for a type, returning C<$type_obj>.\n\nThis method is typically called as the last step of creating a new\ntype. For example, this is how it would be used in a minimal HOW that\nonly supports naming and stashing:\n\n=begin code :solo\nclass WithStashHOW\n    does Metamodel::Naming\n    does Metamodel::Stashing\n{\n    method new_type(WithStashHOW:_: Str:D :$name! --> Mu) {\n        my WithStashHOW:D $meta := self.new;\n        my Mu             $type := Metamodel::Primitives.create_type: $meta, 'Uninstantiable';\n        $meta.set_name: $type, $name;\n        self.add_stash: $type\n    }\n}\n\nmy Mu constant WithStash = WithStashHOW.new_type: :name<WithStash>;\nsay WithStash.WHO; # OUTPUT: «WithStash␤»\n=end code\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/Trusting.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"metamodel\")\n\n=TITLE role Metamodel::Trusting\n\n=SUBTITLE Metaobject that supports trust relations between types\n\n=for code :preamble<class SuperClass {};>\nrole Metamodel::Trusting is SuperClass { ... }\n\nI<Warning>: this role is part of the Rakudo implementation, and is not\na part of the language specification.\n\nNormally, code in a class or role can only access its own private methods. If\nanother type declares that it trusts that first class, then access to private\nmethods of that second type is possible. C<Metamodel::Trusting> implements\nthat aspect of the Raku object system.\n\n    class A {\n        my class B {\n            trusts A;   # that's where Metamodel::Trusting comes in\n            method !private_method() {\n                say \"Private method in B\";\n            }\n        }\n        method build-and-poke {\n            # call a private method from B\n            # disallowed if A doesn't trust B\n            B.new()!B::private_method();\n        }\n    };\n\n    A.build-and-poke;   # Private method in B\n\n=head1 Methods\n\n=head2 method add_trustee\n\n    method add_trustee($type, Mu $trustee)\n\nTrust C<$trustee>.\n\n=for code :preamble<class B {};>\nclass A {\n    BEGIN A.^add_trustee(B);\n    # same as 'trusts B';\n}\n\n=head2 method trusts\n\n    method trusts($type --> List)\n\nReturns a list of types that the invocant trusts.\n\n    class A { trusts Int; };\n    say .^name for A.^trusts;       # Int\n\n=head2 method is_trusted\n\n    method is_trusted($type, $claimant)\n\nReturns 1 if C<$type> trusts C<$claimant>, and 0 otherwise.\nTypes always trust themselves.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/TypePretense.rakudoc",
    "content": "=begin pod :kind<Type> :subkind<role> :category<metamodel>\n\n=TITLE role Metamodel::TypePretense\n\n=SUBTITLE Metarole for type pretenses\n\n    role Metamodel::TypePretense { }\n\nI<Warning>: this role is part of the Rakudo implementation, and is not\na part of the language specification.\n\nAny role will type-check as L<C<Mu>|/type/Mu>, L<C<Any>|/type/Any>, and L<C<Cool>|/type/Cool>, but don't\nactually have these classes as parents:\n\n=begin code\nclass Class { }\nrole  Role  { }\n\nsay Role ~~ Mu;   # OUTPUT: «True␤»\nsay Role ~~ Any;  # OUTPUT: «True␤»\nsay Role ~~ Cool; # OUTPUT: «True␤»\n\nsay Class.^parents(:all).map(*.^name);     # OUTPUT: «(Any Mu)␤»\nsay Role.^pun.^parents(:all).map(*.^name); # OUTPUT: «()␤»\n=end code\n\nC<Metamodel::TypePretense> is the metarole that's responsible for this\nbehavior. Using the metamethods this provides, types can C<pretend to\nbe> other types, i.e. types can type-check as other types. This can be\nuseful when implementing types that should not store parent types\nthrough\nL<C<Metamodel::MultipleInheritance>|/type/Metamodel::MultipleInheritance>,\nbut should still type-check like other types somehow.\n\nAll this metarole does is provide an interface for storing type objects\nin a HOW and provide a default C<type_check> method that allows types to\ntype-check as the types they're pretending to be if no other\ntype-checking behavior for it exists; any other behavior related to type\npretenses are left up to the metaclasses that do this metarole to\nimplement themselves.\n\nBecause type pretenses are a property of the metaclass for a HOW, not\nHOWs themselves, the C<pretend_to_be> and C<pretending_to_be>\nmetamethods this metarole provides must be invoked directly through a\nmetaclass or HOW, not with C<.^> syntax:\n\n=for code :preamble<role Role { }>\nsay Role.HOW.pretending_to_be.map(*.^name); # OUTPUT: «(Cool Any Mu)»\n\nThis metarole is commonly used in combination with\nL<C<Metamodel::MethodDelegation>|/type/Metamodel::MethodDelegation>.\n\n=head1 Methods\n\n=head2 method pretend_to_be\n\n    method pretend_to_be(@types)\n\nMakes all types for a type of HOW pretend to be any of the type objects\nin C<@types>.\n\n=head2 method pretending_to_be\n\n    method pretending_to_be()\n\nReturns the type objects this type of HOW is pretending to be.\n\n=head2 method type_check\n\n    method type_check($obj, $checkee)\n\nIf C<$checkee> is the same object as C<$obj> or is of any of the types\nC<$obj> is pretending to be, returns C<1>, otherwise returns C<0>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Metamodel/Versioning.rakudoc",
    "content": "=begin pod :kind<Type> :subkind<role> :category<metamodel>\n\n=TITLE role Metamodel::Versioning\n\n=SUBTITLE Metaobjects that support versioning\n\n   role Metamodel::Versioning { ... }\n\nI<Warning>: this role is part of the Rakudo implementation, and is not\na part of the language specification.\n\nL<Metamodel|/language/mop> role for (optionally) versioning metaobjects.\n\nWhen you declare a type, you can pass it a version, author, and/or API and get\nthem, like so:\n\n=begin code\nclass Versioned:ver<0.0.1>:auth<github:Kaiepi>:api<1> { }\n\nsay Versioned.^ver;  # OUTPUT: «v0.0.1␤»\nsay Versioned.^auth; # OUTPUT: «github:Kaiepi␤»\nsay Versioned.^api;  # OUTPUT: «1␤»\n=end code\n\nThis is roughly equivalent to the following, which also sets them explicitly:\n\n=begin code\nBEGIN {\n    class Versioned { }\n    Versioned.^set_ver:  v0.0.1;\n    Versioned.^set_auth: 'github:Kaiepi';\n    Versioned.^set_api:  <1>;\n}\n\nsay Versioned.^ver;  # OUTPUT: «v0.0.1␤»\nsay Versioned.^auth; # OUTPUT: «github:Kaiepi␤»\nsay Versioned.^api;  # OUTPUT: «1␤»\n=end code\n\n=head1 Methods\n\n=head2 method ver\n\n    method ver($obj)\n\nReturns the version of the metaobject, if any, otherwise returns L<C<Mu>|/type/Mu>.\n\n=head2 method auth\n\n    method auth($obj)\n\nReturns the author of the metaobject, if any, otherwise returns an empty string.\n\n=head2 method api\n\n    method api($obj)\n\nReturns the API of the metaobject, if any, otherwise returns an empty string.\n\n=head2 method set_ver\n\n    method set_ver($obj, $ver)\n\nSets the version of the metaobject.\n\n=head2 method set_auth\n\n    method set_auth($obj, $auth)\n\nSets the author of the metaobject.\n\n=head2 method set_api\n\n    method set_api($obj, $api)\n\nSets the API of the metaobject.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Method.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Method\n\n=SUBTITLE Member function\n\n    class Method is Routine { }\n\nA type for methods that behaves in the same way as L<C<Routine>|/type/Routine> with\nsome exceptions listed below. For details of a method's parameter\nlist see L<C<Signature>|/type/Signature>.\n\nTo create a method outside a L<class definition|/language/typesystem#Methods>,\nuse the declarators C<my> and C<method>. If an\nL<identifier|/language/syntax#Identifiers> is provided the methods name will be\ninjected into the scope specified by the declarator.\n\n    my $m = method ($invocant: $param) {\n        say \"$invocant: '$param'\";\n    }\n    \"greeting\".$m(\"hello\");  # OUTPUT: «greeting: 'hello'␤»\n\n    <a b c>.&(my method (List:D:) { say self.raku; self }).say;\n    # OUTPUT: «(\"a\", \"b\", \"c\")␤(a b c)␤»\n\nThe invocant of a method defaults to C<self>. A type constraint including a\ntype-smiley can be used and is honored both for methods defined in a class and\nfor free floating methods. Call the latter with C<.&> on an object.\n\n    my method m(Int:D: $b){\n        say self.^name\n    }\n    my $i = 1;\n    $i.&m(<a>);\n    # OUTPUT: «Int␤»\n\nPlease note that the main difference between methods defined within and\nwithout a class is the need to use `&` to invoke them in the latter case. In\ncase any other sigil is used in the definition, as in the first example, that\nsigil can also be used.\n\nX<|Syntax,*%_ (extra named arguments)>\nMethods automatically capture extra named arguments into the special variable C<%_>,\nwhere other types of L<C<Routine>|/type/Routine> will throw at runtime. So\n\n    method x() {}\n\nis actually equivalent to\n\n    method x(*%_) {}\n\nExtra arguments will be forwarded by L«C<nextsame> and\nfriends|/language/functions#Re-dispatching».\n\n    class A {\n        multi method m(:$a, :$b) { say \"2 named\" }\n    }\n\n    class B is A {\n        method m(:$a) { say \"1 named\"; nextsame }\n    }\n    B.m( :1a, :2b );\n    # OUTPUT: «1 named␤2 named␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Mix.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class Mix\n\n=SUBTITLE Immutable collection of distinct objects with Real weights\n\n    class Mix does Mixy { }\n\nA C<Mix> is an immutable collection of distinct elements\nin no particular order that each have a real-number weight assigned to\nthem. (For I<mutable> mixes, see L<C<MixHash>|/type/MixHash> instead.)\n\nC<Mix>es are often used for performing weighted random selections - see\nL<.roll|/routine/roll>.\n\nObjects/values of any type are allowed as mix elements. Within a C<Mix>,\nitems that would compare positively with the L<===|/routine/===> operator are\nconsidered the same element, with a combined weight.\n\n=begin code\nmy $recipe = (butter => 0.22, sugar => 0.1,\n              flour => 0.275, sugar => 0.02).Mix;\n\nsay $recipe.elems;      # OUTPUT: «3␤»\nsay $recipe.keys.sort;  # OUTPUT: «butter flour sugar␤»\nsay $recipe.pairs.sort; # OUTPUT: «\"butter\" => 0.22 \"flour\" => 0.275 \"sugar\" => 0.12␤»\nsay $recipe.total;      # OUTPUT: «0.615␤»\n=end code\n\nC<Mix>es can be treated as object hashes using the\nL«C<{ }> postcircumfix operator|/language/operators#postcircumfix_{_}»,\nor the\nL«C«< >» postcircumfix operator|/language/operators#postcircumfix_<_>»\nfor literal string keys, which\nreturns the corresponding numeric weight for keys that\nare elements of the mix, and C<0> for keys that aren't:\n\n    my $recipe = (butter => 0.22, sugar => 0.1,\n                  flour => 0.275, sugar => 0.02).Mix;\n    say $recipe<butter>;     # OUTPUT: «0.22␤»\n    say $recipe<sugar>;      # OUTPUT: «0.12␤»\n    say $recipe<chocolate>;  # OUTPUT: «0␤»\n\n=head1 Creating C<Mix> objects\n\nC<Mix>es can be composed using the L<mix|#sub mix> subroutine (or\nC<Mix.new>, for which it is a shorthand). Any positional parameters,\nregardless of their type, become elements of the mix - with a weight of\nC<1> for each time the parameter occurred:\n\n    my $n = mix \"a\", \"a\", \"b\" => 0, 3.14, π, π; # The Pair is a single element\n    say $n.keys.map: *.^name; # OUTPUT: «(Rat Pair Num Str)␤»\n    say $n.pairs;\n    # OUTPUT: «(3.14 => 1 (b => 0) => 1 3.141592653589793 => 2 a => 2)␤»\n\nAlternatively, the C<.Mix> coercer (or its functional form, C<Mix()>)\ncan be called on an existing object to coerce it to a C<Mix>. Its\nsemantics depend on the type and contents of the object. In general it\nevaluates the object in list context and creates a mix with the\nresulting items as elements, although for Hash-like objects or Pair\nitems, only the keys become elements of the mix, and the (cumulative)\nvalues become the associated numeric weights:\n\n    my $n = (\"a\", \"a\", \"b\" => 0, \"c\" => 3.14).Mix;\n    say $n.keys.map(&WHAT);  # OUTPUT: «((Str) (Str))␤»\n    say $n.pairs;            # OUTPUT: «(a => 2 c => 3.14)␤»\n\nElements with a 0 value, as C<b> above, are simply eliminated from the C<Mix>.\n\nAlternatively, since C<Mix>es are L<C<Associative>|/type/Associative>, we can use the C<%> sigil to\ndeclare them; in that case, we can employ C<is> to declare their type:\n\n    my %n is Mix = (\"a\", \"a\", \"b\" => 0, \"c\" => 3.14);\n    say %n.^name; # OUTPUT: «Mix␤»\n    say %n;       # OUTPUT: «Mix(a(2) c(3.14))␤»\n\nSince 6.d (2019.03 and later) it is also possible to specify the type of values\nyou would like to allow in a C<Mix>.  This can either be done when calling\nC<.new>:\n\n    # only allow strings\n    my $n = Mix[Str].new: <a b b c c c>;\n\nor using the masquerading syntax:\n\n    # only allow strings\n    my %m is Mix[Str] = <a b b c c c>;\n    say %m<b>;  # OUTPUT: «2␤»\n    say %m<d>;  # OUTPUT: «0␤»\n\n    # only allow whole numbers\n    my %m is Mix[Int] = <a b b c c c>;\n    # Type check failed in binding; expected Int but got Str (\"a\")\n\n=head1 Operators\n\nSee L<Operators with set\nsemantics|/language/setbagmix#Operators_with_set_semantics> for a complete\nlist of \"set operators\" applicable to, among other types, C<Mix>.\n\nExamples:\n\n=begin code\nmy $this-mix = (sugar => ⅓, spice => ¼, all-things-nice => ¾);\nmy $that-mix = ( sugar => 1, spice => 2);\n\nsay $that-mix (<) $this-mix;     # OUTPUT: «True␤»\nsay $that-mix (^) $this-mix;     # OUTPUT: «Set(all-things-nice)␤»\nsay $that-mix (+) $this-mix;     # OUTPUT: «Bag(spice(2) sugar)␤»\n\n# Unicode versions:\nsay $that-mix ⊂ $this-mix;     # OUTPUT: «True␤»\nsay $that-mix ⊖ $this-mix;     # OUTPUT: «Set(all-things-nice)␤»\nsay $that-mix ⊎ $this-mix;     # OUTPUT: «Bag(spice(2) sugar)␤»\n=end code\n\n=head2 sub mix\n\n    sub mix(*@args --> Mix)\n\nCreates a new C<Mix> from C<@args>.\n\n=head1 Methods\n\n=head2 method Bag\n\n    method Bag (--> Bag:D)\n\nCoerces the C<Mix> to a L«C<Bag>|/type/Bag». The weights are convert to\nL«C<Int>|/type/Int», which means the number of keys in the resulting\nL<C<Bag>|/type/Bag> can be fewer than in the original C<Mix>, if any of the weights\nare negative or truncate to zero.\n\n=head2 method BagHash\n\n    method BagHash (--> BagHash:D)\n\nCoerces the C<Mix> to a L«C<BagHash>|/type/BagHash». The weights are\nconvert to L«C<Int>|/type/Int», which means the number of keys in the\nresulting L<C<BagHash>|/type/BagHash> can be fewer than in the original C<Mix>, if any of\nthe weights are negative or truncate to zero.\n\n=head2 method reverse\n\nI<Note>: This method is inherited from L<Any|/type/Any#routine_reverse>,\nhowever, C<Mix>es do not have an inherent order and you should not trust\nit returning a consistent output.\n\n=head2 method total\n\n    method total(Mix:D: --> Real)\n\nReturns the sum of all the weights\n\n    say mix('a', 'b', 'c', 'a', 'a', 'd').total == 6;  # OUTPUT: «True␤»\n    say %(a => 5.6, b => 2.4).Mix.total == 8;          # OUTPUT: «True␤»\n\n=head2 Note on order\n\nSame as the other elements in the L<Bag/Mix suite|/language/setbagmix>,\norder is not guaranteed or consistent and you shouldn't rely on methods\nlike C<reverse> above returning always the same result.\n\n=head1 See Also\n\nL<Sets, Bags, and Mixes|/language/setbagmix>\n\n=end pod\n"
  },
  {
    "path": "doc/Type/MixHash.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class MixHash\n\n=SUBTITLE Mutable collection of distinct objects with Real weights\n\n    class MixHash does Mixy { }\n\nA C<MixHash> is a mutable mix, meaning a collection of distinct elements in no\nparticular order that each have a real-number weight assigned to them. (For\nI<immutable> mixes, see L<C<Mix>|/type/Mix> instead.)\n\nObjects/values of any type are allowed as mix elements. Within a C<MixHash>,\nitems that would compare positively with the L<===|/routine/===> operator are considered the\nsame element, with a combined weight.\n\n=begin code\nmy $recipe = (butter => 0.22, sugar => 0.1,\n              flour => 0.275, sugar => 0.02).MixHash;\n\nsay $recipe.elems;      # OUTPUT: «3␤»\nsay $recipe.keys.sort;  # OUTPUT: «butter flour sugar␤»\nsay $recipe.pairs.sort; # OUTPUT: «\"butter\" => 0.22 \"flour\" => 0.275 \"sugar\" => 0.12␤»\nsay $recipe.total;      # OUTPUT: «0.615␤»\n=end code\n\nC<MixHash>es can be treated as object hashes using the\nL«C<{ }> postcircumfix operator|/language/operators#postcircumfix_{_}»,\nor the\nL«C«< >» postcircumfix operator|/language/operators#postcircumfix_<_>»\nfor literal string keys, which\nreturns the corresponding numeric weight for keys that are\nelements of the mix, and C<0> for keys that aren't. It can also be used to modify\nweights; Setting a weight to C<0> automatically removes that element from the\nmix, and setting a weight to a non-zero number adds that element if it didn't\nalready exist:\n\n=begin code\nmy $recipe = (butter => 0.22, sugar => 0.1,\n              flour => 0.275, sugar => 0.02).MixHash;\n\nsay $recipe<butter>;     # OUTPUT: «0.22␤»\nsay $recipe<sugar>;      # OUTPUT: «0.12␤»\nsay $recipe<chocolate>;  # OUTPUT: «0␤»\n\n$recipe<butter> = 0;\n$recipe<chocolate> = 0.30;\nsay $recipe.pairs;       # OUTPUT: «\"sugar\" => 0.12 \"flour\" => 0.275 \"chocolate\" => 0.3␤»\n=end code\n\n\n=head1 Creating C<MixHash> objects\n\nC<MixHash>es can be composed using C<MixHash.new>. Any positional parameters,\nregardless of their type, become elements of the mix - with a weight of C<1> for\neach time the parameter occurred:\n\n    my $n = MixHash.new: \"a\", \"a\", \"b\" => 0, \"c\" => 3.14;\n    say $n.keys.map(&WHAT);  # OUTPUT: «((Str) (Pair) (Pair))␤»\n    say $n.pairs;            # OUTPUT: «(a => 2 (c => 3.14) => 1 (b => 0) => 1)␤»\n\nAlternatively, the C<.MixHash> coercer (or its functional form, C<MixHash()>)\ncan be called on an existing object to coerce it to a C<MixHash>. Its semantics\ndepend on the type and contents of the object. In general it evaluates the\nobject in list context and creates a mix with the resulting items as elements,\nalthough for Hash-like objects or Pair items, only the keys become elements of\nthe mix, and the (cumulative) values become the associated numeric weights:\n\n    my $n = (\"a\", \"a\", \"b\" => 0, \"c\" => 3.14).MixHash;\n    say $n.keys.map(&WHAT);  # OUTPUT: «((Str) (Str))␤»\n    say $n.pairs;            # OUTPUT: «(a => 2 c => 3.14)␤»\n\nSince 6.d (2019.03 and later) it is also possible to specify the type of values\nyou would like to allow in a C<MixHash>.  This can either be done when calling\nC<.new>:\n\n    # only allow strings\n    my $n = MixHash[Str].new: <a b b c c c>;\n\nor using the masquerading syntax:\n\n    # only allow strings\n    my %mh is MixHash[Str] = <a b b c c c>;\n    say %mh<b>;  # OUTPUT: «2␤»\n    say %mh<d>;  # OUTPUT: «0␤»\n\n    # only allow whole numbers\n    my %mh is MixHash[Int] = <a b b c c c>;\n    # Type check failed in binding; expected Int but got Str (\"a\")\n\n=head1 Operators\n\nSee L<Operators with set\nsemantics|/language/setbagmix#Operators_with_set_semantics> for a complete\nlist of \"set operators\" applicable to, among other types, C<MixHash>.\n\nExamples:\n\n=begin code\nmy ($a, $b) = MixHash(2 => 2, 4), MixHash(2 => 1.5, 3 => 2, 4);\n\nsay $a (<) $b;   # OUTPUT: «False␤»\nsay $a (<=) $b;  # OUTPUT: «False␤»\nsay $a (^) $b;   # OUTPUT: «MixHash(2(0.5) 3(2))␤»\nsay $a (+) $b;   # OUTPUT: «MixHash(2(3.5) 4(2) 3(2))␤»\n\n# Unicode versions:\nsay $a ⊂ $b;  # OUTPUT: «False␤»\nsay $a ⊆ $b;  # OUTPUT: «False␤»\nsay $a ⊖ $b;  # OUTPUT: «MixHash(2(0.5) 3(2))␤»\nsay $a ⊎ $b;  # OUTPUT: «MixHash(2(3.5) 4(2) 3(2))␤»\n=end code\n\n=head1 Note on C<reverse> and ordering.\n\nMixHash inherits C<reverse> from L<Any|/type/Any#routine_reverse>,\nhowever, L<C<Mix>|/type/Mix>es do not have an inherent order and you should not trust\nit returning a consistent output.\n\nIf you sort a MixHash, the result is a list of pairs, at which point\nC<reverse> makes perfect sense:\n\n=begin code\nmy $a = MixHash.new(2, 2, 18, 3, 4);\nsay $a;  # OUTPUT: «MixHash(18 2(2) 3 4)␤»\n\nsay $a.sort;  # OUTPUT: «(2 => 2 3 => 1 4 => 1 18 => 1)␤»\nsay $a.sort.reverse;  # OUTPUT: «(18 => 1 4 => 1 3 => 1 2 => 2)␤»\n=end code\n\n=head1 Methods\n\n=head2 method Bag\n\n    method Bag (--> Bag:D)\n\nCoerces the C<MixHash> to a L«C<Bag>|/type/Bag». The weights are converted\nto L«C<Int>|/type/Int»,\nwhich means the number of keys in the resulting L<C<Bag>|/type/Bag> can be fewer than in the\noriginal C<MixHash>, if any of the weights are negative or truncate to zero.\n\n=head2 method BagHash\n\n    method BagHash (--> BagHash:D)\n\nCoerces the C<MixHash> to a L«C<BagHash>|/type/BagHash». The weights are converted\nto L«C<Int>|/type/Int»,\nwhich means the number of keys in the resulting L<C<BagHash>|/type/BagHash> can be fewer than in the\noriginal C<MixHash>, if any of the weights are negative or truncate to zero.\n\n=head1 See Also\n\nL<Sets, Bags, and Mixes|/language/setbagmix>\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Mixy.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"composite\")\n\n=TITLE role Mixy\n\n=SUBTITLE Collection of distinct objects with Real weights\n\n    role Mixy does Baggy { }\n\nA role for collections of weighted values. See L<C<Mix>|/type/Mix> and L<C<MixHash>|/type/MixHash>.\nC<Mixy> objects differ from L<C<Baggy>|/type/Baggy> objects in that the weights of\nC<Mixy> are L<C<Real>|/type/Real>s rather than L<C<Int>|/type/Int>s.\n\n=head1 Methods\n\n=head2 method roll\n\n    method roll($count = 1)\n\nSimilar to a L<C<Bag>|/type/Bag>.roll, but with L<C<Real>|/type/Real> weights rather than integral\nones.\n\n=head2 method pick\n\n    method pick($?)\n\nThrows an exception. The feature is not supported on the type, since there's no\nclear value to subtract from non-integral weights, to make it work.\n\n=head2 method grab\n\n    method grab($?)\n\nThrows an exception. The feature is not supported on the type, since there's no\nclear value to subtract from non-integral weights, to make it work.\n\n=head2 method kxxv\n\n    method kxxv()\n\nThrows an exception. The feature is not supported on the type, since there's no\nclear value to subtract from non-integral weights, to make it work.\n\n=head1 See Also\n\nL<Sets, Bags, and Mixes|/language/setbagmix>\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Mu.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Mu\n\n=SUBTITLE The root of the Raku type hierarchy.\n\n    class Mu { }\n\nThe root of the Raku type hierarchy. For the origin of the name, see\nL<Mu (negative)|https://en.wikipedia.org/wiki/Mu_%28negative%29> on Wikipedia.\nOne can also say that there are many undefined values in Raku, and C<Mu> is the\nI<most undefined> value.\n\nNote that most classes do not derive from C<Mu> directly, but rather from\nL<C<Any>|/type/Any>.\n\n=head1 Methods\n\n=head2 method iterator\n\n    method iterator(--> Iterator)\n\nCoerces the invocant to a C<list> by applying its L«C<.list>|/routine/list»\nmethod and uses L«C<iterator>|/type/Iterable#method_iterator» on it.\n\n    my $it = Mu.iterator;\n    say $it.pull-one; # OUTPUT: «(Mu)␤»\n    say $it.pull-one; # OUTPUT: «IterationEnd␤»\n\n=head2 routine defined\n\n    multi method defined(   --> Bool:D)\n    multi        defined(Mu --> Bool:D)\n\nReturns C<False> on a type object, and C<True> otherwise. (The sub\nevaluates its argument, and the method its invocant.)\n\n    say Int.defined;                # OUTPUT: «False␤»\n    say 42.defined;                 # OUTPUT: «True␤»\n\nA few types (like L<C<Failure>|/type/Failure>) override C<defined> to\nreturn C<False> even for instances:\n\n    sub fails() { fail 'oh noe' };\n    say fails().defined;            # OUTPUT: «False␤»\n\n=head2 method isa\n\n    multi method isa(Mu $type     --> Bool:D)\n    multi method isa(Str:D $type  --> Bool:D)\n\nReturns C<True> if the invocant is an instance of class C<$type>, a subset type\nor a derived class (through inheritance) of C<$type>.\nL<C<does>|/method/does#(Mu)_method_does> is similar, but includes roles.\n\n    my $i = 17;\n    say $i.isa(\"Int\");   # OUTPUT: «True␤»\n    say $i.isa(Any);     # OUTPUT: «True␤»\n    role Truish {};\n    my $but-true = 0 but Truish;\n    say $but-true.^name;        # OUTPUT: «Int+{Truish}␤»\n    say $but-true.does(Truish); # OUTPUT: «True␤»\n    say $but-true.isa(Truish);  # OUTPUT: «False␤»\n\n=head2 method does\n\n    method does(Mu $type --> Bool:D)\n\nReturns C<True> if and only if the invocant conforms to type C<$type>.\n\n=for code\nmy $d = Date.new('2016-06-03');\nsay $d.does(Dateish);             # OUTPUT: «True␤»    (Date does role Dateish)\nsay $d.does(Any);                 # OUTPUT: «True␤»    (Date is a subclass of Any)\nsay $d.does(DateTime);            # OUTPUT: «False␤»   (Date is not a subclass of DateTime)\n\nUnlike L<C<isa>|/method/isa#(Mu)_method_isa>, which\nreturns C<True> only for superclasses, C<does> includes both superclasses and\nroles.\n\n=for code :preamble<my $d = Date.new('2016-06-03');>\nsay $d.isa(Dateish); # OUTPUT: «False␤»\n\nUsing the smartmatch operator L<~~|/routine/~~> is a more idiomatic alternative.\n\n    my $d = Date.new('2016-06-03');\n    say $d ~~ Dateish;                # OUTPUT: «True␤»\n    say $d ~~ Any;                    # OUTPUT: «True␤»\n    say $d ~~ DateTime;               # OUTPUT: «False␤»\n\n=head2 routine Bool\n\n    multi method Bool(   --> Bool:D)\n    multi        Bool(Mu --> Bool:D)\n\nReturns C<False> on the type object, and C<True> otherwise.\n\nMany built-in types override this to be C<False> for empty collections, the\nempty L<string|/type/Str> or numerical zeros\n\n    say Mu.Bool;                    # OUTPUT: «False␤»\n    say Mu.new.Bool;                # OUTPUT: «True␤»\n    say [1, 2, 3].Bool;             # OUTPUT: «True␤»\n    say [].Bool;                    # OUTPUT: «False␤»\n    say %( hash => 'full' ).Bool;   # OUTPUT: «True␤»\n    say {}.Bool;                    # OUTPUT: «False␤»\n    say \"\".Bool;                    # OUTPUT: «False␤»\n    say 0.Bool;                     # OUTPUT: «False␤»\n    say 1.Bool;                     # OUTPUT: «True␤»\n    say \"0\".Bool;                   # OUTPUT: «True␤»\n\n=head2 method Capture\n\n    method Capture(Mu:D: --> Capture:D)\n\nReturns a L<C<Capture>|/type/Capture> with named arguments corresponding to\ninvocant's public attributes:\n\n    class Foo {\n        has $.foo = 42;\n        has $.bar = 70;\n        method bar { 'something else' }\n    }.new.Capture.say; # OUTPUT: «\\(:bar(\"something else\"), :foo(42))␤»\n\n=head2 method Str\n\n    multi method Str(--> Str)\n\nReturns a string representation of the invocant, intended to be machine\nreadable. Method L<C<Str>|/type/Str> warns on type objects, and produces the empty string.\n\n    say Mu.Str;   # Use of uninitialized value of type Mu in string context.\n    my @foo = [2,3,1];\n    say @foo.Str  # OUTPUT: «2 3 1␤»\n\n=head2 routine gist\n\n    multi method gist(   --> Str)\n    multi        gist(+args --> Str)\n\nReturns a string representation of the invocant, optimized for fast recognition\nby humans. As such lists will be truncated at 100 elements. Use C<.raku> to get\nall elements.\n\nThe default C<gist> method in C<Mu> re-dispatches to the L<raku|/routine/raku>\nmethod for defined invocants, and returns the type name in parenthesis for type\nobject invocants. Many built-in classes override the case of instances to\nsomething more specific that may truncate output.\n\nC<gist> is the method that L<say|/routine/say> calls implicitly, so C<say\n$something> and C<say $something.gist> generally produce the same output.\n\n    say Mu.gist;        # OUTPUT: «(Mu)␤»\n    say Mu.new.gist;    # OUTPUT: «Mu.new␤»\n\n=head2 method perl\n\n    multi method perl(Mu:)\n\nCalls L«C<.raku>|/routine/raku» on the invocant.  Since the change of the\nlanguage name to Raku, this method is deprecated. Use C<.raku> instead.\n\n=head2 method raku\n\n    multi method raku(Mu:U:)\n    multi method raku(Mu:D:)\n\nFor type objects, returns its name if C<.raku> has not been redefined from\nC<Mu>, or calls C<.raku> on the name of the type object otherwise.\n\n    say Str.raku;          # OUTPUT: «Str␤»\n\nFor plain objects, it will conventionally return a representation of the object\nthat can be used via L«C<EVAL>|/routine/EVAL» to reconstruct the value of the object.\n\n    say (1..3).Set.raku;  # OUTPUT: «Set.new(1,2,3)␤»\n\n=head2 routine item\n\n    method item(Mu \\item:) is raw\n    multi  item(\\x)\n    multi  item(|c)\n    multi  item(Mu $a)\n\nForces the invocant to be evaluated in item context and returns the\nvalue of it.\n\n    say [1,2,3].item.raku;          # OUTPUT: «$[1, 2, 3]␤»\n    say %( apple => 10 ).item.raku; # OUTPUT: «${:apple(10)}␤»\n    say item([1,2,3]).raku;         # OUTPUT: «$[1, 2, 3]␤»\n    say item(\"abc\").raku;           # OUTPUT: «\"abc\"␤»\n\nYou can also use C<$> as item contextualizer.\n\n    say $[1,2,3].raku;              # OUTPUT: «$[1, 2, 3]␤»\n    say $(\"abc\").raku;              # OUTPUT: «\"abc\"␤»\n\n=head2 method self\n\n    method self(--> Mu)\n\nReturns the object it is called on.\n\n=head2 method clone\n\n    multi method clone(Mu:U: *%twiddles)\n    multi method clone(Mu:D: *%twiddles)\n\nThis method will clone type objects, or die if it's invoked with any argument.\n\n=for code\nsay Num.clone( :yes )\n# OUTPUT: «(exit code 1) Cannot set attribute values when cloning a type object␤  in block <unit>␤␤»\n\nIf invoked with value objects, it creates a shallow clone of the invocant,\nincluding shallow cloning of private attributes. Alternative values for\nI<public> attributes can be provided via named arguments with names matching the\nattributes' names.\n\n=begin code\nclass Point2D {\n    has ($.x, $.y);\n    multi method gist(Point2D:D:) {\n        \"Point($.x, $.y)\";\n    }\n}\n\nmy $p = Point2D.new(x => 2, y => 3);\n\nsay $p;                     # OUTPUT: «Point(2, 3)␤»\nsay $p.clone(y => -5);      # OUTPUT: «Point(2, -5)␤»\n=end code\n\nNote that C<.clone> does not go the extra mile to shallow-copy C<@.> and C<%.>\nsigiled attributes and, if modified, the modifications will still be available\nin the original object:\n\n=begin code\nclass Foo {\n    has $.foo is rw = 42;\n    has &.boo is rw = { say \"Hi\" };\n    has @.bar       = <a b>;\n    has %.baz       = <a b c d>;\n}\n\nmy $o1 = Foo.new;\nwith my $o2 = $o1.clone {\n    .foo = 70;\n    .bar = <Z Y>;\n    .baz = <Z Y X W>;\n    .boo = { say \"Bye\" };\n}\n\n# Hash and Array attribute modifications in clone appear in original as well:\nsay $o1;\n# OUTPUT: «Foo.new(foo => 42, bar => [\"Z\", \"Y\"], baz => {:X(\"W\"), :Z(\"Y\")}, …␤»\nsay $o2;\n# OUTPUT: «Foo.new(foo => 70, bar => [\"Z\", \"Y\"], baz => {:X(\"W\"), :Z(\"Y\")}, …␤»\n$o1.boo.(); # OUTPUT: «Hi␤»\n$o2.boo.(); # OUTPUT: «Bye␤»\n=end code\n\nTo clone those, you could implement your own C<.clone> that clones the\nappropriate attributes and passes the new values to C<Mu.clone>, for example,\nvia L«C<nextwith>|/language/functions#sub_nextwith».\n\n=begin code\nclass Bar {\n    has $.quux;\n    has @.foo = <a b>;\n    has %.bar = <a b c d>;\n    method clone { nextwith :foo(@!foo.clone), :bar(%!bar.clone), |%_  }\n}\n\nmy $o1 = Bar.new( :42quux );\nwith my $o2 = $o1.clone {\n    .foo = <Z Y>;\n    .bar = <Z Y X W>;\n}\n\n# Hash and Array attribute modifications in clone do not affect original:\nsay $o1;\n# OUTPUT: «Bar.new(quux => 42, foo => [\"a\", \"b\"], bar => {:a(\"b\"), :c(\"d\")})␤»\nsay $o2;\n# OUTPUT: «Bar.new(quux => 42, foo => [\"Z\", \"Y\"], bar => {:X(\"W\"), :Z(\"Y\")})␤»\n=end code\n\nThe C<|%_> is needed to slurp the rest of the attributes that would have been\ncopied via shallow copy.\n\n=head2 method new\n\n    multi method new(*%attrinit)\n\nDefault method for constructing (create + initialize) new objects\nof a class. This method expects only named arguments which are then\nused to initialize attributes with accessors of the same name.\n\nClasses may provide their own C<new> method to override this default.\n\nC<new> triggers an object construction mechanism that calls submethods named\nC<BUILD> in each class of an inheritance hierarchy, if they exist. See\nL<the documentation on object construction|/language/objects#Object_construction>\nfor more information.\n\n=head2 method bless\n\n    method bless(*%attrinit --> Mu:D)\n\nLow-level object construction method, usually called from within C<new>,\nimplicitly from the default constructor, or explicitly if you create your own\nconstructor. C<bless> creates a new object of the same type as the invocant,\nusing the named arguments to initialize attributes and returns the created\nobject.\n\nIt is usually invoked within custom C<new> method implementations:\n\n=begin code\nclass Point {\n    has $.x;\n    has $.y;\n    multi method new($x, $y) {\n        self.bless(:$x, :$y);\n    }\n}\nmy $p = Point.new(-1, 1);\n=end code\n\nIn this example we are declaring this C<new> method to avoid the extra syntax\nof using pairs when creating the object. C<self.bless> returns the object,\nwhich is in turn returned by C<new>. C<new> is declared as a C<multi method> so\nthat we can still use the default constructor like this:\nC«Point.new( x => 3, y => 8 )».\n\nFor more details see\nL<the documentation on object construction|/language/objects#Object_construction>.\n\n=head2 method CREATE\n\n    method CREATE(--> Mu:D)\n\nAllocates a new object of the same type as the invocant, without\ninitializing any attributes.\n\n    say Mu.CREATE.defined;  # OUTPUT: «True␤»\n\n=head2 routine print\n\n    multi method print(--> Bool:D)\n\nPrints value to C<$*OUT> after stringification using C<.Str> method without\nadding a newline at end.\n\n    \"abc\\n\".print;          # OUTPUT: «abc␤»\n\n=head2 routine put\n\n    multi method put(--> Bool:D)\n\nPrints value to C<$*OUT>, adding a newline at end, and if necessary,\nstringifying non-L<C<Str>|/type/Str> object using the C<.Str> method.\n\n    \"abc\".put;              # OUTPUT: «abc␤»\n\n=head2 routine say\n\n    multi method say()\n\nWill L<C<say>|/type/IO::Handle#method_say> to\nL<standard output|/language/variables#index-entry-$*OUT>.\n\n    say 42;                 # OUTPUT: «42␤»\n\nWhat C<say> actually does is, thus, deferred to the actual subclass. In L<most\ncases|/routine/say> it calls L<C<.gist>|/routine/gist> on the object, returning\na compact string representation.\n\nIn non-sink context, C<say> will always return C<True>.\n\n    say (1,[1,2],\"foo\",Mu).map: so *.say ;\n    # OUTPUT: «1␤[1 2]␤foo␤(Mu)␤(True True True True)␤»\n\nHowever, this behavior is just conventional and you shouldn't trust it for\nyour code. It's useful, however, to explain certain behaviors.\n\nC<say> is first printing out in C<*.say>, but the outermost C<say> is printing\nthe C<True> values returned by the C<so> operation.\n\n=head2 method ACCEPTS\n\n    multi method ACCEPTS(Mu:U: $other)\n\nC<ACCEPTS> is the method that smartmatching with the L<infix ~~|/routine/~~>\noperator and given/when invokes on the right-hand side (the matcher).\n\nThe C<Mu:U> multi performs a type check. Returns C<True> if C<$other> conforms\nto the invocant (which is always a type object or failure).\n\n    say 42 ~~ Mu;           # OUTPUT: «True␤»\n    say 42 ~~ Int;          # OUTPUT: «True␤»\n    say 42 ~~ Str;          # OUTPUT: «False␤»\n\nNote that there is no multi for defined invocants; this is to allow\nautothreading of L<junctions|/type/Junction>, which happens as a fallback\nmechanism when no direct candidate is available to dispatch to.\n\n=head2 method WHICH\n\n    multi method WHICH(--> ObjAt:D)\n\nReturns an object of type L<C<ObjAt>|/type/ObjAt> which uniquely identifies the\nobject. Value types override this method which makes sure that two equivalent\nobjects return the same return value from C<WHICH>.\n\n    say 42.WHICH eq 42.WHICH;       # OUTPUT: «True␤»\n\n=head2 method WHERE\n\n    method WHERE(Mu:)\n\nReturns an L<C<Int>|/type/Int> representing the memory address of the object.  Please note\nthat in the Rakudo implementation of Raku, and possibly other implementations,\nthe memory location of an object is B<NOT> fixed for the lifetime of the\nobject.  So it has limited use for applications, and is intended as a debugging\ntool only.\n\n=head2 method WHY\n\n    multi method WHY(Mu: --> Pod::Block::Declarator)\n\nReturns the attached Pod::Block::Declarator.\n\nFor instance:\n\n=for code :preamble<class Spell {};sub do-raw-magic(Spell) {};> :method<False>\n#| Initiate a specified spell normally\nsub cast(Spell $s) {\n  do-raw-magic($s);\n}\n#= (do not use for class 7 spells)\nsay &cast.WHY;\n# OUTPUT: «Initiate a specified spell normally␤(do not use for class 7 spells)␤»\n\nSee L<Pod declarator blocks|/language/pod#Declarator_blocks> for\ndetails about attaching Pod to variables, classes, functions, methods, etc.\n\n=head2 trait is export\n\n    multi trait_mod:<is>(Mu:U \\type, :$export!)\n\nMarks a type as being exported, that is, available to external users.\n\n    my class SomeClass is export { }\n\nA user of a module or class automatically gets all the symbols imported that\nare marked as C<is export>.\n\nSee L<Exporting and Selective Importing Modules|/language/using-modules/code#Exporting_and_selective_importing>\nfor more details.\n\n=head2 routine return\n\n    method return()\n\nThe method C<return> will stop execution of a subroutine or method, run all\nrelevant L<phasers|/language/phasers#Block_phasers> and provide invocant as a\nreturn value to the caller. If a return\nL<type constraint|/language/signatures#Constraining_return_types> is provided it will be\nchecked unless the return value is L<C<Nil>|/type/Nil>. A control exception is raised and\ncan be caught with L<CONTROL|/language/phasers#CONTROL>.\n\n    sub f { (1|2|3).return };\n    say f(); # OUTPUT: «any(1, 2, 3)␤»\n\n=head2 routine return-rw\n\nSame as routine L<C<return>|/type/Mu#routine_return> except that C<return-rw> returns a writable\ncontainer to the invocant (see more details here: L<C<return-rw>|/language/control#return-rw>).\n\n=head2 routine emit\n\n    method emit()\n\nEmits the invocant into the enclosing\nL<supply|/language/concurrency#index-entry-supply_(on-demand)> or\nL<react|/language/concurrency#react> block.\n\n    react { whenever supply { .emit for \"foo\", 42, .5 } {\n        say \"received {.^name} ($_)\";\n    }}\n\n    # OUTPUT:\n    # received Str (foo)\n    # received Int (42)\n    # received Rat (0.5)\n\n=head2 routine take\n\n    method take()\n    sub    take(\\item)\n\nThe sub takes the given item and passes it to the enclosing C<gather>\nblock.\n\n    #| randomly select numbers for lotto\n    my $num-selected-numbers = 6;\n    my $max-lotto-numbers = 49;\n    gather for ^$num-selected-numbers {\n        take (1 .. $max-lotto-numbers).pick(1);\n    }.say;    # six random values\n\nThe method returns the invocant in the enclosing\nL<gather|/language/control#gather/take> block.\n\n    sub insert($sep, +@list) {\n        gather for @list {\n            FIRST .take, next;\n            take slip $sep, .item\n        }\n    }\n\n    say insert ':', <a b c>;\n    # OUTPUT: «(a : b : c)␤»\n\n=head2 sub take-rw\n\n    sub take-rw(\\item)\n\nReturns the given item to the enclosing C<gather> block, without introducing a new container.\n\n    my @a = 1...3;\n    sub f(@list){ gather for @list { take-rw $_ } };\n    for f(@a) { $_++ };\n    say @a;\n    # OUTPUT: «[2 3 4]␤»\n\n=head2 routine so\n\n    method so()\n\nEvaluates the item in Boolean context (and thus, for instance, collapses Junctions),\nand returns the result.\nIt is the opposite of C<not>, and equivalent to the\nL«C<?> operator|/language/operators#prefix_?».\n\nOne can use this method similarly to the English sentence: \"If that is B<so>,\nthen do this thing\".  For instance,\n\n    my @args = <-a -e -b -v>;\n    my $verbose-selected = any(@args) eq '-v' | '-V';\n    if $verbose-selected.so {\n        say \"Verbose option detected in arguments\";\n    } # OUTPUT: «Verbose option detected in arguments␤»\n\nThe C<$verbose-selected> variable in this case contains a\nL<C<Junction>|/type/Junction>, whose value is C<any(any(False, False),\nany(False, False), any(False, False), any(True, False))>. That is actually a\nI<truish> value; thus, negating it will yield C<False>. The negation of that\nresult will be C<True>. C<so> is performing all those operations under the hood.\n\n=head2 routine not\n\n    method not()\n\nEvaluates the item in Boolean context (leading to final evaluation of Junctions, for instance),\nand negates the result.\nIt is the opposite of C<so> and its behavior is equivalent to the\nL«C<!> operator|/language/operators#prefix_!».\n\n    my @args = <-a -e -b>;\n    my $verbose-selected = any(@args) eq '-v' | '-V';\n    if $verbose-selected.not {\n        say \"Verbose option not present in arguments\";\n    } # OUTPUT: «Verbose option not present in arguments␤»\n\nSince there is also a\nL«prefix version of C<not>|/language/operators#prefix_not»,\nthis example reads better as:\n\n    my @args = <-a -e -b>;\n    my $verbose-selected = any(@args) eq '-v' | '-V';\n    if not $verbose-selected {\n        say \"Verbose option not present in arguments\";\n    } # OUTPUT: «Verbose option not present in arguments␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/NFC.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class NFC\n\n=SUBTITLE Codepoint string in Normal Form C (composed)\n\n    class NFC is Uni {}\n\nA Codepoint string in Unicode Normalization Form C. It is created by Canonical Decomposition,\nfollowed by Canonical Composition. For more information on what this means, see\nL<Unicode TR15|https://www.unicode.org/reports/tr15/>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/NFD.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class NFD\n\n=SUBTITLE Codepoint string in Normal Form D (decomposed)\n\n    class NFD is Uni {}\n\nA Codepoint string in the \"D\" L<Unicode Normalization Form|https://www.unicode.org/reports/tr15/>\n\n=end pod\n"
  },
  {
    "path": "doc/Type/NFKC.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class NFKC\n\n=SUBTITLE Codepoint string in Normal Form KC (compatibility composed)\n\n    class NFKC is Uni {}\n\nA Codepoint string in Unicode Normalization Form KC. It is created by Compatibility Decomposition,\nfollowed by Canonical Composition. For more information on what this means, see\nL<Unicode TR15|https://www.unicode.org/reports/tr15/>.\n=end pod\n"
  },
  {
    "path": "doc/Type/NFKD.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class NFKD\n\n=SUBTITLE Codepoint string in Normal Form KD (compatibility decomposed)\n\n    class NFKD is Uni {}\n\nA Codepoint string in Unicode Normalization Form KD. It is created by Compatibility Decomposition.\nFor more information on what this means, see L<Unicode TR15|https://www.unicode.org/reports/tr15/>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Nil.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Nil\n\n=SUBTITLE Absence of a value\n\n    class Nil is Cool { }\n\nThe value C<Nil> may be used to fill a spot where a value would normally\ngo, and in so doing, explicitly indicate that no value is present. It\nmay also be used as a cheaper and less explosive alternative to a\nL<C<Failure>|/type/Failure>.  (In fact, class L<C<Failure>|/type/Failure> is derived from C<Nil>,\nso smartmatching C<Nil> will also match L<C<Failure>|/type/Failure>.)\n\nThe class C<Nil> is the same exact thing as its only possible value, C<Nil>.\n\n    say Nil === Nil.new;        # OUTPUT: «True␤»\n\nAlong with L<C<Failure>|/type/Failure>, C<Nil> and its subclasses may always be returned from a\nroutine even when the routine specifies a particular return type. It may also\nbe returned regardless of the definedness of the return type, however, C<Nil>\nis considered undefined for all other purposes.\n\n    sub a( --> Int:D ) { return Nil }\n    a().say;                    # OUTPUT: «Nil␤»\n\nC<Nil> is what is returned from empty routines or closure, or routines\nthat use a bare C<return> statement.\n\n    sub a { }; a().say;         # OUTPUT: «Nil␤»\n    sub b { return }; b().say;  # OUTPUT: «Nil␤»\n    say (if 1 { });             # OUTPUT: «Nil␤»\n    { ; }().say;                # OUTPUT: «Nil␤»\n    say EVAL \"\";                # OUTPUT: «Nil␤»\n\nIn a list, C<Nil> takes the space of one value.  Iterating C<Nil>\nbehaves like iteration of any non-iterable value, producing a sequence\nof one C<Nil>. (When you need the other meaning, the special value\nL<Empty|/type/Slip#constant_Empty> is available to take no spaces when inserted into\nlist, and to return no values when iterated.)\n\n    (1, Nil, 3).elems.say;      # OUTPUT: «3␤»\n    (for Nil { $_ }).raku.say;  # OUTPUT: «(Nil,)␤»\n\nAny method call on C<Nil> of a method that does not exist,\nand consequently, any subscripting operation, will succeed and return\nC<Nil>.\n\n    say Nil.ITotallyJustMadeThisUp;  # OUTPUT: «Nil␤»\n    say (Nil)[100];                  # OUTPUT: «Nil␤»\n    say (Nil){100};                  # OUTPUT: «Nil␤»\n\nX<|Language,Nil assignment>\nWhen assigned to a L<container|/language/containers>, the C<Nil> value (but not any subclass of\nC<Nil>) will attempt to revert the container to its default value; if no\nsuch default is declared, Raku assumes L<C<Any>|/type/Any>.\n\nSince a hash assignment expects two elements, use C<Empty> not C<Nil>, e.g.\n\n    my %h = 'a'..'b' Z=> 1..*;\n    # stuff happens\n    %h = Empty; # %h = Nil will generate an error\n\nHowever, if the container\ntype is constrained with C<:D>, assigning C<Nil> to it will immediately throw\nan exception.  (In contrast, an instantiated L<C<Failure>|/type/Failure> matches C<:D>\nbecause it's a definite value, but will fail to match the actual nominal\ntype unless it happens to be a parent class of L<C<Failure>|/type/Failure>.) Native types can\nnot have default values nor hold a type object. Assigning C<Nil> to a native\ntype container will fail with a runtime error.\n\n    my Int $x = 42;\n    $x = Nil;\n    $x.say;                     # OUTPUT: «(Int)␤»\n\n    sub f( --> Int:D ){ Nil };  # this definedness constraint is ignored\n    my Int:D $i = f;            # this definedness constraint is not ignored, so throws\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::TypeCheck::Assignment: Type check failed in assignment to $y; expected Int but got Any (Any)»\n\n    sub g( --> Int:D ){ fail \"oops\" }; # this definedness constraint is ignored\n    my Any:D $h = g;                   # failure object matches Any:D, so is assigned\n\nbut\n\n=for code :skip-test<compile time error>\nmy Int:D $j = g;\n# It will throw both exceptions:\n# Earlier failure:\n#  oops\n#   in sub g at <unknown file> line 1\n#   in block <unit> at <unknown file> line 1\n#\n# Final error:\n#  Type check failed in assignment to $j; expected Int:D but got Failure (Failure.new(exception...)\n#   in block <unit> at <unknown file> line 1\n\nBecause an untyped variable is type L<C<Any>|/type/Any>, assigning a C<Nil> to one\nwill result in an L<(Any)|/type/Any> type object.\n\n    my $x = Nil;\n    $x.say;          # OUTPUT: «(Any)␤»\n    my Int $y = $x;  # will throw an exception\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::TypeCheck::Assignment: Type check failed in assignment to $y; expected Int but got Any (Any)␤»\n\nIf you are looking for a variable which transforms objects into type\nobjects when said variable appears on the right-hand side, you can\ntype the container as C<Nil>.\n\n    my Nil $x;\n    my Str $s = $x;\n    $s.say;          # OUTPUT: «(Str)␤»\n\nThere is an important exception to this transforms-into-type-object rule:\nassigning C<Nil> to a variable which has a default will restore that default.\n\n    my Int $x is default(42) = -1;\n    my $y = 1;\n    for $x, $y -> $val is rw { $val = Nil unless $val > 0 }\n    $x.say;          # OUTPUT: «42␤»\n\nMethods such as C<BIND-POS>, C<ASSIGN-KEY>, C<ASSIGN-POS> will die;\nC<BIND-KEY> will produce a failure with an L<C<X::Bind>|/type/X::Bind> exception in it, and\nC<STORE> will produce an L<C<X::Assignment::RO>|/type/X::Assignment::RO> exception.\n\n=head1 Methods\n\n=head2 method append\n\n    method append(*@)\n\nWarns the user that they tried to append onto a C<Nil> (or derived type object).\n\n=head2 method gist\n\n    method gist(--> Str:D)\n\nReturns C<\"Nil\">.\n\n=head2 method Str\n\n    method Str()\n\nWarns the user that they tried to stringify a C<Nil>.\n\n=head2 method new\n\n    method new(*@)\n\nReturns C<Nil>\n\n=head2 method prepend\n\n    method prepend(*@)\n\nWarns the user that they tried to prepend onto a C<Nil> or derived type object.\n\n=head2 method push\n\n    method push(*@)\n\nWarns the user that they tried to push onto a C<Nil> or derived type object.\n\n=head2 method unshift\n\n    method unshift(*@)\n\nWarns the user that they tried to unshift onto a C<Nil> or derived type object.\n\n=head2 method ords\n\nReturns an empty L<C<Seq>|/type/Seq>, but will also issue a warning depending on the\ncontext it's used (for instance, a warning about using it in string context\nif used with C<say>).\n\n=head2 method chrs\n\nWill return C<\\0>, and also throw a warning.\n\n=head2 method FALLBACK\n\n    method FALLBACK(| --> Nil) {}\n\nThe L<fallback method|/language/typesystem#index-entry-FALLBACK_(method)>\ntakes any arguments and always returns a C<Nil>.\n\n=head2 method Numeric\n\n    method Numeric()\n\nWarns the user that they tried to numify a C<Nil>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Num.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Num\n\n=SUBTITLE Floating-point number\n\n    class Num is Cool does Real { }\n\nA C<Num> object stores a floating-point number. It is immutable. On most\nplatforms, it's an IEEE 754 64-bit floating point numbers, aka \"double\nprecision\".\n\nX<|Syntax,Inf (definition)>\nX<|Syntax,∞ (definition)>\n=head2 Inf\n\nThe value C<Inf> is an instance of C<Num> and represents value that's too large\nto represent in 64-bit double-precision floating point number (roughly, above\nC<1.7976931348623158e308> for positive C<Inf> and below\nC<-1.7976931348623157e308> for negative C<Inf>) as well as returned from certain\noperations as defined by the\nL<IEEE 754-2008 standard|https://ieeexplore.ieee.org/document/4610935>.\n\n    say 2e300 ** 2e300; # OUTPUT: «Inf␤»\n    say (-1/0).Num;     # OUTPUT: «-Inf␤»\n\nThe C<∞> C<U+221E> Unicode character can be used instead of\nthe word C<Inf> and can be handy when C<Inf> would otherwise require an\nL<unspace|/language/syntax#Unspace>, such as when writing L<C<Complex>|/type/Complex> numbers:\n\n    say Inf+Inf\\i; # Backslash (unspace) before `i` required\n    say ∞+∞i;      # No backslash is needed\n\nNote that there are just two infinities (positive and negative), so even if an\noperation that would instinctively give a \"larger\" infinity is performed, the\nresult in still an infinity of the original magnitude. The infinities can be\ncompared, operated and used as an argument as if they were simply a number\nthat's too big to represent or to signify \"without bounds\" or limits:\n\n    say ∞²;                       # OUTPUT: «Inf␤»\n    say 42 + Inf === ∞;           # OUTPUT: «True␤»\n    say atan ∞;                   # OUTPUT: «1.5707963267949␤»\n    say -∞ < 42 < ∞;              # OUTPUT: «True␤»\n    my  $l := 1, 2, 4, 8 ... Inf; # Infinite sequence (no limits)\n\nIn some cases, it's used as an implicit value to represent \"all of them\"\n\n    say \"House of M\".comb(3,Inf).join(\"←X→\");\n    # OUTPUT: «Hou←X→se ←X→of ←X→M␤»\n\nIn the example above, C<Inf> can be eliminated, since it's the default value for\nthe second argument of L<C<.comb>|/type/Str#routine_comb>, used to indicate how\nmany parts should be returned.\n\nDivision of an infinity by another infinity results in a C<NaN>:\n\n    say ∞/∞;             # OUTPUT: «NaN␤»\n\n=head2 NaN\n\nThe value X<C<NaN>|Reference,NaN (definition)> is an instance of C<Num> and represents a\nfloating point not-a-number value, which is returned from some routines where\na concrete number as the answer is not defined, but a L<C<Numeric>|/type/Numeric> value is still\nacceptable. C<NaN> is L<defined|/routine/defined> and L<boolifies|/routine/Bool>\nto C<True>, but is I<not> numerically equal to any value (including itself).\n\n    say cos ∞;     # OUTPUT: «NaN␤»\n    say (0/0).Num; # OUTPUT: «NaN␤»\n\nTo test for C<NaN>, use L<isNaN|/routine/isNaN> method or L<=== operator|/language/operators#infix_===>:\n\n    say (0/0).isNaN;       # OUTPUT: «True␤»\n    say (0/0).Num === NaN; # OUTPUT: «True␤»\n\n=head2 method new\n\n     multi method new()\n     multi method new($n)\n\nC<Num.new> without argument will create a C<Num> with the value C<0e0>. With an\nargument, it will be coerced to C<Num> and then returned.\n\n\n    say Num.new(⅓); # OUTPUT: «0.3333333333333333␤»\n\n=head2 method rand\n\n    method rand(Num:D: --> Num)\n\nReturns a pseudo random number between 0 and the invocant.\n\n=head2 sub srand\n\n    sub srand(Int $seed --> Int:D)\n\nSeeds the pseudo random number generator used by L<Num.rand|#method_rand> with\nthe provided value. Note that C<srand> is called with a platform dependent\nvalue when a Raku program is started.\n\n=head2 method Capture\n\n    method Capture()\n\nThrows C<X::Cannot::Capture>.\n\n=head2 method Int\n\n    method Int(Num:D:)\n\nConverts the number to an L<C<Int>|/type/Int>. L<Fails|/routine/fail> with\nC<X::Numeric::CannotConvert> if the invocant L«is a C<NaN>|/routine/isNaN»\nor C<Inf>/C<-Inf>. No L<rounding|/routine/round> is performed.\n\n=head2 method Rat\n\n    method Rat(Num:D: Real $epsilon = 1e-6)\n\nConverts the number to a L<C<Rat>|/type/Rat> with C<$epsilon> precision. If the invocant\nis an C<Inf>, C<-Inf>, or C<NaN>, converts them to a L<C<Rat>|/type/Rat> with C<0>\nL<denominator|/routine/denominator> and C<1>, C<-1>, or C<0> L<numerator|/routine/numerator>, respectively.\n\n=head2 method FatRat\n\n    method FatRat(Num:D: Real $epsilon = 1e-6)\n\nConverts the number to a L<C<FatRat>|/type/FatRat> with the precision C<$epsilon>. If invocant\nis an C<Inf>, C<-Inf>, or C<NaN>, converts them to a L<C<FatRat>|/type/FatRat> with C<0>\nL<denominator|/routine/denominator> and C<1>, C<-1>, or C<0> L<numerator|/routine/numerator>, respectively.\n\n=head2 method Num\n\n    method Num()\n\nReturns the invocant.\n\n=head2 method Str\n\n    method Str(Int:D)\n\nReturns a string representation of the number.\n\n    say π.Str;                # OUTPUT: «3.141592653589793␤»\n\nL«C<Cool>|/type/Cool» being a parent class of C<Num>, an explicit call\nto the C<Num.Str> method is seldom needed.\n\n    say π.Str.comb == π.comb; # OUTPUT: «True␤»\n\n=head2 method Bridge\n\n    method Bridge(Num:D:)\n\nReturns the number.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/NumStr.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class NumStr\n\n=SUBTITLE Dual value floating-point number and string\n\n    class NumStr is Allomorph is Num { }\n\nC<NumStr> is a dual value type, a subclass of both\nL«C<Allomorph>|/type/Allomorph», hence L«C<Str>|/type/Str», and\nL«C<Num>|/type/Num».\n\nSee L«C<Allomorph>|/type/Allomorph» for further details.\n\n=begin code\nmy $num-str = <42.1e0>;\nsay $num-str.^name;         # OUTPUT: «NumStr␤»\n\nmy Num $num = $num-str;     # OK!\nmy Str $str = $num-str;     # OK!\n\n# ∈ operator cares about object identity\nsay 42e10 ∈ <42e10  55  1>; # OUTPUT: «False␤»\n=end code\n\n=head1 Methods\n\n=head2 method new\n\n    method new(Num $i, Str $s)\n\nThe constructor requires both the L<C<Num>|/type/Num> and the L<C<Str>|/type/Str> value, when constructing one\ndirectly the values can be whatever is required:\n\n    my $f = NumStr.new(42.1e0, \"forty two and a bit\");\n    say +$f; # OUTPUT: «42.1␤»\n    say ~$f; # OUTPUT: «\"forty two and a bit\"␤»\n\n=head2 method Num\n\n    method Num\n\nReturns the L<C<Num>|/type/Num> value of the C<NumStr>.\n\n=head2 method Numeric\n\n    multi method Numeric(NumStr:D: --> Num:D)\n    multi method Numeric(NumStr:U: --> Num:D)\n\nThe C<:D> variant returns the numeric portion of the invocant. The C<:U> variant issues\na warning about using an uninitialized value in numeric context and then returns value C<0e0>.\n\n=head2 method Real\n\n    multi method Real(NumStr:D: --> Num:D)\n    multi method Real(NumStr:U: --> Num:D)\n\nThe C<:D> variant returns the numeric portion of the invocant. The C<:U> variant issues\na warning about using an uninitialized value in numeric context and then returns value C<0e0>.\n\n=head1 Operators\n\n=head2 infix C«===»\n\n    multi infix:<===>(NumStr:D $a, NumStr:D $b)\n\nC<NumStr> Value identity operator. Returns C<True> if the L<C<Num>|/type/Num>\nvalues of C<$a> and C<$b> are L<identical|/routine/===> and their L<C<Str>|/type/Str>\nvalues are also L<identical|/routine/===>. Returns C<False> otherwise.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Numeric.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE role Numeric\n\n=SUBTITLE Number or object that can act as a number\n\n    role Numeric { ... }\n\nCommon role for numbers and types that can act as numbers.\n\nBinary numeric operations return an object of the \"wider\" type:\n\n=begin code :lang<text>\nInt         narrowest\nRat\nFatRat\nNum\nComplex     widest\n=end code\n\nSo for example the product of a L<C<Rat>|/type/Rat> and an L<C<Int>|/type/Int> is a L<C<Rat>|/type/Rat>.\n\nUnary operations that in pure math usually return an irrational number\ngenerally return L<C<Num>|/type/Num> in Raku.\n\n=head1 Methods\n\n=head2 method Numeric\n\n    multi method Numeric(Numeric:D: --> Numeric:D)\n    multi method Numeric(Numeric:U: --> Numeric:D)\n\nThe C<:D> variant simply returns the invocant. The C<:U> variant issues a warning about using\nan uninitialized value in numeric context and then returns C<self.new>.\n\n=head2 method narrow\n\n    method narrow(Numeric:D --> Numeric:D)\n\nReturns the number converted to the narrowest type that can hold it without\nloss of precision.\n\n    say (4.0 + 0i).narrow.raku;     # OUTPUT: «4␤»\n    say (4.0 + 0i).narrow.^name;    # OUTPUT: «Int␤»\n\n=head2 method ACCEPTS\n\n    multi method ACCEPTS(Numeric:D: $other)\n\nReturns C<True> if C<$other> can be coerced to C<Numeric> and\nis L<numerically equal|/routine/==, infix ⩵> to the invocant (or both evaluate\nto C<NaN>).\n\n=head2 routine log\n\n    multi        log(Numeric:D, Numeric $base = e --> Numeric:D)\n    multi method log(Numeric:D: Numeric $base = e --> Numeric:D)\n\nCalculates the logarithm to base C<$base>. Defaults to the natural logarithm.\nThrows an exception if C<$base> is C<1>.\n\nReturns C<NaN> for negative arguments.  As of 6.e language version (early\nimplementation exists in Rakudo compiler 2023.02+), will return a\nL<C<Complex>|/type/Complex> value for negative arguments.\n\n=head2 routine log10\n\n    multi        log10(Numeric:D  --> Numeric:D)\n    multi method log10(Numeric:D: --> Numeric:D)\n\nCalculates the logarithm to base 10. Returns C<-Inf> for C<0>.\n\nReturns C<NaN> for negative arguments.  As of 6.e language version (early\nimplementation exists in Rakudo compiler 2023.02+), will return a\nL<C<Complex>|/type/Complex> value for negative arguments.\n\n=head2 routine log2\n\n    multi        log2(Numeric:D)\n    multi method log2(Numeric:D:)\n\nCalculates the logarithm to base 2. Returns C<-Inf> for C<0>.\n\nReturns C<NaN> for negative arguments.  As of 6.e language version (early\nimplementation exists in Rakudo compiler 2023.02+), will return a\nL<C<Complex>|/type/Complex> value for negative arguments.\n\n=head2 routine exp\n\n    multi        exp(Numeric:D, Numeric:D $base = e --> Numeric:D)\n    multi method exp(Numeric:D: Numeric:D $base = e --> Numeric:D)\n\nReturns C<$base> to the power of the number, or C<e> to the power of the\nnumber if called without a second argument.\n\n=head2 method roots\n\n    multi method roots(Numeric:D: Int:D $n --> Positional)\n\nReturns a list of the C<$n> complex roots, which evaluate to the original\nnumber when raised to the C<$n>th power.\n\n=head2 routine abs\n\n    multi        abs(Numeric:D  --> Real:D)\n    multi method abs(Numeric:D: --> Real:D)\n\nReturns the absolute value of the number.\n\n=head2 routine sqrt\n\n    multi        sqrt(Numeric:D --> Numeric:D)\n    multi method sqrt(Numeric:D --> Numeric:D)\n\nReturns a square root of the number. For real numbers the positive square\nroot is returned.\n\nOn negative real numbers, C<sqrt> returns L<C<NaN>|/type/Num#NaN> rather than a complex number,\nin order to not confuse people who are not familiar with complex arithmetic.\nIf you want to calculate complex square roots, coerce to L<C<Complex>|/type/Complex> first, or\nuse the C<roots> method.\n\nAs of 6.e language version (early implementation exists in Rakudo compiler\n2023.02+), B<will> return a L<C<Complex>|/type/Complex> value for negative\narguments.\n\n=head2 method Bool\n\n    multi method Bool(Numeric:D:)\n\nReturns C<False> if the number is equivalent to zero, and C<True> otherwise.\n\n=head2 method succ\n\n    method succ(Numeric:D:)\n\nReturns the number incremented by one (successor).\n\n=head2 method pred\n\n    method pred(Numeric:D:)\n\nReturns the number decremented by one (predecessor).\n\n=end pod\n"
  },
  {
    "path": "doc/Type/ObjAt.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class ObjAt\n\n=SUBTITLE Unique identification for an object\n\n    class ObjAt is Any {}\n\nObjects of type C<ObjAt> are the return value of C<.WHICH> calls on other\nobjects, and identify an object uniquely.\n\nIf two objects compare equally via C<===>, their C<.WHICH> methods return\nthe same ObjAt object.\n\nSee also L<C<ValueObjAt>|/type/ValueObjAt> for value types.\n\n=head1 Methods\n\n=head2 infix eqv\n\n    multi infix:<eqv>(ObjAt:D $a, ObjAt:D $b)\n\nReturns True if the two ObjAt are the same, that is, if the object they identify\nis the same.\n\n    my @foo = [2,3,1];\n    my @bar := @foo;\n    say @foo.WHICH eqv @bar.WHICH; # OUTPUT: «True␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Order.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"enum\") :category(\"domain-specific\")\n\n=TITLE enum Order\n\n=SUBTITLE Human readable form for comparison operators.\nX<|Reference,Less>X<|Reference,Same>X<|Reference,More>\n\n    enum Order (:Less(-1), :Same(0), :More(1));\n\n=head1 Operators\n\n=head2 infix cmp\n\n    multi infix:<cmp>(\\a, \\b --> Order:D)\n\nC<cmp> will first try to compare operands as strings (via coercion to L<C<Stringy>|/type/Stringy>), and, failing that, will try to compare numerically via the C«<=>» operator or any other type-appropriate comparison operator. See also L<the documentation for the C<cmp> operator|/routine/cmp#(Operators)_infix_cmp>.\n\n\n=head2 infix C«<=>»\n\n   multi infix:«<=>»(Int:D \\a, Int:D \\b --> Order:D)\n\nSpecialized form for Int.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Pair.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class Pair\n\n=SUBTITLE Key/value pair\n\n    class Pair does Associative {}\n\nConsists of two parts, a I<key> and a I<value>. C<Pair>s can be seen as the\natomic units in L<C<Hash>|/type/Hash>es, and they are also used in conjunction with named\narguments and parameters.\n\nX<|Language,colon pair (Pair)>\nX<|Syntax,:> X«|Syntax,=>» X<|Syntax,:!> X<|Syntax,:$>\nThere are many syntaxes for creating C<Pair>s:\n\n    Pair.new('key', 'value'); # The canonical way\n    'key' => 'value';         # this...\n    :key<value>;              # ...means the same as this\n    :key<value1 value2>;      # But this is  key => <value1 value2>\n    :foo(127);                # short for  foo => 127\n    :127foo;                  # the same   foo => 127\n\nNote that last form supports Non-ASCII numerics as well:\n\n    # use MATHEMATICAL DOUBLE-STRUCK DIGIT THREE\n    say (:𝟛math-three);         # OUTPUT: «math-three => 3␤»\n\nBut not I<synthetic> (i.e. formed by a digit and additional Unicode marks):\n\n=for code :skip-test<Will fail>\nsay :7̈a\n\nYou can also use an I<identifier-like literal> as key; this will not need the\nquotes as long as it follows the syntax of\nL<ordinary identifiers|/language/syntax#Ordinary_identifiers>:\n\n    (foo => 127)              # the same   foo => 127\n\nVariants of this are\n\n    :key;                     # same as   key => True\n    :!key;                    # same as   key => False\n\nAnd this other variant, to be used in routine invocation\n\n=begin code\nsub colon-pair( :$key-value ) {\n    say $key-value;\n}\nmy $key-value = 'value';\ncolon-pair( :$key-value );               # OUTPUT: «value␤»\ncolon-pair( key-value => $key-value );   # OUTPUT: «value␤»\n=end code\n\n\nX<|Language,colon list (Pair)>\nColon pairs can be chained without a comma to create a List of Pairs. Depending\non context you may have to be explicit when assigning colon lists.\n\n    sub s(*%h){ say %h.raku };\n    s :a1:b2;\n    # OUTPUT: «{:a1, :b2}␤»\n\n    my $manna = :a1:b2:c3;\n    say $manna.^name;\n    # OUTPUT: «Pair␤»\n\n    $manna = (:a1:b2:c3);\n    say $manna.^name;\n    # OUTPUT: «List␤»\n\nAny variable can be turned into a C<Pair> of its name and its value.\n\n    my $bar = 10;\n    my $p   = :$bar;\n    say $p; # OUTPUT: «bar => 10␤»\n\n\nIt is worth noting that when assigning a L<C<Scalar>|/type/Scalar> as value of a\nC<Pair> the value holds the container of the value itself. This means that it is\npossible to change the value from outside of the C<Pair> itself:\n\n=begin code\nmy $v = 'value A';\nmy $pair = a => $v;\n$pair.say;  # OUTPUT: «a => value A␤»\n\n$v = 'value B';\n$pair.say;  # OUTPUT: «a => value B␤»\n=end code\n\nPlease also note that this behavior is totally unrelated to the way used to\nbuild the C<Pair> itself (i.e., explicit usage of C<new>, use of colon, fat\narrow), as well as if the C<Pair> is bound to a variable.\n\nIt is possible to change the above behavior forcing the C<Pair> to remove the\nscalar container and to hold the effective value itself via the method\nL<freeze|/type/Pair#method_freeze>:\n\n=begin code\nmy $v = 'value B';\nmy $pair = a => $v;\n$pair.freeze;\n$v = 'value C';\n$pair.say; # OUTPUT: «a => value B␤»\n=end code\n\nAs Pair implements L<C<Associative>|/type/Associative> role, its value can be\naccessed using Associative subscription operator, however, due to Pair's\nsingular nature, the pair's value will be only returned for the pair's key.\nL<C<Nil>|/type/Nil> object will be returned for any other key. Subscript\nadverbs such as C<:exists> can be used on Pair.\n\n=for code\nmy $pair = a => 5;\nsay $pair<a>;           # OUTPUT: «5␤»\nsay $pair<a>:exists;    # OUTPUT: «True␤»\nsay $pair<no-such-key>; # OUTPUT: «Nil␤»\n\n=head1 Methods\n\n=head2 method new\n\n    multi method new(Pair: Mu  $key, Mu  $value)\n    multi method new(Pair: Mu :$key, Mu :$value)\n\nConstructs a new C<Pair> object.\n\n=head2 method ACCEPTS\n\n    multi method ACCEPTS(Pair:D $: %topic)\n    multi method ACCEPTS(Pair:D $: Pair:D $topic)\n    multi method ACCEPTS(Pair:D $: Mu $topic)\n\nIf C<%topic> is an L<C<Associative>|/type/Associative>, looks up the value using invocant's key in\nit and checks invocant's value C<.ACCEPTS> that value:\n\n    say %(:42a) ~~ :42a; # OUTPUT: «True␤»\n    say %(:42a) ~~ :10a; # OUTPUT: «False␤»\n\nIf C<$topic> is another C<Pair>, checks the invocant's key and value\nC<.ACCEPTS> the C<$topic>'s key and value respectively:\n\n    say :42a ~~ :42a; # OUTPUT: «True␤»\n    say :42z ~~ :42a; # OUTPUT: «False␤»\n    say :10a ~~ :42a; # OUTPUT: «False␤»\n\nIf C<$topic> is any other value, the invocant C<Pair>'s key is treated as a method name.\nThis method is called on C<$topic>, the L«C<Bool>|/type/Bool» result of which is compared\nagainst the invocant C<Pair>'s L«C<Bool>|/type/Bool» value. For example, primality can\nbe tested using smartmatch:\n\n    say 3 ~~ :is-prime;             # OUTPUT: «True␤»\n    say 3 ~~  is-prime => 'truthy'; # OUTPUT: «True␤»\n    say 4 ~~ :is-prime;             # OUTPUT: «False␤»\n\nThis form can also be used to check\nL<C<Bool>|/type/Bool> values of multiple methods on the same object, such as\nL<C<IO::Path>|/type/IO::Path>, by using L<C<Junction>|/type/Junction>s:\n\n    say \"foo\" .IO ~~ :f & :rw; # OUTPUT: «False␤»\n    say \"/tmp\".IO ~~ :!f;      # OUTPUT: «True␤»\n    say \".\"   .IO ~~ :f | :d;  # OUTPUT: «True␤»\n\n=head2 method antipair\n\n    method antipair(Pair:D: --> Pair:D)\n\nReturns a new C<Pair> object with key and value exchanged.\n\n    my $p = (d => 'Raku').antipair;\n    say $p.key;         # OUTPUT: «Raku␤»\n    say $p.value;       # OUTPUT: «d␤»\n\n=head2 method key\n\n    multi method key(Pair:D:)\n\nReturns the I<key> part of the C<Pair>.\n\n    my $p = (Raku => \"d\");\n    say $p.key; # OUTPUT: «Raku␤»\n\n=head2 method value\n\n    multi method value(Pair:D:) is rw\n\nReturns the I<value> part of the C<Pair>.\n\n    my $p = (Raku => \"d\");\n    say $p.value; # OUTPUT: «d␤»\n\n=head2 infix cmp\n\n    multi infix:<cmp>(Pair:D, Pair:D)\n\nThe type-agnostic comparator; compares two C<Pair>s. Compares first their\nI<key> parts, and then compares the I<value> parts if the keys are equal.\n\n    my $a = (Apple => 1);\n    my $b = (Apple => 2);\n    say $a cmp $b; # OUTPUT: «Less␤»\n\n=head2 method fmt\n\n    multi method fmt(Pair:D: Str:D $format --> Str:D)\n\nTakes a I<format string>, and returns a string the I<key> and I<value>\nparts of the C<Pair> formatted. Here's an example:\n\n    my $pair = :Earth(1);\n    say $pair.fmt(\"%s is %.3f AU away from the sun\")\n    # OUTPUT: «Earth is 1.000 AU away from the sun␤»\n\nFor more about format strings, see L<sprintf|/routine/sprintf>.\n\n=head2 method kv\n\n    multi method kv(Pair:D: --> Seq:D)\n\nReturns a two-element L<C<Seq>|/type/Seq> with the I<key> and I<value> parts of\nC<Pair>, in that order. This method is a special case of the same-named\nmethod on L<C<Hash>|/type/Hash>, which returns all its entries as a list of keys and\nvalues.\n\n    my $p = (Raku => \"d\");\n    say $p.kv[0]; # OUTPUT: «Raku␤»\n    say $p.kv[1]; # OUTPUT: «d␤»\n\n=head2 method pairs\n\n    multi method pairs(Pair:D:)\n\nReturns a list of one C<Pair>, namely this one.\n\n    my $p = (Raku => \"d\");\n    say $p.pairs.^name; # OUTPUT: «List␤»\n    say $p.pairs[0];    # OUTPUT: «Raku => d␤»\n\n=head2 method antipairs\n\n    multi method antipairs(Pair:D:)\n\nReturns a L<C<List>|/type/List> containing the L<antipair|/type/Pair#method_antipair>\nof the invocant.\n\n    my $p = (d => 'Raku').antipairs;\n    say $p.^name;                                     # OUTPUT: «List␤»\n    say $p.first;                                     # OUTPUT: «Raku => d␤»\n    say $p.first.^name;                               # OUTPUT: «Pair␤»\n\n=head2 method invert\n\n    method invert(Pair:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq>. If the C<.value> of the invocant is I<NOT> an\nL<C<Iterable>|/type/Iterable>, the L<C<Seq>|/type/Seq> will contain a single C<Pair> whose\nC<.key> is the C<.value> of the invocant and whose C<.value> is the C<.key> of\nthe invocant:\n\n    :foo<bar>.invert.raku.say; # OUTPUT: «(:bar(\"foo\"),).Seq␤»\n\nIf invocant's C<.value> I<is> an L<C<Iterable>|/type/Iterable>, the returned L<C<Seq>|/type/Seq>\nwill contain the same number of C<Pair>s as items in the C<.value>, with each\nof those items a C<.key> of a pair and the C<.key> of the invocant the C<.value>\nof that pair:\n\n    :foo<Raku is great>.invert.raku.say;\n    # OUTPUT: «(:Raku(\"foo\"), :is(\"foo\"), :great(\"foo\")).Seq␤»\n\n    :foo{ :42a, :72b }.invert.raku.say;\n    # OUTPUT: «((:a(42)) => \"foo\", (:b(72)) => \"foo\").Seq␤»\n\nTo perform the exact C<.key> and C<.value> swap, use\nL«C<.antipair> method|/type/Pair#method_antipair».\n\n=head2 method keys\n\n    multi method keys(Pair:D: --> List:D)\n\nReturns a L<C<List>|/type/List> containing the L<key|/type/Pair#method_key>\nof the invocant.\n\n    say (Raku => \"d\").keys;                           # OUTPUT: «(Raku)␤»\n\n=head2 method values\n\n    multi method values(Pair:D: --> List:D)\n\nReturns a L<C<List>|/type/List> containing the L<value|/type/Pair#method_value>\nof the invocant.\n\n    say (Raku => \"d\").values;                         # OUTPUT: «(d)␤»\n\n=head2 method freeze\n\n    method freeze(Pair:D:)\n\nMakes the I<value> of the C<Pair> read-only, by removing it from its L<Scalar container|/language/containers#Scalar_containers>, and returns it.\n\n    my $str = \"apple\";\n    my $p = Pair.new('key', $str);\n    $p.value = \"orange\";              # this works as expected\n    $p.say;                           # OUTPUT: «key => orange␤»\n    $p.freeze.say;                    # OUTPUT: «orange␤»\n    $p.value = \"a new apple\";         # Fails\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Assignment::RO: Cannot modify an immutable Str (apple)␤»\n\nB<NOTE:> this method is deprecated as of B<6.d> language version. Instead,\ncreate a new C<Pair>, with a L<decontainerized|/language/glossary#decont> key/value.\n\n=for code :preamble<my $p>\n$p.=Map.=head.say;                                    # OUTPUT: «orange␤»\n\n=head2 method Str\n\n    multi method Str(Pair:D: --> Str:D)\n\nReturns a string representation of the invocant formatted\nas I<key ~ \\t ~ value>.\n\n    my $b = eggs => 3;\n    say $b.Str;                                       # OUTPUT: «eggs  3␤»\n\n=head2 method Pair\n\n    method Pair()\n\nReturns the invocant C<Pair> object.\n\n    my $pair = eggs => 3;\n    say $pair.Pair === $pair;                         # OUTPUT: «True␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Parameter.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Parameter\n\n=SUBTITLE Element of a Signature\n\n    class Parameter { }\n\nRepresents a parameter, for purpose of introspection.\n\nThe usual way to obtain a C<Parameter> object is to create a signature,\nand call C<.params> on it to obtain a list of the parameters.\n\n    my $sig   = :(Str $x);\n    my $param = $sig.params[0];\n    say $param.type;              # OUTPUT: «Str()␤»\n\nSee L<C<Signature>|/type/Signature> for more information, and also for an explanation\non what most of the concepts related to parameters mean.\n\n=head1 Methods\n\n=head2 method name\n\n    method name(Parameter:D: --> Str:D)\n\nReturns the parameter name, which includes\nall L<sigils|/language/variables#Sigils> and\nL<twigils|/language/variables#Twigils>.\nThis name is used internally when applied to code, or in a declaration\nto determine the declared the name.  This name is not necessarily\nusable by a caller – if it is, it will also appear as an\nL<alias|#method named_names>.  Often, the name will be chosen descriptively\nas a form of self-documentation.\n\nIf the parameter is anonymous, an empty string will be returned.\n\nB<Note:> Before Rakudo release 2020.08 the return value for an anonymous\nparameter was L<C<Nil>|/type/Nil>.\n\n=for code\nmy Signature $sig = :(Str $x, Bool);\nsay $sig.params[0].name;                 # OUTPUT: «$x␤»\nsay $sig.params[1].name;                 # OUTPUT: «␤»\n\n=head2 method usage-name\n\n    method usage-name(Parameter:D: --> Str:D)\n\nReturns the parameter name without any\nL<sigils|/language/variables#Sigils> and\nL<twigils|/language/variables#Twigils>.\n\nIf the parameter is anonymous, an empty string will be returned.\n\nB<Note:> Before Rakudo release 2020.08 the return value for an anonymous\nparameter was L<C<Nil>|/type/Nil>.\n\n=for code\nmy Signature $sig = :(Str $x, Str @*l, Bool);\nsay $sig.params[0].usage-name;           # OUTPUT: «x␤»\nsay $sig.params[1].usage-name;           # OUTPUT: «l␤»\nsay $sig.params[2].usage-name;           # OUTPUT: «␤»\n\n=head2 method sigil\n\n    method sigil(Parameter:D: --> Str:D)\n\nReturns a string containing the parameter's sigil, for a looser\ndefinition of \"sigil\" than what is considered part of\nthe parameter's L«C<name>|#method name».  Still returns a sigil even\nif the parameter is anonymous.\n\nThis \"sigil\" is actually an introspection used to help determine\nthe normal binding style of a parameter, if it has not been altered\nthrough a L<trait|/language/signatures#Parameter_traits_and_modifiers>.\n\n=begin table\nSigil | Will bind to           | Default behavior\n===================================================\n $    | Scalar                 | Generate new Scalar, use instead of Scalar in argument, if any\n @    | Positional             | Bind directly to the argument\n @    | PositionalBindFailover | If binding failed, call argument's .cache method, bind to result\n %    | Associative            | Bind directly to the argument\n &    | Callable               | Bind directly to the argument\n \\    | (anything)             | Bind directly to the argument, keep existing Scalar, if any\n=end table\n\nAlso, C<|> will bind to all remaining arguments and make new L<C<Capture>|/type/Capture> if needed.\n\n=head2 method type\n\nReturns the L<nominal type constraint|/language/signatures#Type_constraints> of\nthe parameter.\n\n=head2 method coerce_type\n\nReturns the L<coercion type|/syntax/Coercion%20type> of the parameter.\n\n=head2 method constraints\n\nReturns L<additional constraints|/language/signatures#Type_constraints> on the\nparameter (usually as an C<all>-Junction).\n\n=head2 method named\n\n    method named(Parameter:D: --> Bool:D)\n\nReturns C<True> if it's a L<named parameter|/language/signatures#Positional_vs._named_arguments>.\n\n    my Signature $sig = :(Str $x, Bool :$is-named);\n    say $sig.params[0].named;                          # OUTPUT: «False␤»\n    say $sig.params[1].named;                          # OUTPUT: «True␤»\n\n=head2 method named_names\n\n    method named_names(Parameter:D: --> List:D)\n\nReturns the list of externally usable names/aliases for a\nL<named parameter|/language/signatures#Positional_vs._named_arguments>.\n\n=head2 method positional\n\n    method positional(Parameter:D: --> Bool:D)\n\nReturns C<True> if the parameter is\nL<positional|/language/signatures#Positional_vs._named_arguments>.\n\n    my Signature $sig = :(Str $x, Bool :$is-named);\n    say $sig.params[0].positional;                     # OUTPUT: «True␤»\n    say $sig.params[1].positional;                     # OUTPUT: «False␤»\n\n=head2 method slurpy\n\n    method slurpy(Parameter:D: --> Bool:D)\n\nReturns C<True> for\nL<slurpy parameters|/language/signatures#Slurpy_parameters>.\n\n=head2 method twigil\n\n    method twigil(Parameter:D: --> Str:D)\n\nReturns a string containing the twigil part of the parameter's name.\n\n=head2 method optional\n\n    method optional(Parameter:D: --> Bool:D)\n\nReturns C<True> for\nL<optional parameters|/language/signatures#Optional_and_mandatory_arguments>.\n\n=head2 method raw\n\n    method raw(Parameter:D: --> Bool:D)\n\nReturns C<True> for raw parameters.\n\n    sub f($a, $b is raw, \\c) {\n        my $sig = &?ROUTINE.signature;\n        for ^$sig.params.elems {\n            say $sig.params[$_].raw;\n        }\n    }\n    f(17, \"4711\", 42); # OUTPUT: «False␤True␤True␤»\n\nRaw parameters bind either a variable or a value passed to it, with\nno decontainerization taking place.  That means that if a variable was passed\nto it, you can assign to the parameter. This is different from\nL<rw|#method_rw>-parameter which can only bind to variables, never to values.\n\nThis is the normal behavior for parameters declared with a\nL<sigil|#method sigil> of 'C<\\>', which is not really a sigil insofar\nas it is only used on the parameter.\n\n    sub f(\\x) {\n        x = 5;\n    }\n    f(my $x);   # works\n    f(42);      # dies\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Assignment::RO: Cannot modify an immutable Int␤»\n\nOther parameters may become raw through use of the 'C<is raw>'\nL<trait|/language/signatures#Parameter_traits_and_modifiers>.  These still use\ntheir sigil in code.\n\n    sub f($x is raw) {\n        $x = 5;\n    }\n\nWhen used with slurpy list parameters, the C<is raw> trait will cause the list\nof arguments given to be packed into a L<C<List>|/type/List> instead of an L<C<Array>|/type/Array>, which\nprevents them from being containerized with L<C<Scalar>|/type/Scalar>. This is the default\nbehavior when using C<+> with a sigilless parameter:\n\n    my @types is List = Mu, Any;\n    say -> *@l { @l }(@types)[0] =:= @types[0];        # OUTPUT: «False␤»\n    say -> +@l { @l }(@types)[0] =:= @types[0];        # OUTPUT: «False␤»\n    say -> +l { l }(@types)[0] =:= @types[0];          # OUTPUT: «True␤»\n    say -> *@l is raw { @l }(@types)[0] =:= @types[0]; # OUTPUT: «True␤»\n\n=head2 method capture\n\n    method capture(Parameter:D: --> Bool:D)\n\nReturns C<True> for parameters that capture the rest of the argument list into\na single L<C<Capture>|/type/Capture> object.\n\n    sub how_many_extra_positionals($!, |capture) { capture.elems.say }\n    how_many_extra_positionals(0, 1, 2, 3);                        # OUTPUT: «3␤»\n    say &how_many_extra_positionals.signature.params[1].capture;   # OUTPUT: «True␤»\n\nLike raw parameters, L<C<Capture>|/type/Capture> parameters do not force any context on the\nvalues bound to them, which is why their sigils are only used in\ndeclarations.\n\n=head2 method rw\n\n    method rw(Parameter:D: --> Bool:D)\n\nReturns C<True> for L<C<is rw>|/language/signatures#Parameter_traits_and_modifiers>\nparameters.\n\n    my Signature $sig = :(Str $x is rw, Bool :$is-named);\n    say $sig.params[0].rw;                             # OUTPUT: «True␤»\n    say $sig.params[1].rw;                             # OUTPUT: «False␤»\n\n=head2 method copy\n\n    method copy(Parameter:D: --> Bool:D)\n\nReturns C<True> for L<C<is copy>|/language/signatures#Parameter_traits_and_modifiers>\nparameters.\n\n    my Signature $sig = :(Str $x, Bool :$is-named is copy);\n    say $sig.params[0].copy;                           # OUTPUT: «False␤»\n    say $sig.params[1].copy;                           # OUTPUT: «True␤»\n\n=head2 method readonly\n\n    method readonly(Parameter:D: --> Bool:D)\n\nReturns C<True> for read-only parameters (the default).\n\n    my Signature $sig = :(Str $x is rw, Bool :$is-named);\n    say $sig.params[0].readonly;                       # OUTPUT: «False␤»\n    say $sig.params[1].readonly;                       # OUTPUT: «True␤»\n\n=head2 method invocant\n\n    method invocant(Parameter:D: --> Bool:D)\n\nReturns C<True> if the parameter is the\nL<invocant parameter|/language/signatures#Parameter_separators>.\n\n    my Signature $sig = :($i : Str $x is rw, Bool :$is-named);\n    say $sig.params[0].invocant;                       # OUTPUT: «True␤»\n    say $sig.params[1].invocant;                       # OUTPUT: «False␤»\n\n=head2 method multi-invocant\n\n    method multi-invocant(Parameter:D: --> Bool:D)\n\nReturns C<True> if the parameter affects\nL<multi dispatch|/language/functions#Multi-dispatch>.\n\n    my Signature $sig = :($a;; $b);\n    say $sig.params[0].multi-invocant;                 # OUTPUT: «True␤»\n    say $sig.params[1].multi-invocant;                 # OUTPUT: «False␤»\n\n=head2 method default\n\n    method default(Parameter:D: --> Code:_)\n\nReturns a closure that upon invocation returns the\nL<default value|/language/signatures#Optional_and_mandatory_arguments> for\nthis parameter, or L<C<Code>|/type/Code> if no default was provided.\n\nB<Note:> Before Rakudo release 2020.08 the return value for a parameter\nwith no default value was L<C<Any>|/type/Any>.\n\n=for code\nmy $sig = :($a, $b = 12);\nsay $sig.params[0].default;        # OUTPUT: «(Code)␤»\nsay $sig.params[1].default.();     # OUTPUT: «12␤»\n\n=head2 method type_captures\n\n    method type_captures(Parameter:D: --> List:D)\n\nReturns a list of variable names of L<type captures|/language/signatures#Type_captures> associated with this\nparameter.  Type captures define a type name within the attached code,\nwhich is an alias to the type gleaned from the argument during a call.\n\n    sub a(::T $x) { T.say }\n    a(8);                                       # OUTPUT: «(Int)␤»\n    say &a.signature.params[0].type_captures;   # OUTPUT: «(T)␤»\n    sub b($x) { $x.^name.say }\n    a(8);                                       # OUTPUT: «Int␤»\n\nThe type used may change from call to call.  Once they are defined,\ntype captures can be used wherever you would use a type, even later\nin the same signature:\n\n=begin code\nsub c(::T $x, T $y, $z) { my T $zz = $z };\nc(4, 5, 6);          # OK\n\ntry c(4, 5, \"six\");\ngiven $! { .message.say };\n# OUTPUT: «Type check failed in assignment to $zz; expected Int but got Str (\"six\")␤»\n\ntry c(\"four\", 5, \"six\");\ngiven $! { .message.say };\n# OUTPUT: «Type check failed in binding to parameter '$y'; expected Str but got Int (5)␤»\n=end code\n\nType captures may be used at the same time as\nL<type constraints|/language/signatures#Type_constraints>.\n\n=begin code\nsub d(::T Numeric $x, T $y) {};\nd(4, 5);            # OK\nd(4e0, 5e0);        # OK\n\ntry d(4e0, 5);\ngiven $! { .message.say };\n# OUTPUT: «Type check failed in binding to parameter '$y'; expected Num but got Int (5)␤»\n\ntry d(\"four\", \"five\");\ngiven $! { .message.say };\n# OUTPUT: «Type check failed in binding to parameter '$x'; expected Numeric but got Str (\"four\")␤»\n=end code\n\n=head2 method sub_signature\n\n    method sub_signature(Parameter:D: --> Signature:_)\n\nIf the parameter has a\nL<sub-signature|/language/signatures#Sub-signatures>,\nreturns a L<C<Signature>|/type/Signature> object for it.  Otherwise returns L<C<Signature>|/type/Signature>.\n\nB<Note:> Before Rakudo release 2020.08 the return value for a parameter\nwith no sub-signature was L<C<Any>|/type/Any>.\n\n=for code\nmy Signature $sig = :(@array ($first, *@rest), @other);\nsay $sig.params[0].sub_signature;     # OUTPUT:«($first, *@rest)␤»\nsay $sig.params[1].sub_signature;     # OUTPUT:«(Signature)␤»\n\n=head2 method prefix\n\n    method prefix(Parameter:D: --> Str:D)\n\nIf the parameter is L«slurpy|/language/signatures#Slurpy_parameters»,\nreturns the marker (e.g., C«*», C«**», or C«+») the parameter was declared\nwith. Otherwise, returns an empty string.\n\n    my Signature $flat-slurpy = :($a, *@b);\n    say $flat-slurpy.params[0].prefix; # OUTPUT:«␤»\n    say $flat-slurpy.params[1].prefix; # OUTPUT:«*␤»\n\n    my Signature $unflat-slurpy = :($a, **@b);\n    say $unflat-slurpy.params[0].prefix; # OUTPUT:«␤»\n    say $unflat-slurpy.params[1].prefix; # OUTPUT:«**␤»\n\n    my Signature $sar-slurpy = :($a, +@b);\n    say $sar-slurpy.params[0].prefix; # OUTPUT:«␤»\n    say $sar-slurpy.params[1].prefix; # OUTPUT:«+␤»\n\n=head2 method suffix\n\n    method suffix(Parameter:D: --> Str:D)\n\nReturns the C«?» or C«!» marker a parameter was declared with, if any. Otherwise,\nreturns the empty string.\n\n    my Signature $pos-sig = :($a, $b?);\n    say $pos-sig.params[0].suffix; # OUTPUT: «␤»\n    say $pos-sig.params[1].suffix; # OUTPUT: «?␤»\n\n    my Signature $named-sig = :(:$a!, :$b);\n    say $named-sig.params[0].suffix; # OUTPUT: «!␤»\n    say $named-sig.params[1].suffix; # OUTPUT: «␤»\n\n=head2 method modifier\n\n    method modifier(Parameter:D: --> Str:D)\n\nReturns the L<type smiley|/language/glossary#Type_smiley> (C<:U>, C<:D>, or\nC<:_>) a parameter was declared with. It returns the empty string for the C<:_>\ntype smiley.\n\n    my Signature $sig = :(Str:U $a, UInt:D $b, $c);\n    say $sig.params[0].modifier; # OUTPUT: «:U␤»\n    say $sig.params[1].modifier; # OUTPUT: «:D␤»\n    say $sig.params[2].modifier; # OUTPUT: «␤»\n\n=head1 Runtime creation of Parameter objects (6.d, 2019.03 and later)\n\n   Parameter.new( ... )\n\nIn some situations, specifically when working with the\nL<MetaObject Protocol|/language/mop>, it makes sense to create C<Parameter>\nobjects programmatically.  For this purpose, you can call the C<new> method\nwith the following named parameters:\n\n=item name\n\nOptional.  The name of the parameter, if any.  Can be specified in the same\nway as in a L<C<Signature>|/type/Signature>.  So it may contain specific additional information,\nsuch as a sigil (C<$>, C<@>, C<%> or C<&>), a C<:> prefix to indicate a named\nparameter, a twigil (C<.> or C<!>) to indicate public / private attribute\nbinding, a postfix C<!> or C<?> to indicate an optional / mandatory parameter,\nand the various combinations of C<+>, C<*>, C<**> prefixes to indicate\nslurpiness types and C<|> to indicate a L<C<Capture>|/type/Capture>.\n\n=item type\n\nOptional.  The type of the parameter.  Assumes L<C<Any>|/type/Any> if not specified.\n\n=item default\n\nOptional.  The value of the parameter if the parameter is optional and no\nargument has been given for that parameter.  Assumes not initialization if\nno argument has been given, which would fall back to the (implicit) type\nof the parameter.\n\n=item where\n\nOptional.  Additional constraints to be applied to any argument to match with\nthis parameter.  Does not set any additional constraints by default.\n\n=item is-copy\n\nOptional.  Allows one to set the \"is copy\" flag on the parameter.  Does not\nset the flag by default.\n\n=item is-raw\n\nOptional.  Allows one to set the \"is raw\" flag on the parameter.  Does not\nset the flag by default.\n\n=item is-rw\n\nOptional.  Allows one to set the \"is rw\" flag on the parameter.  Does not\nset the flag by default.\n\n=item named\n\nOptional.  Indicates whether the parameter is a named parameter or not.\nShould only be specified if the C<:> prefix is B<not> specified in the name\nand a named parameter is required.\n\n=item optional\n\nOptional.  Indicates whether the parameter is optional or not.  Should only be\nspecified if the C<?> postfix is B<not> specified in the name and an optional\nparameter is required.\n\n=item mandatory\n\nOptional.  Indicates whether the parameter is mandatory or not.  Should only be\nspecified if the C<!> postfix is B<not> specified in the name and a mandatory\nparameter is required.\n\n=item multi-invocant\n\nOptional.  Indicates whether the parameter should be considered in\nmulti-dispatch or not.  Defaults to C<True>, so one would need to do\nC<:!multi-invocant> to make the parameter B<not> be considered in\nmulti-dispatch.\n\n=item sub-signature\n\nOptional.  Specifies any L<C<Signature>|/type/Signature> that should be applied to the\nparameter to deconstruct it.  By default, no signature is to be applied.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Perl.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Perl\n\n=SUBTITLE Perl related information\n\n    class Perl is Raku { }\n\nA class that provides the same internal language information as the\nL<Raku|/type/Raku> class.  Only maintained for historical reasons.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Pod/Block/Code.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Pod::Block::Code\n\n=SUBTITLE Verbatim code block in a Pod document\n\n    class Pod::Block::Code is Pod::Block { }\n\nClass for a code (verbatim) Pod block.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Pod/Block/Comment.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Pod::Block::Comment\n\n=SUBTITLE Comment in a Pod document\n\n    class Pod::Block::Comment is Pod::Block { }\n\nClass for a Pod comment.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Pod/Block/Declarator.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Pod::Block::Declarator\n\n=SUBTITLE Declarator block in a Pod document\n\n    class Pod::Block::Declarator is Pod::Block { }\n\nClass for a declarator Pod block\n\n=head1 Methods\n\n=head2 method leading\n\n    method leading(Pod::Block::Declarator:D:)\n\nReturns the leading Pod comment attached to the declarator\n\n=head2 method trailing\n\n    method trailing(Pod::Block::Declarator:D:)\n\nReturns the trailing Pod comment attached to the declarator\n\n=head2 method WHEREFORE\n\n    method WHEREFORE(--> Mu)\n\nReturns the code object or metaobject to which the Pod block is attached to\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Pod/Block/Named.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Pod::Block::Named\n\n=SUBTITLE Named block in a Pod document\n\n    class Pod::Block::Named is Pod::Block { }\n\nClass for a named Pod block. For example\n\n=begin code\n=begin MySection\n...\n=end MySection\n=end code\n\ncreates a C<Pod::Block::Named> with name C<MySection>.\n\n=head1 Methods\n\n=head2 method name\n\n    method name(--> Str:D)\n\nReturns the name of the block.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Pod/Block/Para.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Pod::Block::Para\n\n=SUBTITLE Paragraph in a Pod document\n\n    class Pod::Block::Para is Pod::Block { }\n\nClass for a Pod paragraph.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Pod/Block/Table.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Pod::Block::Table\n\n=SUBTITLE Table in a Pod document\n\n    class Pod::Block::Table is Pod::Block { }\n\nClass for a table in a Pod document.\n\n=head1 Methods\n\n=head2 method caption\n\n    method caption(--> Str:D)\n\nReturns the associated caption of the table.\n\n=head2 method headers\n\n    method headers(--> Positional:D)\n\nReturns a list of table headers. If no headers have been defined the\nlist is empty.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Pod/Block.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Pod::Block\n\n=SUBTITLE Block in a Pod document\n\n    class Pod::Block { }\n\nClass for a Pod block, and base class for most other Pod classes.\n\nA Pod block has contents (more pod blocks or strings) and a config hash.\n\nUseful subclasses:\n\n=begin table\n\n    Class                     Used for\n    =====                     ========\n    Pod::Block::Para          paragraphs\n\n    Pod::Block::Named         named blocks\n\n    Pod::Block::Declarator    declarator blocks\n\n    Pod::Block::Code          code blocks\n\n    Pod::Block::Comment       comments\n\n    Pod::Block::Table         =begin/end table\n                              tabular data\n\n    Pod::Heading              =head1 etc. headings\n\n    Pod::Item                 list items\n\n    Pod::Defn                 definition lists\n\n    Pod::FormattingCode       formatting codes\n\n=end table\n\n=head1 Methods\n\n=head2 method contents\n\n    method contents(--> Positional:D)\n\nReturns a list of contents of this block.\n\n=head2 method config\n\n    method config(--> Map:D)\n\nReturns a hash of configs.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Pod/Defn.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Pod::Defn\n\n=SUBTITLE Pod definition list\n\n    class Pod::Defn is Pod::Block { }\n\nClass for definition lists in a Pod document.\n\n=head1 Methods\n\n=head2 method term\n\n    method term(--> Mu)\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Pod/FormattingCode.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Pod::FormattingCode\n\n=SUBTITLE Pod formatting code\n\n    class Pod::FormattingCode is Pod::Block { }\n\nClass for formatting codes in a Pod document.\n\n=head1 Methods\n\n=head2 method type\n\n    method type(--> Mu)\n\n=head2 method meta\n\n    method meta(--> Positional)\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Pod/Heading.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Pod::Heading\n\n=SUBTITLE Heading in a Pod document\n\n    class Pod::Heading is Pod::Block { }\n\nClass for headings in a Pod document.\n\n=head1 Methods\n\n=head2 method level\n\n    method level(--> Int)\n\nReturns the level of the heading, starting at 1.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Pod/Item.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Pod::Item\n\n=SUBTITLE Item in a Pod enumeration list\n\n    class Pod::Item is Pod::Block { }\n\nClass for items in Pod enumeration lists.\n\n=head1 Methods\n\n=head2 method level\n\n    method level(--> Int)\n\nReturns the level of the enumeration list, starting at 1.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Positional.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"composite\")\n\n=TITLE role Positional\n\n=SUBTITLE Object that supports looking up values by index\n\n    role Positional[::T = Mu] { ... }\n\nRole for objects which support indexing them using the\nL«C<[ ]> postcircumfix operator|/language/operators#postcircumfix_[_]»\n(usually list-like objects). Example types with Positional role\ninclude L<C<List>|/type/List>, L<C<Array>|/type/Array>, L<C<Range>|/type/Range>,\nand L<C<Buf>|/type/Buf>.\n\n=head1 Methods\n\n=head2 method of\n\n    method of()\n\nReturns the type constraint for elements of the positional container, that\nis, the C<T> in the definition above, which, as it can be seen, defaults\nto L<C<Mu>|/type/Mu>. It is returned as a type object.\n\n=for code\nmy @þ;\nsay @þ.of.^name;   # OUTPUT: «Mu␤\nmy Str @þð;\nsay @þð.of.raku;   # OUTPUT: «Str␤»\nsay (my int @).of; # OUTPUT: «(int)␤»\n\n=head1 Methods that should be provided by classes that mix in this role\n\n=head2 method elems\n\n    method elems()\n\nShould return the number of available elements in the instantiated object.\n\n=head2 method AT-POS\n\n    method AT-POS(\\position)\n\nShould return the value / container at the given position.\n\n=head2 method EXISTS-POS\n\n    method EXISTS-POS(\\position)\n\nShould return a L<C<Bool>|/type/Bool> indicating whether the given position actually has a\nvalue.\n\n=head2 method STORE\n\n    method STORE(\\values, :$INITIALIZE)\n\nThis method should only be supplied if you want to support the:\n\n=for code :preamble<role Foo {}>\nmy @a is Foo = 1,2,3;\n\nsyntax for binding your implementation of the C<Positional> role.\n\nShould accept the values to (re-)initialize the object with.  The optional\nnamed parameter will contain a C<True> value when the method is called on\nthe object for the first time.  Should return the invocant.\n\n=head1 See also\n\nSee L<Methods to implement for positional subscripting|/language/subscripts#Methods_to_implement_for_positional_subscripting> for information about additional methods that can be implemented for the C<Positional> role.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/PositionalBindFailover.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"composite\")\n\n=TITLE role PositionalBindFailover\n\n=SUBTITLE Failover for binding to a Positional\n\n    role PositionalBindFailover { ... }\n\nThis role provides an interface by which an object can\nbe coerced into a L<C<Positional>|/type/Positional> when binding to L<C<Positional>|/type/Positional> parameters.\n\nFor example, L<C<Seq>|/type/Seq> type is not L<C<Positional>|/type/Positional>, but you can still write\nthe following, because it L<does|/routine/does> C<PositionalBindFailover> role:\n\n    sub fifths(@a) {        # @a is constraint to Positional\n        @a[4];\n    }\n    my $seq := gather {     # a Seq, which is not Positional\n        take $_ for 1..*;\n    }\n    say fifths($seq);       # OUTPUT: «5␤»\n\nThe invocation of C<fifths> in the example above would ordinarily give a type\nerror, because C<$seq> is of type L<C<Seq>|/type/Seq>, which doesn't do the\nL<C<Positional>|/type/Positional> interface that the C<@>-sigil implies.\n\nBut the signature binder recognizes that L<C<Seq>|/type/Seq> does the\nC<PositionalBindFailover> role, and calls its C<cache> method to coerce it to\na L<C<List>|/type/List>, which does the L<C<Positional>|/type/Positional> role.\n\nThe same happens with custom classes that do the role; they simply\nneed to provide an C<iterator> method that produces an L<C<Iterator>|/type/Iterator>:\n\n    class Foo does PositionalBindFailover {\n        method iterator {\n            class :: does Iterator {\n                method pull-one {\n                    return 42 unless $++;\n                    IterationEnd\n                }\n            }.new\n        }\n    }\n\n    sub first-five (@a) { @a[^5].say }\n    first-five Foo.new; # OUTPUT: # OUTPUT: «(42 Nil Nil Nil Nil)␤»\n\n=head1 Methods\n\n=head2 method cache\n\n    method cache(PositionalBindFailover:D: --> List:D)\n\nReturns a L<C<List>|/type/List> based on the C<iterator> method, and caches it.\nSubsequent calls to C<cache> always return the same L<C<List>|/type/List> object.\n\n=head2 method list\n\n    multi method list(::?CLASS:D:)\n\nReturns a L<C<List>|/type/List> based on the C<iterator> method without caching it.\n\n=head2 method iterator\n\n    method iterator(PositionalBindFailover:D:) { ... }\n\nThis method stub ensure that a class implementing role\nC<PositionalBindFailover> provides an C<iterator> method.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/PredictiveIterator.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"basic\")\n\n=TITLE role PredictiveIterator\n\n=SUBTITLE Iterators that can predict number of values\n\nA C<PredictiveIterator> is a special kind of L<C<Iterator>|/type/Iterator> that can know\nhow many values it will (still) generate B<without> actually needing to\ngenerate those values.\n\nThe main addition to the API of the L<C<Iterator>|/type/Iterator> role, is the C<count-only>\nmethod, which should return the number of values the Iterator is still\nable to generate.\n\nThe other addition is the C<bool-only> method, that should return a\nL<C<Bool>|/type/Bool> indicating whether the Iterator is still capable of producing\nvalues (aka, is not exhausted yet).  By default, this is the Booleanification\nof the result of the call to the C<count-only> method.\n\n=head1 Methods\n\n=head2 method count-only\n\n    method count-only(--> Int:D) { ... }\n\nIt is expected to return the number of values the iterator can still produce\nB<without> actually producing them. The returned number B<must adjust itself>\nfor items already pulled, so that the method can be called on a partially\nconsumed L<C<Iterator>|/type/Iterator>.\n\nIt will be used in situations where only the B<number> of values of an iterator\nis needed, e.g. when the C<.elems> method is called.\n\nB<Important:> it's expected the L<C<Iterator>|/type/Iterator>s that implement this method can\nreturn that number B<without> producing any values.  In other words,\nit's expected the user of the class will be able to still L<pull-one|/routine/pull-one>\nafter calling this method, and eventually receive as many values as the\nreturn value of this method indicated.\n\n=head2 method bool-only\n\nDefaults to the Booleanification of the result of calling the C<count-only>\nmethod.  If it is possible to have a faster way of finding out whether the\niterator is capable of producing any value, it should be implemented.\n\n    method bool-only(--> Bool:D) { self.count-only.Bool }\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Proc/Async.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Proc::Async\n\n=SUBTITLE Running process (asynchronous interface)\n\n=begin code\nclass Proc::Async {}\n=end code\n\nC<Proc::Async> allows you to run external commands asynchronously,\ncapturing standard output and error handles, and optionally write to its\nstandard input.\n\n=begin code\nmy $file = ‘foo’.IO;\nspurt $file, “and\\nCamelia\\n♡\\nme\\n”;\n\nmy $proc = Proc::Async.new: :w, ‘tac’, ‘--’, $file, ‘-’;\n# my $proc = Proc::Async.new: :w, ‘sleep’, 15; # uncomment to try timeouts\n\nreact {\n    whenever $proc.stdout.lines { # split input on \\r\\n, \\n, and \\r\n        say ‘line: ’, $_\n    }\n    whenever $proc.stderr { # chunks\n        say ‘stderr: ’, $_\n    }\n    whenever $proc.ready {\n        say ‘PID: ’, $_ # Only in Rakudo 2018.04 and newer, otherwise Nil\n    }\n    whenever $proc.start {\n        say ‘Proc finished: exitcode=’, .exitcode, ‘ signal=’, .signal;\n        done # gracefully jump from the react block\n    }\n    whenever $proc.print: “I\\n♥\\nCamelia\\n” {\n        $proc.close-stdin\n    }\n    whenever signal(SIGTERM).merge: signal(SIGINT) {\n        once {\n            say ‘Signal received, asking the process to stop’;\n            $proc.kill; # sends SIGHUP, change appropriately\n            whenever signal($_).zip: Promise.in(2).Supply {\n                say ‘Kill it!’;\n                $proc.kill: SIGKILL\n            }\n        }\n    }\n    whenever Promise.in(5) {\n        say ‘Timeout. Asking the process to stop’;\n        $proc.kill; # sends SIGHUP, change appropriately\n        whenever Promise.in(2) {\n            say ‘Timeout. Forcing the process to stop’;\n            $proc.kill: SIGKILL\n        }\n    }\n}\n\nsay ‘Program finished’;\n=end code\n\nExample above produces the following output:\n=begin code :lang<text>\nline: me\nline: ♡\nline: Camelia\nline: and\nline: Camelia\nline: ♥\nline: I\nProc finished: exitcode=0 signal=0\nProgram finished\n=end code\n\nAlternatively, you can use C<Proc::Async> without using a\nL<react|/language/concurrency#react> block:\n\n    # command with arguments\n    my $proc = Proc::Async.new('echo', 'foo', 'bar');\n\n    # subscribe to new output from out and err handles:\n    $proc.stdout.tap(-> $v { print \"Output: $v\" }, quit => { say 'caught exception ' ~ .^name });\n    $proc.stderr.tap(-> $v { print \"Error:  $v\" });\n\n    say \"Starting...\";\n    my $promise = $proc.start;\n\n    # wait for the external program to terminate\n    await $promise;\n    say \"Done.\";\n\nThis produces the following output:\n\n=begin code :lang<text>\nStarting...\nOutput: foo bar\nDone.\n=end code\n\nAn example that opens an external program for writing:\n\n    my $prog = Proc::Async.new(:w, 'hexdump', '-C');\n    my $promise = $prog.start;\n    await $prog.write(Buf.new(12, 42));\n    $prog.close-stdin;\n    await $promise;\n\nAn example of piping several commands like C<echo \"Hello, world\" | cat -n>:\n\n    my $proc-echo = Proc::Async.new: 'echo', 'Hello, world';\n    my $proc-cat = Proc::Async.new: 'cat', '-n';\n    $proc-cat.bind-stdin: $proc-echo.stdout;\n    await $proc-echo.start, $proc-cat.start;\n\n=head1 Methods\n\n=head2 method new\n\n    multi method new(*@ ($path, *@args), :$w, :$enc, :$translate-nl, :$arg0,\n                     :$win-verbatim-args = False, :$pty,\n                     :$started = False --> Proc::Async:D)\n    multi method new(   :$path, :@args,  :$w, :$enc, :$translate-nl, :$arg0,\n                     :$win-verbatim-args = False, :$pty,\n                     :$started = False --> Proc::Async:D)\n\nCreates a new C<Proc::Async> object with external program name or path\nC<$path> and the command line arguments C<@args>.\n\nIf C<:w> is passed to C<new>, then a pipe to the external program's standard\ninput stream (C<stdin>) is opened, to which you can write with C<write> and\nC<say>.\n\nThe C<:enc> specifies L<the encoding|/type/IO::Handle#method_encoding>\nfor streams (can still be overridden in individual methods) and defaults\nto C<utf8>.\n\nIf C<:translate-nl> is set to C<True> (default value), OS-specific\nnewline terminators (e.g. C<\\r\\n> on Windows) will be automatically\ntranslated to C<\\n>.\n\nIf C<:arg0> is set to a value, that value is passed as arg0 to the process\ninstead of the program name.\n\nThe C<:started> attribute is set by default to C<False>, so that you need to\nstart the command afterwards using\nL<C<.start>|/type/Proc::Async#method_start>. You probably don't want to do this\nif you want to bind any of the handlers, but it's OK if you just need to\nstart an external program immediately.\n\nOn Windows the flag C<$win-verbatim-args> disables all automatic quoting of\nprocess arguments. See\nL<this blog|https://docs.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way>\nfor more information on windows command quoting. The flag is ignored on all\nother platforms. The flag was introduced in Rakudo release 2020.06 and is not\npresent in older releases. By default, it's set to C<False>, in which case\narguments will be quoted according to Microsoft convention.\n\nThe C<pty> attribute allows creating the child process behind a PTY. To do so\npass the PTY row and column count as follows: C<:pty(:rows(24), :cols(80))>\nWhen working with a PTY, the STDERR stream is inactive and it's output is\nintermingled with STDOUT. That's part of the nature of how PTYs work.\n\n=head2 method stdout\n\n    method stdout(Proc::Async:D: :$bin --> Supply:D)\n\nReturns the L<C<Supply>|/type/Supply> for the external program's standard output\nstream. If C<:bin> is passed, the standard output is passed along in binary as\nL<C<Blob>|/type/Blob>, otherwise it is interpreted as UTF-8, decoded, and passed\nalong as L<C<Str>|/type/Str>.\n\n    my $proc = Proc::Async.new(:r, 'echo', 'Raku');\n    $proc.stdout.tap( -> $str {\n        say \"Got output '$str' from the external program\";\n    });\n    my $promise = $proc.start;\n    await $promise;\n\nYou must call C<stdout> before you call\nL<C<.start>|/type/Proc::Async#method_start>. Otherwise an\nexception of class\nL<C<X::Proc::Async::TapBeforeSpawn>|/type/X::Proc::Async::TapBeforeSpawn> is\nthrown.\n\nIf C<stdout> is not called, the external program's standard output is not\ncaptured at all.\n\nNote that you cannot call C<stdout> both with and without C<:bin> on the same\nobject; it will throw an exception of type L<C<X::Proc::Async::CharsOrBytes>|/type/X::Proc::Async::CharsOrBytes> if\nyou try.\n\nUse L«C<.Supply>|/type/Proc::Async#method_Supply» for merged STDOUT and STDERR.\n\n=head2 method stderr\n\n    method stderr(Proc::Async:D: :$bin --> Supply:D)\n\nReturns the L<C<Supply>|/type/Supply> for the external program's standard error\nstream. If C<:bin> is passed, the standard error is passed along in binary as\nL<C<Blob>|/type/Blob>, otherwise it is interpreted as UTF-8, decoded, and passed\nalong as L<C<Str>|/type/Str>.\n\n    my $proc = Proc::Async.new(:r, 'echo', 'Raku');\n    $proc.stderr.tap( -> $str {\n        say \"Got error '$str' from the external program\";\n    });\n    my $promise = $proc.start;\n    await $promise;\n\nYou must call C<stderr> before you call\nL<C<.start>|/type/Proc::Async#method_start>. Otherwise an exception of class\nL<C<X::Proc::Async::TapBeforeSpawn>|/type/X::Proc::Async::TapBeforeSpawn>\nis thrown.\n\nIf C<stderr> is not called, the external program's standard error stream is not\ncaptured at all.\n\nNote that you cannot call C<stderr> both with and without C<:bin> on the same\nobject; it will throw an exception of type L<C<X::Proc::Async::CharsOrBytes>|/type/X::Proc::Async::CharsOrBytes>\nif you try.\n\nUse L«C<.Supply>|/type/Proc::Async#method_Supply» for merged STDOUT and STDERR.\n\n=head2 method bind-stdin\n\n    multi method bind-stdin(IO::Handle:D $handle)\n    multi method bind-stdin(Proc::Async::Pipe:D $pipe)\n\nSets a handle (which must be opened) or a C<Pipe> as a source of\nC<STDIN>. The C<STDIN> of the target process must be writable or\nL<C<X::Proc::Async::BindOrUse>|/type/X::Proc::Async::BindOrUse> will be thrown.\n\n    my $p = Proc::Async.new(\"cat\", :in);\n    my $h = \"/etc/profile\".IO.open;\n    $p.bind-stdin($h);\n    $p.start;\n\nThis is equivalent to\n\n=for code :lang<shell>\ncat < /etc/profile\n\nand will print the content of C</etc/profile> to standard output.\n\n=head2 method bind-stdout\n\n    method bind-stdout(IO::Handle:D $handle)\n\nRedirects STDOUT of the target process to a handle (which must be\nopened). If STDOUT is closed\nL<C<X::Proc::Async::BindOrUse>|/type/X::Proc::Async::BindOrUse> will be\nthrown.\n\n    my $p = Proc::Async.new(\"ls\", :out);\n    my $h = \"ls.out\".IO.open(:w);\n    $p.bind-stdout($h);\n    $p.start;\n\nThis program will pipe the output of the C<ls> shell command to a file\ncalled C<ls.out>, which we are opened for reading.\n\n=head2 method bind-stderr\n\n    method bind-stderr(IO::Handle:D $handle)\n\nRedirects C<STDERR> of the target process to a handle (which must be opened).\nIf C<STDERR> is closed L<C<X::Proc::Async::BindOrUse>|/type/X::Proc::Async::BindOrUse> will be thrown.\n\n    my $p = Proc::Async.new(\"ls\", \"--foo\", :err);\n    my $h = \"ls.err\".IO.open(:w);\n    $p.bind-stderr($h);\n    $p.start;\n\n=head2 method w\n\n    method w(Proc::Async:D:)\n\nReturns a true value if C<:w> was passed to the constructor, that is, if the\nexternal program is started with its input stream made available to output to\nthe program through the C<.print>, C<.say> and C<.write> methods.\n\n=head2 method start\n\n    method start(Proc::Async:D: :$scheduler = $*SCHEDULER, :$ENV, :$cwd = $*CWD --> Promise)\n\nInitiates spawning of the external program. Returns a L<C<Promise>|/type/Promise>\nthat will be kept with a L<C<Proc>|/type/Proc> object once the external program\nexits or broken if the program cannot be started. Optionally, you can use a\nscheduler instead of the default C<$*SCHEDULER>, or change the environment the\nprocess is going to run in via the named argument C<:$ENV> or the directory via\nthe named argument C<:$cwd>.\n\nIf C<start> is called on a Proc::Async object on which it has already been\ncalled before, an exception of type L<C<X::Proc::Async::AlreadyStarted>|/type/X::Proc::Async::AlreadyStarted> is\nthrown.\n\nNote: If you wish to C<await> the Promise and discard its result, using\n\n=begin code :preamble<my $p>\ntry await $p.start;\n=end code\n\nB<will throw> if the program exited with non-zero status, as the L<C<Proc>|/type/Proc>\nreturned as the result of the Promise throws when sunk and in this case it\nwill get sunk outside the C<try>. To avoid that, sink it yourself I<inside> the\nC<try>:\n\n=begin code :preamble<my $p>\ntry sink await $p.start;\n=end code\n\n=head2 method started\n\n    method started(Proc::Async:D: --> Bool:D)\n\nReturns C<False> before C<.start> has been called, and C<True> afterwards.\n\n=head2 method ready\n\n    method ready(Proc::Async:D: --> Promise:D)\n\nReturns a L<C<Promise>|/type/Promise> that will be kept once the process\nhas successfully started. L<C<Promise>|/type/Promise> will be broken if the program\nfails to start.\n\nB<Implementation-specific note:> Starting from Rakudo 2018.04, the\nreturned promise will hold the process id (PID).\n\n=head2 method pid\n\n    method pid(Proc::Async:D: --> Promise:D)\n\nEquivalent to L<ready|/routine/ready>.\n\nReturns a L<C<Promise>|/type/Promise> that will be kept once the process\nhas successfully started. L<C<Promise>|/type/Promise> will be broken if the program\nfails to start. Returned promise will hold the process id (PID).\n\nB<Implementation-specific note:> Available starting from Rakudo 2018.04.\n\n=head2 method path\n\n    method path(Proc::Async:D:)\n\nB<Deprecated as of v6.d>. Use L<command|/routine/command> instead.\n\nReturns the name and/or path of the external program that was passed to the\nC<new> method as first argument.\n\n=head2 method args\n\n    method args(Proc::Async:D: --> Positional:D)\n\nB<Deprecated as of v6.d>. Use L<command|/routine/command> instead.\n\nReturns the command line arguments for the external programs, as passed to the\nC<new> method.\n\n=head2 method command\n\n    method command(Proc::Async:D: --> List:D)\n\nI<Available as of v6.d.>\n\nReturns the command and arguments used for this C<Proc::Async> object:\n\n    my $p := Proc::Async.new: 'cat', 'some', 'files';\n    $p.command.say; # OUTPUT: «(cat some files)␤»\n\n=head2 method write\n\n    method write(Proc::Async:D: Blob:D $b, :$scheduler = $*SCHEDULER --> Promise:D)\n\nWrite the binary data in C<$b> to the standard input stream of the external\nprogram.\n\nReturns a L<C<Promise>|/type/Promise> that will be kept once the data has fully\nlanded in the input buffer of the external program.\n\nThe C<Proc::Async> object must be created for writing (with\nC<Proc::Async.new(:w, $path, @args)>). Otherwise an\nL<C<X::Proc::Async::OpenForWriting>|/type/X::Proc::Async::OpenForWriting> exception will the thrown.\n\nC<start> must have been called before calling method write, otherwise an\nL<C<X::Proc::Async::MustBeStarted>|/type/X::Proc::Async::MustBeStarted> exception is thrown.\n\n=head2 method print\n\n    method print(Proc::Async:D: Str() $str, :$scheduler = $*SCHEDULER)\n\nWrite the text data in C<$str> to the standard input stream of the external\nprogram, encoding it as UTF-8.\n\nReturns a L<C<Promise>|/type/Promise> that will be kept once the data has fully\nlanded in the input buffer of the external program.\n\nThe C<Proc::Async> object must be created for writing (with\nC<Proc::Async.new(:w, $path, @args)>). Otherwise an\nL<C<X::Proc::Async::OpenForWriting>|/type/X::Proc::Async::OpenForWriting> exception\nwill the thrown.\n\nC<start> must have been called before calling method print, otherwise an\nL<C<X::Proc::Async::MustBeStarted>|/type/X::Proc::Async::MustBeStarted> exception is thrown.\n\n=head2 method put\n\n    method put(Proc::Async:D: \\x, |c)\n\nDoes a C<.join> on the output, adds a newline, and calls C<.print> on it.\nWill throw if it's not started, or not open for writing.\n\n=head2 method say\n\n    method say(Proc::Async:D: $output, :$scheduler = $*SCHEDULER)\n\nCalls method C<gist> on the C<$output>, adds a newline, encodes it as UTF-8,\nand sends it to the standard input stream of the external\nprogram, encoding it as UTF-8.\n\nReturns a L<C<Promise>|/type/Promise> that will be kept once the data has fully\nlanded in the input buffer of the external program.\n\nThe C<Proc::Async> object must be created for writing (with\nC<Proc::Async.new(:w, $path, @args)>). Otherwise an\nL<C<X::Proc::Async::OpenForWriting>|/type/X::Proc::Async::OpenForWriting> exception will the thrown.\n\nC<start> must have been called before calling method say, otherwise an\nL<C<X::Proc::Async::MustBeStarted>|/type/X::Proc::Async::MustBeStarted> exception is thrown.\n\n=head2 method pty\n\n    method pty(--> Bool)\n\nReturns whether the child process was created with a PTY.\n\n=head2 method resize-pty\n\n    method resize-pty(Int :$cols, Int :$rows)\n\nChanges the size of the PTY the child is attached to.\n\n=head2 method Supply\n\n    multi method Supply(Proc::Async:D: :$bin!)\n    multi method Supply(Proc::Async:D: :$enc, :$translate-nl)\n\nReturns a L<C<Supply>|/type/Supply> of merged L<stdout|/routine/stdout> and L<stderr|/routine/stderr> streams. If C<:$bin>\nnamed argument is provided, the L<C<Supply>|/type/Supply> will be binary, producing L<C<Buf>|/type/Buf>\nobjects, otherwise, it will be in character mode, producing L<C<Str>|/type/Str> objects and\nC<:$enc> named argument can specify L<encoding|/routine/encoding> to use.\nThe C<:$translate-nl> option specifies whether new line endings should be\ntranslated for to match those used by the current operating system (e.g.\nC<\\r\\n> on Windows).\n\n=for code\nreact {\n    with Proc::Async.new: «\"$*EXECUTABLE\" -e 'say 42; note 100'» {\n        whenever .Supply { .print }  # OUTPUT: «42␤100␤»\n        whenever .start {}\n    }\n}\n\nIt is an error to create both binary and non-binary\nL«C<.Supply>|/type/Proc::Async#method_Supply». It is also an error\nto use both L«C<.Supply>|/type/Proc::Async#method_Supply» and either\nL<stderr|/routine/stderr> or L<stdout|/routine/stdout> supplies.\n\n=head2 method close-stdin\n\n    method close-stdin(Proc::Async:D: --> True)\n\nCloses the standard input stream of the external program. Programs that read\nfrom STDIN often only terminate when their input stream is closed. So if\nwaiting for the promise from\nL<C<.start>|/type/Proc::Async#method_start> hangs (for a program opened for\nwriting), it might be a forgotten C<close-stdin>.\n\nThe C<Proc::Async> object must be created for writing (with\nC<Proc::Async.new(:w, $path, @args)>). Otherwise an\nL<C<X::Proc::Async::OpenForWriting>|/type/X::Proc::Async::OpenForWriting> exception\nwill the thrown.\n\nC<start> must have been called before calling method close-stdin,\notherwise an L<C<X::Proc::Async::MustBeStarted>|/type/X::Proc::Async::MustBeStarted> exception is thrown.\n\n=head2 method kill\n\n=for code :method\nmulti method kill(Proc::Async:D: Signal:D \\signal = SIGHUP)\n=for code :method\nmulti method kill(Proc::Async:D: Int:D \\signal)\n=for code :method\nmulti method kill(Proc::Async:D: Str:D \\signal)\n\nSends a signal to the running program. The signal can be a signal name\n(\"KILL\" or \"SIGKILL\"), an integer (9) or an element of the L<C<Signal>|/type/Signal> enum\n(Signal::SIGKILL); by default and with no argument, the C<SIGHUP> signal will\nbe used.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Proc.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Proc\n\n=SUBTITLE Running process (filehandle-based interface)\n\n    class Proc {}\n\nC<Proc> is a representation of an invocation of an external\nprocess. It provides access to the input, output and error stream as well as\nthe exit code. It is typically created through the X<C<run>|Subroutines,run> subroutine:\n\n=for code\nmy $proc = run 'echo', 'Hallo world', :out;\nmy $captured-output = $proc.out.slurp: :close;\nsay \"Output was $captured-output.raku()\";# OUTPUT: «Output was \"Hallo world\\n\"␤»\n\nPiping several commands is easy too. To achieve the equivalent of the\npipe C<echo \"Hello, world\" | cat -n> in Raku, and capture the output\nfrom the second command, you can do\n\n=for code\nmy $p1 = run 'echo', 'Hello, world', :out;\nmy $p2 = run 'cat', '-n', :in($p1.out), :out;\nsay $p2.out.get;\n\nYou can also feed the C<:in> (standard input) pipe directly from your program,\nby setting it to C<True>, which will make the pipe available via C<.in> method\non the C<Proc>:\n\n=for code\nmy $p = run \"cat\", \"-n\", :in, :out;\n$p.in.say: \"Hello,\\nworld!\";\n$p.in.close;\nsay $p.out.slurp: :close;\n# OUTPUT: «1  Hello,␤\n#          2  world!␤»\n\nIn order to capture the standard error, C<:err> can be supplied:\n\n=for code\nmy $p = run \"ls\", \"-l\", \".\", \"qqrq\", :out, :err;\nmy $captured-output = $p.out.slurp: :close;\nmy $captured-error  = $p.err.slurp: :close;\nmy $exit-code       = $p.exitcode;\n\nIn sink context, a C<Proc> will call its C<sink> method, throwing an exception\nif the process has exited with an exit code different from zero:\n\n=for code\nshell 'exit 1'\n# OUTPUT: «(exit code 1) The spawned command 'exit 1' exited unsuccessfully (exit code: 1)␤»\n\nB<Note:> Versions of L<Rakudo|/language/glossary#Rakudo> older than 2017.04 do\nnot have C<.slurp> available on L<C<IO::Pipe>|/type/IO::Pipe> objects; use\nL«C<.slurp-rest>|/routine/slurp-rest» instead.\n\nUse L<C<Proc::Async>|/type/Proc::Async> for non-blocking operations.\n\n\n=head1 Potential Deadlocks\n\nIf you run an external program with C<:out> and C<:err> (so\ncapturing standard output and standard error separately), a deadlock\ncan occur, for example in the following scenario:\n\n=item Your Raku script reads from the program's standard output until\nthe End of File (EOF) marker).\n=item The external program writes to its standard error stream.\n=item The external program runs into the standard error's buffer limit.\n=item Your Raku script blocks, waiting for input on the output stream, while\nthe external program blocks until its standard error buffer is being drained.\n\nYou can avoid this by using C<:merge> to join the external program's\nstandard output and error streams, so that you only need to read from\none pipe. This presupposes that you do not need separate access\nto the two streams. If you do, the only safe approach is to use\nL<C<Proc::Async>|/type/Proc::Async>.\n\nA similar deadlock can occur when you call an external program with\nboth the C<:in> option (to open a pipe to its standard input) and\none of the C<:out>, C<:err> or C<:merge> options. In this scenario,\nit can happen that your Raku script blocks reading from the external\nprogram's output while it waits for input, and vice versa.\n\nIn this scenario, switching to L<C<Proc::Async>|/type/Proc::Async> is the most\nrobust solution.\n\n=head1 Methods\n\n=head2 routine new\n\n=begin code :skip-test<compile time error>\nmethod new(Proc:U:\n        :$in = '-',\n        :$out = '-',\n        :$err = '-',\n        Bool :$bin = False,\n        Bool :$chomp = True,\n        Bool :$merge = False,\n        Str:D :$enc = 'UTF-8',\n        Str:D :$nl = \"\\n\",\n    --> Proc:D)\n\nsub shell(\n        $cmd,\n        :$in = '-',\n        :$out = '-',\n        :$err = '-',\n        Bool :$bin = False,\n        Bool :$chomp = True,\n        Bool :$merge = False,\n        Str:D :$enc = 'UTF-8',\n        Str:D :$nl = \"\\n\",\n        :$cwd = $*CWD,\n        Hash() :$env = %*ENV\n    --> Proc:D)\n=end code\n\nC<new> creates a new C<Proc> object, whereas C<run> or C<shell> create one and\nspawn it with the command and arguments provided in C<@args> or C<$cmd>,\nrespectively.\n\nC<$in>, C<$out> and C<$err> are the three standard streams of the to-be-launched\nprogram, and default to C<\"-\"> meaning they inherit the stream from the parent\nprocess. Setting one (or more) of them to C<True> makes the stream available as\nan L<C<IO::Pipe>|/type/IO::Pipe> object of the same name, like for example\nC<$proc.out>. You can set them to C<False> to discard them. Or you can pass an\nexisting L<C<IO::Handle>|/type/IO::Handle> object (for example L<C<IO::Pipe>|/type/IO::Pipe>) in, in\nwhich case this handle is used for the stream.\n\nPlease bear in mind that the process streams reside in process\nvariables, not in the dynamic variables that make them available to our\nprograms. Thus, modifying\nL<the dynamic filehandle variables (such as C<$*OUT>)|/language/variables#Special_filehandles:_STDIN,_STDOUT_and_STDERR>\ninside the host process will have no effect in the spawned process,\nunlike C<$*CWD> and C<$*ENV>, whose changes will be actually reflected\nin it.\n\n=begin code\nmy $p-name = \"/tmp/program.raku\";\nmy $program = Q:to/END/;\n    #!/usr/bin/env raku\n\n    $*OUT.say( qq/\\t$*PROGRAM: This goes to standard output/ );\nEND\n\nspurt $p-name, $program;\n\n$*OUT.put: \"1. standard output before doing anything weird\";\n\n{\n    temp $*OUT = open '/tmp/out.txt', :w;\n    $*OUT.put: \"2. temp redefine standard output before this message\";\n    shell( \"raku $p-name\" ).so;\n}\n\n$*OUT.put: \"3. everything should be back to normal\";\n# OUTPUT\n# 1. standard output before doing anything weird\n#     /tmp/program.raku: This goes to standard output\n# 3. everything should be back to normal\n\n# /tmp/out.txt will contain:\n# 2. temp redefine standard output before this message\n=end code\n\nThis program shows that the program spawned with C<shell> is not using\nthe temporary C<$*OUT> value defined in the host process (redirected to\nC</tmp/out.txt>), but the initial C<STDOUT> defined in the process.\n\nC<$bin> controls whether the streams are handled as binary (i.e.\nL<C<Blob>|/type/Blob> object) or text (i.e. L<C<Str>|/type/Str> objects). If\nC<$bin> is False, C<$enc> holds the character encoding to encode strings\nsent to the input stream and decode binary data from the output and\nerror streams.\n\nWith C<$chomp> set to C<True>, newlines are stripped from the output and\nerr streams when reading with C<lines> or C<get>. C<$nl> controls what\nyour idea of a newline is.\n\nIf C<$merge> is set to True, the standard output and error stream end up\nmerged in C<$proc.out>.\n\n\n=head2 method sink\n\n    method sink(--> Nil)\n\nWhen sunk, the C<Proc> object will throw L<C<X::Proc::Unsuccessful>|/type/X::Proc::Unsuccessful>\nif the process it ran exited unsuccessfully.\n\n=for code\nshell 'ls /qqq';\n# OUTPUT:\n# (exit code 1) ls: cannot access '/qqq': No such file or directory\n# The spawned command 'ls /qqq' exited unsuccessfully (exit code: 2)\n#   in block <unit> at /tmp/3169qXElwq line 1\n#\n\n=head2 method spawn\n\n    method spawn(*@args ($, *@), :$cwd = $*CWD, Hash() :$env = %*ENV, :$arg0,\n                 :$win-verbatim-args = False --> Bool:D)\n\nRuns the C<Proc> object with the given command, argument list, working directory,\nand environment.\n\nIf C<:arg0> is set to a value, that value is passed as arg0 to the process\ninstead of the program name.\n\nOn Windows the flag C<$win-verbatim-args> disables all automatic quoting of\nprocess arguments. See L<this blog|https://docs.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way>\nfor more information on windows command quoting. The flag is ignored on all\nother platforms. The flag was introduced in Rakudo release 2020.06 and is not\npresent in older releases.\n\n=head2 method shell\n\n    method shell($cmd, :$cwd = $*CWD, :$env --> Bool:D)\n\nRuns the C<Proc> object with the given command and environment which are\npassed through to the shell for parsing and execution. See\nL<C<shell>|/type/independent-routines#sub_shell> for an explanation of which shells\nare used by default in the most common operating systems.\n\n=head2 method command\n\n    method command(Proc:D: --> List:D)\n\nThe command method is an accessor to a list containing the arguments\nthat were passed when the Proc object was executed via C<spawn> or\nC<shell> or C<run>.\n\n=head2 method Bool\n\n    multi method Bool(Proc:D:)\n\nAwaits for the process to finish and returns C<True> if both exit code and signal\nof the process were 0, indicating a successful process termination. Returns C<False> otherwise.\n\n=head2 method pid\n\n    method pid()\n\nReturns the C<PID> value of the process if available, or L<C<Nil>|/type/Nil>.\n\n=head2 method exitcode\n\n    method exitcode(Proc:D: --> Int:D)\n\nReturns the exit code of the external process, or -1 if it has not exited yet.\n\n=head2 method signal\n\n    method signal(Proc:D:)\n\nReturns the signal number with which the external process was killed, or\nC<0> or an undefined value otherwise.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Promise.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Promise\n\n=SUBTITLE Status/result of an asynchronous computation\n\n    class Promise {}\n\nA C<Promise> is used to handle the result of a computation that might not have\nfinished. It allows the user to execute code once the computation is done\n(with the C<then> method), execution after a time delay (with C<in>),\ncombining promises, and waiting for results.\n\n    my $p = Promise.start({ sleep 2; 42});\n    $p.then({ say .result });   # will print 42 once the block finished\n    say $p.status;              # OUTPUT: «Planned␤»\n    $p.result;                  # waits for the computation to finish\n    say $p.status;              # OUTPUT: «Kept␤»\n\nThere are two typical scenarios for using promises. The first is to use a\nfactory method (C<start>, C<in>, C<at>, C<anyof>, C<allof>, C<kept>, C<broken>)\non the type object; those will make sure that the promise is automatically kept\nor broken for you, and you can't call C<break> or C<keep> on these promises\nyourself.\n\nThe second is to create your promises yourself with C<Promise.new>. If you\nwant to ensure that only your code can keep or break the promise, you can use\nthe C<vow> method to get a unique handle, and call C<keep> or C<break> on it:\n\n=begin code\nsub async-get-with-promise($user-agent, $url) {\n    my $p = Promise.new;\n    my $v = $p.vow;\n\n    # do an asynchronous call on a fictive user agent,\n    # and return the promise:\n    $user-agent.async-get($url,\n            on-error => -> $error {\n                $v.break($error);\n            },\n            on-success => -> $response {\n                $v.keep($response);\n            }\n    );\n    return $p;\n}\n=end code\n\nFurther examples can be found in the L<concurrency page|/language/concurrency#Promises>.\n\n=head1 Methods\n\n=head2 method start\n\n    method start(Promise:U: &code, :$scheduler = $*SCHEDULER --> Promise:D)\n\nCreates a new Promise that runs the given code object. The promise will be\nkept when the code terminates normally, or broken if it throws an exception.\nThe return value or exception can be inspected with the C<result> method.\n\nThe scheduler that handles this promise can be passed as a named argument.\n\nThere is also a statement prefix C<start> that provides syntactic sugar for\nthis method:\n\n    # these two are equivalent:\n    my $p1 = Promise.start({ ;#`( do something here ) });\n    my $p2 = start { ;#`( do something here ) };\n\nAs of the 6.d version of the language, C<start> statement prefix used in\nL<sink|/routine/sink> context will automatically attach an exceptions handler. If an\nexception occurs in the given code, it will be printed and the program\nwill then exit, like if it were thrown without any C<start> statement\nprefixes involved.\n\n    =begin code :solo\n    use v6.c;\n    start { die }; sleep ⅓; say \"hello\"; # OUTPUT: «hello␤»\n    =end code\n\n    =begin code :solo\n    use v6.d;\n    start { die }; sleep ⅓; say \"hello\";\n    # OUTPUT:\n    # Unhandled exception in code scheduled on thread 4\n    # Died\n    #     in block  at -e line 1\n    =end code\n\nIf you wish to avoid this behavior, use C<start> in non-sink context or\ncatch the exception yourself:\n\n    =begin code\n    # Don't sink it:\n    my $ = start { die }; sleep ⅓; say \"hello\"; # OUTPUT: «hello␤»\n\n    # Catch yourself:\n    start { die; CATCH { default { say \"caught\" } } };\n    sleep ⅓;\n    say \"hello\";\n    # OUTPUT: «caught␤hello␤»\n    =end code\n\nThis behavior exists only syntactically, by using an alternate C<.sink> method\nfor C<Promise> objects created by C<start> blocks in sink context, thus simply\nsinking a C<Promise> object that was created by other means won't trigger this\nbehavior.\n\n=head2 method in\n\n    method in(Promise:U: $seconds, :$scheduler = $*SCHEDULER --> Promise:D)\n\nCreates a new Promise that will be kept in C<$seconds> seconds, or later.\n\n    my $proc = Proc::Async.new('raku', '-e', 'sleep 10; warn \"end\"');\n\n    my $result = await Promise.anyof(\n        my $promise = $proc.start,  # may or may not work in time\n        Promise.in(5).then: {       # fires after 5 seconds no matter what\n            unless $promise {       # don't do anything if we were successful\n                note 'timeout';\n                $proc.kill;\n            }\n        }\n    ).then: { $promise.result }\n    # OUTPUT: «timeout␤»\n\nC<$seconds> can be fractional or negative. Negative values are treated as\nC<0> (i.e. L<keeping|/routine/keep> the returned C<Promise> right away).\n\nPlease note that situations like these are often more clearly handled with\na L<react and whenever block|/language/concurrency#react>.\n\n=head2 method at\n\n    method at(Promise:U: $at, :$scheduler = $*SCHEDULER --> Promise:D)\n\nCreates a new C<Promise> that will be kept C<$at> the given time—which is\ngiven as an L<C<Instant>|/type/Instant> or equivalent L<C<Numeric>|/type/Numeric>—or as soon as possible after it.\n\n    my $p = Promise.at(now + 2).then({ say \"2 seconds later\" });\n    # do other stuff here\n\n    await $p;   # wait here until the 2 seconds are over\n\nIf the given time is in the past, it will be treated as L<now|/routine/now> (i.e.\nL<keeping|/routine/keep> the returned C<Promise> right away).\n\nPlease note that situations like these are often more clearly handled with\na L<react and whenever block|/language/concurrency#react>.\n\n=head2 method kept\n\n    multi method kept(Promise:U: \\result = True --> Promise:D)\n\nReturns a new promise that is already kept, either with the given value,\nor with the default value C<True>.\n\n=head2 method broken\n\n    multi method broken(Promise:U: --> Promise:D)\n    multi method broken(Promise:U: \\exception --> Promise:D)\n\nReturns a new promise that is already broken, either with the given value,\nor with the default value C«X::AdHoc.new(payload => \"Died\")»\n\n=head2 method allof\n\n    method allof(Promise:U: *@promises --> Promise:D)\n\nReturns a new promise that will be kept when all the promises passed as\narguments are kept or broken. The result of the individual Promises is\nnot reflected in the result of the returned promise: it simply\nindicates that all the promises have been completed in some way.\nIf the results of the individual promises are important then they should\nbe inspected after the C<allof> promise is kept.\n\nIn the following requesting the C<result> of a broken promise will cause the\noriginal Exception to be thrown. (You may need to run it several times to\nsee the exception.)\n\n    my @promises;\n    for 1..5 -> $t {\n        push @promises, start {\n            sleep $t;\n        };\n    }\n    my $all-done = Promise.allof(@promises);\n    await $all-done;\n    @promises>>.result;\n    say \"Promises kept so we get to live another day!\";\n\n=head2 method anyof\n\n    method anyof(Promise:U: *@promises --> Promise:D)\n\nReturns a new promise that will be kept as soon as any of the promises\npassed as arguments is kept or broken. The result of the completed\nPromise is not reflected in the result of the returned promise which\nwill always be Kept.\n\nYou can use this to wait at most a number of seconds for a promise:\n\n    my $timeout = 5;\n    await Promise.anyof(\n        Promise.in($timeout),\n        start {\n            # do a potentially long-running calculation here\n        },\n    );\n\n=head2 method then\n\n    method then(Promise:D: &code)\n\nSchedules a piece of code to be run after the invocant has been kept or\nbroken, and returns a new promise for this computation. In other words,\ncreates a chained promise. The C<Promise> is passed as an argument\nto the C<&code>.\n\n    # Use code only\n    my $timer = Promise.in(2);\n    my $after = $timer.then({ say '2 seconds are over!'; 'result' });\n    say $after.result;\n    # OUTPUT: «2 seconds are over␤result␤»\n\n    # Interact with original Promise\n    my $after = Promise.in(2).then(-> $p { say $p.status; say '2 seconds are over!'; 'result' });\n    say $after.result;\n    # OUTPUT: «Kept␤2 seconds are over␤result␤»\n\n=head2 method keep\n\n    multi method keep(Promise:D: \\result = True)\n\nKeeps a promise, optionally setting the result. If no result is passed, the\nresult will be C<True>.\n\nThrows an exception of type L<C<X::Promise::Vowed>|/type/X::Promise::Vowed> if a vow has already been\ntaken. See method C<vow> for more information.\n\n    my $p = Promise.new;\n\n    if Bool.pick {\n        $p.keep;\n    }\n    else {\n         $p.break;\n    }\n\n=head2 method break\n\n    multi method break(Promise:D: \\cause = False)\n\nBreaks a promise, optionally setting the cause. If no cause is passed, the\ncause will be C<False>.\n\nThrows an exception of type L<C<X::Promise::Vowed>|/type/X::Promise::Vowed> if a vow has already been\ntaken. See method C<vow> for more information.\n\n    my $p = Promise.new;\n\n    $p.break('sorry');\n    say $p.status;          # OUTPUT: «Broken␤»\n    say $p.cause;           # OUTPUT: «sorry␤»\n\n=head2 method result\n\n    method result(Promise:D:)\n\nWaits for the promise to be kept or broken. If it is kept, returns the result;\notherwise throws the result as an exception.\n\n=head2 method cause\n\n    method cause(Promise:D:)\n\nIf the promise was broken, returns the result (or exception). Otherwise, throws\nan exception of type L<C<X::Promise::CauseOnlyValidOnBroken>|/type/X::Promise::CauseOnlyValidOnBroken>.\n\n=head2 method Bool\n\n    multi method Bool(Promise:D:)\n\nReturns C<True> for a kept or broken promise, and C<False> for one in state\nC<Planned>.\n\n=head2 method status\n\n    method status(Promise:D --> PromiseStatus)\n\nReturns the current state of the promise: C<Kept>, C<Broken> or C<Planned>:\nSee L<C<PromiseStatus>|/type/PromiseStatus>.\n\n=for code :preamble<my $promise>\nsay \"promise got Kept\" if $promise.status ~~ Kept;\n\n=head2 method scheduler\n\n    method scheduler(Promise:D:)\n\nReturns the scheduler that manages the promise.\n\n=head2 method vow\n\n=for code\nmy class Vow {\n    has Promise $.promise;\n    method keep() { ... }\n    method break() { ... }\n}\nmethod vow(Promise:D: --> Vow:D)\n\nReturns an object that holds the sole authority over keeping or breaking a\npromise. Calling C<keep> or C<break> on a promise that has vow taken throws an\nexception of type L<C<X::Promise::Vowed>|/type/X::Promise::Vowed>.\n\n    my $p   = Promise.new;\n    my $vow = $p.vow;\n    $vow.keep($p);\n    say $p.status;          # OUTPUT: «Kept␤»\n\n=head2 method Supply\n\n    method Supply(Promise:D:)\n\nReturns a L<C<Supply>|/type/Supply> that will emit the C<result> of the C<Promise> being Kept\nor C<quit> with the C<cause> if the C<Promise> is Broken.\n\n\n=head2 sub await\n\n    multi await(Promise:D --> Promise)\n    multi await(*@ --> Array)\n\nWaits until one or more promises are I<all> fulfilled, and then returns their\nvalues. Also works on L<C<Channel>|/type/Channel>s. Any broken promises will\nrethrow their exceptions. If a list is passed it will return a\nlist containing the results of awaiting each item in turn.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/PromiseStatus.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"enum\") :category(\"basic\")\n\n=TITLE enum PromiseStatus\n\n=SUBTITLE Indicate status of a promise\n\n    enum PromiseStatus <Planned Kept Broken>;\n\nX<|Reference,Planned>\nX<|Reference,Kept>\nX<|Reference,Broken>\nAn enum for indicating the result of a L<C<Promise>|/type/Promise>.\nConsists of C<Planned>, C<Kept> and C<Broken>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Proxy.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Proxy\n\n=SUBTITLE Item container with custom storage and retrieval\n\n    class Proxy {}\n\nA Proxy is an object that allows you to set a hook that executes whenever a\nvalue is retrieved from a container (C<FETCH>) or when it is set (C<STORE>).\nPlease note that C<Proxy> can introduce mutability at places where it would\nbreak behavior, e.g. in L<C<Hash>|/type/Hash> keys.\n\nTo create a container that returns twice what was stored in it, you do something\nlike this:\n\n=begin code :method\nsub double() is rw {\n    my $storage = 0;\n    Proxy.new(\n        FETCH => method ()     { $storage * 2    },\n        STORE => method ($new) { $storage = $new },\n    )\n}\nmy $doubled := double();\n$doubled = 4;\nsay $doubled;       # OUTPUT: «8␤»\n=end code\n\n=head1 Methods\n\n=head2 method new\n\n    method new(:&FETCH!, :&STORE! --> Proxy:D)\n\nCreates a new C<Proxy> object. C<&FETCH> is called with one argument (the\nproxy object) when the value is accessed, and must return the value that the\nfetch produces. C<&STORE> is called with two arguments (the proxy object, and\nthe new value) when a new value is stored in the container.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/PseudoStash.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class PseudoStash\n\n=SUBTITLE Stash type for pseudo-packages\n\n    class PseudoStash is Map { }\n\nC<PseudoStash> is the stash type (hanging off C<.WHO>) that backs\nvarious pseudo-packages. So, when you do C<MY::> or C<CALLER::>, that\ngives back a C<PseudoStash>. In most cases, C<Package::> gives\nback a L<C<Stash>|/type/Stash>. Neither of these are objects the user is expected to\ncreate by themselves, but in case you have one, you can just use it like a\nhash.\n\n=for code\nmy $a = 42;\nmy $b = q/$a/;\nsay MY::{$b};\n# OUTPUT: «42␤»\n\nThis shows how you can use a C<PseudoStash> to look up variables, by name,\nat runtime.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/QuantHash.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"composite\")\n\n=TITLE role QuantHash\n\n=SUBTITLE Object hashes with a limitation on the type of values\n\n    role QuantHash does Associative { }\n\nThe C<QuantHash> role provides the basic functionality shared by the\nL<C<Setty>|/type/Setty>, L<C<Baggy>|/type/Baggy> and L<C<Mixy>|/type/Mixy> roles.  These\nprovide object hashes whose values are limited in some way.\n\nC<QuantHashes> are what L<set operators|/language/setbagmix> use internally.\n\n=head1 Methods\n\n=head2 method hash\n\n    method hash()\n\nCoerces the C<QuantHash> object to a L<C<Hash>|/type/Hash> (by stringifying the objects\nfor the keys) with the values of the hash limited to the same limitation as\nC<QuantHash>, and returns that.\n\n=head2 method Hash\n\n    method Hash()\n\nCoerces the C<QuantHash> object to a L<C<Hash>|/type/Hash> (by stringifying the objects\nfor the keys) without any limitations on the values, and returns that.\n\n=head2 method Map\n\n    method Map()\n\nAvailable as of the 2021.02 release of the Rakudo compiler.\n\nCoerces the C<QuantHash> object to a L<C<Map>|/type/Map> (by stringifying the objects\nfor the keys) without any limitations on the values, and returns that.\n\n=head2 method of\n\n    method of()\n\nReturns the type of value a value of this C<QuantHash> may have.  This is\ntypically L<C<Bool>|/type/Bool> for L<C<Setty>|/type/Setty>, L<C<UInt>|/type/UInt> for\nL<C<Baggy>|/type/Baggy> or L<C<Real>|/type/Real> for L<C<Mixy>|/type/Mixy> roles.\n\n=head2 method keyof\n\n    method keyof()\n\nReturns the type of value a key of this subclass of C<QuantHash> may have. This\nis typically L<C<Mu>|/type/Mu>, which is also the default for punned QuantHashes.\n\n=head2 method Capture\n\n    method Capture()\n\nReturns the object as a L<C<Capture>|/type/Capture> by previously coercing it to a L<C<Hash>|/type/Hash>.\n\n=head2 method list\n\n    multi method list(QuantHash:D:)\n\nReturns a list of L<C<Pair>|/type/Pair> objects of all keys and values in the\nQuantHash.\n\n=head2 method Setty\n\n    method Setty(--> Setty:D)\n\nCoerce the C<QuantHash> object to the equivalent object that uses the L<C<Setty>|/type/Setty>\nrole. Note that for L<C<Mixy>|/type/Mixy> type coercion items with negative values will be skipped.\n\n    my %b is Bag = one => 1, two => 2;\n    say %b.Setty; # OUTPUT: «Set(one two)␤»\n    my %m is Mix = one => 1, minus => -1;\n    say %m.Setty; # OUTPUT: «Set(one)␤»\n\n=head2 method Baggy\n\n    method Baggy(--> Baggy:D)\n\nCoerce the C<QuantHash> object to the equivalent object that uses the L<C<Baggy>|/type/Baggy>\nrole. Note that for L<C<Mixy>|/type/Mixy> type coercion items with negative values will be skipped.\n\n    my %s is Set = <one two>;\n    say %s.Baggy; # OUTPUT: «Bag(one two)␤»\n    my %m is Mix = one => 1, minus => -1;\n    say %m.Baggy; # OUTPUT: «Bag(one)␤»\n\n=head2 method Mixy\n\n    method Mixy(--> Mixy:D)\n\nCoerce the C<QuantHash> object to the equivalent object that uses the L<C<Mixy>|/type/Mixy>\nrole.\n\n    my %s is Set = <one two>;\n    say %s.Mixy; # OUTPUT: «Mix(one two)␤»\n    my %b is Bag = one => 1, two => 2;\n    say %b.Mixy; # OUTPUT: «Mix(one two(2))␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/RaceSeq.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class RaceSeq\n\n=SUBTITLE Performs batches of work in parallel without respecting original\norder.\n\n    class RaceSeq does Iterable does Sequence { }\n\nA C<RaceSeq> is the intermediate object used when\nL<C<race>|/routine/race> is invoked on a L<C<Seq>|/type/Seq>. In general,\nit's not intended for direct consumption by the developer.\n\n=head1 Methods\n\n\n=head2 method iterator\n\n    method iterator(RaceSeq:D: --> Iterator:D)\n\nReturns the underlying iterator.\n\n=head2 method grep\n\n    method grep(RaceSeq:D: $matcher, *%options)\n\nApplies C<grep> to the C<RaceSeq> similarly to how it would do it on a L<C<Seq>|/type/Seq>.\n\n=for code\nmy @raced = (^10000).map(*²).race;\n@raced.grep( * %% 3 ).say;\n# OUTPUT: «(0 9 36 81 144 ...)␤»\n\nWhen you use C<race> on a L<C<Seq>|/type/Seq>, this is the method that is actually called.\n\n=head2 method map\n\n    method map(RaceSeq:D: $matcher, *%options)\n\nUses maps on the C<RaceSeq>, generally created by application of C<.race> to\na preexisting L<C<Seq>|/type/Seq>.\n\n=head2 method invert\n\n    method invert(RaceSeq:D:)\n\nInverts the C<RaceSeq> created from a L<C<Seq>|/type/Seq> by C<.race>.\n\n=head2 method race\n\n    method race(RaceSeq:D:)\n\nReturns the object.\n\n=head2 method hyper\n\n    method hyper(RaceSeq:D:)\n\nCreates a L<C<HyperSeq>|/type/HyperSeq> object out of the current one.\n\n=head2 method serial\n\n    multi method serial(RaceSeq:D:)\n\nConverts the object to a L<C<Seq>|/type/Seq> and returns it.\n\n=head2 method is-lazy\n\n    method is-lazy(--> False )\n\nReturns C<False>.\n\n\n=head2 method sink\n\n    method sink(--> Nil)\n\nSinks the underlying data structure, producing any side effects.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Raku.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Raku\n\n=SUBTITLE Raku related information\n\n    class Raku does Systemic { }\n\nBuilt-in class for providing information related to the implementation of\nthe Raku language. Usually accessed through the L<$*RAKU|/language/variables#index-entry-%24*RAKU>\ndynamic variable.\n\n=head1 Methods\n\n=head2 method compiler\n\nInstance method returning the L<compiler|/routine/compiler> object, of type\nL<C<Compiler>|/type/Compiler>, associated with the Raku object.\n\n=head2 method DISTROnames\n\nInstance / Class method returning the names of the L<C<Distro>|/type/Distro>\nobjects that are supported by this version of Raku.\n\n=head2 method KERNELnames\n\nInstance / Class method returning the names of the L<C<Kernel>|/type/Kernel>\nobjects that are supported by this version of Raku.\n\n=head2 method VMnames\n\nInstance / Class method returning the names of the L<C<VM>|/type/VM> objects that\nare supported by this version of Raku.\n\n=head1 See Also\n\nL<C<Systemic>|/type/Systemic>, L<C<Compiler>|/type/Compiler>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/RakuAST/Doc/Block.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class RakuAST::Doc::Block\n\n=SUBTITLE Contains the information of a RakuDoc block\n\n    class RakuAST::Doc::Block { }\n\nThe C<RakuAST::Doc::Block> class contains the information about a\nC<RakuDoc> block.\n\nSupport for L<C<RakuAST>|/type/RakuAST> functionality is available in language version\nC<6.e+> and was added in Rakudo compiler release 2023.02.  In earlier\nlanguage versions it is only available when specifying:\n\n    use experimental :rakuast;\n\n=head2 Object introspection\n\nC<RakuAST::Doc::Block> objects are typically created when parsing\nRaku Programming Language code that has C<RakuDoc> markers in it.\nSo most developers will only need to know how to introspect the\nobjects created.\n\n=head3 method type\n\n=begin code :preamble<my $block>\nsay \"type = $block.type()\";\n=end code\n\nReturns the type of the block.\n\n=head3 method level\n\n=begin code :preamble<my $block>\nsay \"level = $block.level()\";\n=end code\n\nReturns a string associated with the level.  If the level is B<0>, then\nit will return an empty string.  Otherwise it will return the\nstringification of the integer value.\n\n=head3 method config\n\n=begin code :preamble<my $block>\nsay \"allows: $_\"\n  with $block.config<allow> andthen .literalize;\n=end code\n\nReturns the L<C<Map>|/type/Map> with any configuration.  Note that you can get\nany constant values by calling the C<.literalize> method on them.\nSee also C<resolved-config>.\n\n=head3 method resolved-config\n\n=begin code :preamble<my $block>\nsay \"allows: $_\" with $block.resolved-config<allow>;\n=end code\n\nReturns the L<C<Map>|/type/Map> with any configuration, with the values already\nresolved to \"normal\" Raku objects.  See also C<config>.\n\nIs available by default if the object was created by the Raku\ngrammar.  If the object was created \"manually\", then the\nC<literalize-config> method must be called once first.\n\n=head3 method paragraphs\n\n=begin code :preamble<my $block>\nfor $block.paragraphs {\n    say $_;\n}\n=end code\n\nReturns a L<C<List>|/type/List> of the paragraphs.  Note that each element can\neither be a string, a\nL«C<RakuAST::Doc::Paragraph>|/type/RakuAST::Doc::Paragraph» or another\nC<RakuAST::Doc::Block> object.\n\n=head3 method delimited\n\n=begin code :preamble<my $block>\nwith $block {\n    say \"=begin $_.type\" if .block;\n}\n=end code\n\nReturns a L<C<Bool>|/type/Bool> indicating the block is a delimited block (aka\nwith a C<=begin> and an C<=end>.\n\n=head3 method for\n\n=begin code :preamble<my $block>\nwith $block {\n    say \"=for $_.type\" if .for;\n}\n=end code\n\nReturns a L<C<Bool>|/type/Bool> indicating the block is an extended block (aka\nwith just a C<=for>.\n\n=head3 method abbreviated\n\n=begin code :preamble<my $block>\nwith $block {\n    say \"=$_.type\" if .abbreviated;\n}\n=end code\n\nReturns a L<C<Bool>|/type/Bool> indicating the block is an abbreviated block\n(aka with just C<=> followed by the type, e.g. C<=foo>).\n\n=head3 method directive\n\n=begin code :preamble<my $block>\nwith $block {\n    say \"=$_.type\" if .directive;\n}\n=end code\n\nReturns a L<C<Bool>|/type/Bool> indicating the block is a C<RakuDoc> directive\n(aka with just C<=> followed by the type, e.g. C<=row>).\n\n=head3 method allowed-markup\n\n=begin code :preamble<my $block>\nmy %*OK := $block.allowed-markup;\nsay \"B markup is allowed\" if %*OK<B>;\n=end code\n\nReturns a special purpose L<C<Map>|/type/Map> that can be checked to see whether\na given markup type is allowed in the block, assuming C<RakuDoc>\nsemantics.  Usually C<bound> to a dynamic variable, so it can be\naccessible for rendering all inner L<C<RakuAST::Doc::Markup>|/type/RakuAST::Doc::Markup> objects.\n\nThree types of L<C<Map>|/type/Map>s can be returned:\n=item a real L<C<Map>|/type/Map> from the C<:allow> configuration\n=item a subclass of L<C<Map>|/type/Map> that returns C<True> for all uppercase letters\n=item a subclass of L<C<Map>|/type/Map> that always returns C<False>\n\n=head3 method Str\n\n=begin code :preamble<my $block>\nput $block;  # bar␤\n=end code\n\nReturns the string for the paragraphs of the block, with any\nmarkup also stringified.\n\n=head3 method raku\n\n=begin code :preamble<my $block>\n# method .gist falls back to .raku\nsay $block;  # RakuAST::Doc::Block.new(...\n=end code\n\nReturns the string that is needed for the creation of the block\nusing L<C<RakuAST>|/type/RakuAST> calls.\n\n=head1 Object creation\n\nOne seldom creates C<RakuAST::Doc::Block> objects directly.  This\ndocumentation is intended for those few people who'd like to devise\ntheir own way of programmatically building a C<RakuAST::Doc::Block>\nobject.\n\n=head2 method new\n\n=begin code :method\nmethod new(\n  Str:D  :$type!,        # type of block, e.g. \"head\"\n  Int:D  :$level = 0,    # level of block, e.g. 1 for \"=head1\"\n         :%config,       # any configuration to be applied\n  Str:D  :$margin = \"\",  # left margin (0 or more spaces)\n         :@paragraphs,   # paragraphs of this block\n  Bool:D :$for,          # this is a =for block\n  Bool:D :$abbreviated,  # this is an abbreviated block\n  Bool:D :$directive     # this is a directive (also abbreviated)\n)\n=end code\n\nThe C<new> method can be called to create a new C<RakuAST::Doc::Block>\nobject.  It only takes named arguments, with the C<:type> argument\nbeing mandatory.\n\n=begin code :lang<raku> :preamble<use experimental :rakuast>\n  =begin foo\n  bar\n  =end foo\n\nmy $block = RakuAST::Doc::Block.new(\n  :margin(\"  \"),\n  :type<foo>,\n  :paragraphs(\"bar\\n\",)\n);\n=end code\n\nNote that the paragraphs should B<not> contain the left margin whitespace.\n\n=head3 :type\n\nThe type of block: this is a string with the name.  Required.  Any name\nis allowed, but the C<RakuDoc> standard assigns semantics to some names.\nWhen these are used, it is assumed that the behavior of the block will\nadhere to the C<RakuDoc> standard semantics.\n\n=head3 :level\n\nThe level of the block, specified as an integer value, defaults to\n0.  Some blocks in C<RakuDoc> can have a number associated with the\nname, such as C<=item1> and C<=head2>.\n\n=head3 :config\n\nAny config to be associated with this block, defaults to none.\nSpecified as an L<C<Associative>|/type/Associative>.  Note that when specified, the\nvalues B<must> be C<RakuAST::> objects.  So something like:\n\n    frobnicate => 42\n\nshould be specified as:\n\n=begin code :preamble<use experimental :rakuast>\nfrobnicate => RakuAST::IntLiteral.new(42)\n=end code\n\n=head3 :margin\n\nThe left margin to be applied, specifically when deparsing.  Should\nconsist of 0 or more spaces.  Defaults to the empty string.\n\n=head3 :paragraphs\n\nThe actual content of the block, specified as a L<C<Positional>|/type/Positional>.\nEach element can either be a string, a L<C<RakuAST::Doc::Paragraph>|/type/RakuAST::Doc::Paragraph>\nor another C<RakuAST::Doc::Block> object.  In the case of a string,\nit is assumed that the C<:margin> has already been removed from each\nline in the string.\n\n=head3 :for, :abbreviated, :directive\n\nMutually exclusive indication of the format of the block, mostly\nused in deparsing.  If C<:for> is specified, it is assumed to be a\nC<=for> block.  If C<:abbreviated> is specified, then it is assumed\nto be a C<=$type> block.  If C<:directive> is specified, then is\nassume to be an abbreviated block that can B<only> occur as an\nabbreviated block B<and> has special C<RakuDoc> semantics (e.g.\nC<=row> or C<=column>).\n\nIf neither of these are specified, then a \"delimited block\" (one\nwith a C<=begin> and an C<=end> will be assumed.\n\n=head2 method from-paragraphs\n\nCreate a C<RakuAST::Doc::Block> from a number of strings to be\nconsidered paragraphs.  Strings are assumed to B<not> have removed\nthe left margin yet.\n\n=begin code :lang<raku> :preamble<use experimental :rakuast>\n  =begin foo\n  bar\n  =end foo\n\nmy $block = RakuAST::Doc::Block.from-paragraphs(\n  :margin(\"  \"),\n  :type<foo>,\n  :paragraphs(\"  bar\\n\",)\n);\n=end code\n\nTakes the same arguments as C<new>.  Note that the paragraphs should\nonly contain strings and should B<not> contain the left margin\nwhitespace.  A C<worry>/C<warning> will be issued if the left margin\nof a string is less than the margin indicated with C<:margin>.\n\nAlso note that C<RakuDoc> semantics will be applied, such as:\n=item implicit code blocks\n=item automatic row/column detection for C<=table>\n=item markup detection where (implicitly)  activated\n\n=head1 Object modification\n\n=head2 method set-margin\n\n=begin code :preamble<my $block>\n$block.set-margin(\"    \");\n=end code\n\nSet the margin to the given value, which is expected to be the empty\nstring or 1 more spaces.\n\n=head2 method set-type\n\n=begin code :preamble<my $block>\n$block.set-type(\"foo\");\n=end code\n\nSet the type to the given value, which is expected to be a string.\n\n=head2 method set-level\n\n=begin code :preamble<my $block>\n$block.set-level(1);\n=end code\n\nSet the level to the given value, which is expected to be an integer.\n\n=head2 method set-config\n\n=begin code :preamble<my $block;use experimental :rakuast>\n$block.set-config({\n  numbered => RakuAST::Term::True.new;\n});\n=end code\n\nSet the configuration to the given value, which is expected to be\nan L<C<Associative>|/type/Associative> of which the values are L<C<RakuAST>|/type/RakuAST> objects.\n\n=head2 method add-config\n\n=begin code :preamble<my $block;use experimental :rakuast>\n$block.add-config(\n  'allow',\n  RakuAST::QuotedString.new(\n    processors => <words val>,\n    segments   => (\n      RakuAST::StrLiteral.new(\"B C\"),\n    )\n  )\n);\n=end code\n\nTakes a key and a value to add to the configuration.  Value is\nexpected to be either a string or a L<C<RakuAST>|/type/RakuAST> object.\n\n=head2 method set-paragraphs\n\n=begin code :preamble<my $block>\n$block.set-paragraphs( (\"foo\\n\\n\",\"bar\\n\") );\n=end code\n\nSet the paragraphs to the given L<C<Positional>|/type/Positional>.  Values are expected\nto be either a string, or a L<C<RakuAST::Doc::Paragraph>|/type/RakuAST::Doc::Paragraph> object.\n\n=head2 method add-paragraph\n\n=begin code :preamble<my $block>\n$block.add-paragraph(\"baz\\n\\n\");\n=end code\n\nAdd a paragraph: should be a string, or a L<C<RakuAST::Doc::Paragraph>|/type/RakuAST::Doc::Paragraph>\nobject.\n\n=head2 method literalize-config\n\n=begin code :preamble<my $block>\n$block.literalize-config;\nsay \"allowed are: $block.resolved-config<allowed>\";\n=end code\n\nRecursively literalizes the C<config> of the block (if any) and\nputs the result in C<resolved-config>.\n\nIf the object was created from the Raku grammar, then there is\nno need to call this method ever, as it will have been called\nas part of the C<CHECK> phaser checks already.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/RakuAST/Doc/Declarator.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class RakuAST::Doc::Declarator\n\n=SUBTITLE Contains the declarator docs of a RakuAST object\n\n    class RakuAST::Doc::Declarator { }\n\nThe C<RakuAST::Doc::Declarator> class contains the leading and trailing\ndocumentation of an object doing the\nL«C<RakuAST::Doc::DeclaratorTarget>|/type/RakuAST::Doc::DeclaratorTarget»\nrole.\n\nSupport for L<C<RakuAST>|/type/RakuAST> functionality is available in language version\nC<6.e+> and was added in Rakudo compiler release 2023.02.  In earlier\nlanguage versions it is only available when specifying:\n\n    use experimental :rakuast;\n\n=head2 Object introspection\n\nC<RakuAST::Doc::Declarator> objects are typically created when parsing\nRaku Programming Language code that has objects with leading (C<#|>)\nand trailing (C<#=>) documentation on it.  So most developers will only\nneed to know how to introspect the objects created.\n\n=head3 method WHEREFORE\n\n=begin code :preamble<my $declarator>\nsay \"attached to a $declarator.WHEREFORE.^name() object\";\n=end code\n\nReturns the object for which this object contains the declarator\ndocumentation.\n\n=head3 method leading\n\n=begin code :preamble<my $declarator>\n.say for $declarator.leading;\n=end code\n\nReturns the lines of the leading declarator documentation (one\nfor each line with C<#|> if the object was created from parsing\nRaku source code.\n\n=head3 method trailing\n\n=begin code :preamble<my $declarator>\n.say for $declarator.trailing;\n=end code\n\nReturns the lines of the trailing declarator documentation (one\nfor each line with C<#=> if the object was created from parsing\nRaku source code.\n\n=head3 method raku\n\n=begin code :preamble<my $declarator;use experimental :rakuast>\n# method .gist falls back to .raku\nsay $declarator;  # RakuAST::Doc::Declarator.new(...\n=end code\n\nReturns the string that is needed for the creation of the block\nusing L<C<RakuAST>|/type/RakuAST> calls.\n\n=head1 Object creation\n\nOne seldom creates C<RakuAST::Doc::Declarator> objects directly.  This\ndocumentation is intended for those few people who'd like to devise\ntheir own way of programmatically building a C<RakuAST::Doc::Declarator>\nobject.\n\n=head2 method new\n\n=begin code :method\nmethod new(\n  Str:D :$WHEREFORE,  # the associated RakuAST object\n        :@leading,    # leading lines of documentation\n        :@trailing    # trailing lines of documentation\n)\n=end code\n\nThe C<new> method can be called to create a new C<RakuAST::Doc::Declarator>\nobject.  It only takes named arguments.\n\n=begin code :preamble<my $declarator;use experimental :rakuast>\n# there is no syntax for creating just a ::Declarator object\n\nmy $declarator = RakuAST::Doc::Declarator.new(\n  :WHEREFORE(RakuAST::VarDeclaration::Simple.new(...)),\n  :leading(\"line 1 leading\",\"line 2 leading\"),\n  :trailing(\"line 1 trailing\",\"line 2 trailing\")\n);\n=end code\n\nNote that the leading and trailing documentation may contain any\nleft margin whitespace.\n\n=head3 :WHEREFORE\n\nThe L<C<RakuAST>|/type/RakuAST> object for which this declarator contains the documentation.\n\n=head3 :leading\n\nA L<C<Positional>|/type/Positional> with the lines of leading documentation strings.\n\n=head3 :trailing\n\nA L<C<Positional>|/type/Positional> with the lines of trailing documentation strings.\n\n=head1 Object modification\n\n=head2 method set-WHEREFORE\n\n=begin code :preamble<my $declarator;my $object>\n$declarator.set-WHEREFORE($object);\n=end code\n\nSet the object for which the C<RakuAST::Doc::Declarator> object contains\nthe documentation.\n\n=head2 method set-leading\n\n=begin code :preamble<my $declarator>\n$declarator.set-leading;  # reset\n$declarator.set-leading(\"foo\", \"bar\");\n=end code\n\nSet the leading documentation.  If no arguments are specified, reset to\nnot having any leading documentation.\n\n=head2 method add-leading\n\n=begin code :preamble<my $declarator>\n$declarator.add-leading(\"additional\");\n=end code\n\nAdd a line to the leading documentation.\n\n=head2 method set-trailing\n\n=begin code :preamble<my $declarator>\n$declarator.set-trailing;  # reset\n$declarator.set-trailing(\"foo\", \"bar\");\n=end code\n\nSet the trailing documentation.  If no arguments are specified, reset to\nnot having any trailing documentation.\n\n=head2 method add-trailing\n\n=begin code :preamble<my $declarator>\n$declarator.add-trailing(\"additional\");\n=end code\n\nAdd a line to the trailing documentation.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/RakuAST/Doc/DeclaratorTarget.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"basic\")\n\n=TITLE class RakuAST::Doc::DeclaratorTarget\n\n=SUBTITLE Provide leading/trailing doc functionality\n\n    role RakuAST::Doc::DeclaratorTarget { }\n\nThe C<RakuAST::Doc::DeclaratorTarget> role is done by objects that support\nleading and trailing documentation.\n\nSupport for L<C<RakuAST>|/type/RakuAST> functionality is available in language version\nC<6.e+> and was added in Rakudo compiler release 2023.02.  In earlier\nlanguage versions it is only available when specifying:\n\n    use experimental :rakuast;\n\n=head2 Object introspection\n\nObjects doing the C<RakuAST::Doc::DeclaratorTarget> role are typically\ncreated when parsing Raku Programming Language code for objects that\nallow leading (C<#|>) and trailing (C<#=>) documentation on them.\nSo most developers will only need to know how to introspect the objects\ncreated.\n\n=head3 method WHY\n\n=begin code :preamble<my $target>\nwith $target.WHY {\n    say \"leading: $_.leading()\";\n    say \"trailing: $_.trailing()\";\n}\n=end code\n\nReturns the L«C<RakuAST::Doc::Declarator>|/type/RakuAST::Doc::Declarator»\nobject containing the declarator documentation, if any.\n\n=head1 Object creation\n\nEach object doing the C<RakuAST::Doc::DeclaratorTarget> role has its own\nwhy of creation.  So there's nothing general that can be said about it\nhere.\n\n=head1 Object modification\n\n=head2 method set-WHY\n\n=begin code :preamble<my $target; my $declarator>\n$target.set-WHY($declarator);\n=end code\n\nSet the L<C<RakuAST::Doc::Declarator>|/type/RakuAST::Doc::Declarator> object to be associated.\n\n=head2 method cut-WHY\n\n=begin code :preamble<my $target>\nmy $WHY := $target.cut-WHY;\n=end code\n\nRemoves the L<C<RakuAST::Doc::Declarator>|/type/RakuAST::Doc::Declarator> object, if any.  Intended\nto be used when deparsing / stringification to prevent an infinite loop\nbecause the L<C<RakuAST::Doc::Declarator>|/type/RakuAST::Doc::Declarator> object points to its target,\nand the other way around.  Usually called on a clone of the original\ntarget.\n\n=head2 method set-leading\n\n=begin code :preamble<my $target>\n$target.set-leading;  # reset\n$target.set-leading(\"foo\", \"bar\");\n=end code\n\nSet the leading documentation.  If no arguments are specified,\nreset to not having any leading documentation.  Creates a\nL<C<RakuAST::Doc::Declarator>|/type/RakuAST::Doc::Declarator> object and sets it in the C<.WHY>\nif there wasn't one already.\n\n=head2 method add-leading\n\n=begin code :preamble<my $target>\n$target.add-leading(\"additional\");\n=end code\n\nAdd a line to the leading documentation. Creates a\nL<C<RakuAST::Doc::Declarator>|/type/RakuAST::Doc::Declarator> object and sets it in the C<.WHY>\nif there wasn't one already.\n\n=head2 method set-trailing\n\n=begin code :preamble<my $target>\n$target.set-trailing;  # reset\n$target.set-trailing(\"foo\", \"bar\");\n=end code\n\nSet the trailing documentation.  If no arguments are specified,\nreset to not having any trailing documentation.  Creates a\nL<C<RakuAST::Doc::Declarator>|/type/RakuAST::Doc::Declarator> object and sets it in the C<.WHY>\nif there wasn't one already.\n\n=head2 method add-trailing\n\n=begin code :preamble<my $target>\n$target.add-trailing(\"additional\");\n=end code\n\nAdd a line to the trailing documentation. Creates a\nL<C<RakuAST::Doc::Declarator>|/type/RakuAST::Doc::Declarator> object and sets it in the C<.WHY>\nif there wasn't one already.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/RakuAST/Doc/Markup.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class RakuAST::Doc::Markup\n\n=SUBTITLE Contains the information about RakuDoc markup\n\n    class RakuAST::Doc::Markup { }\n\nThe C<RakuAST::Doc::Markup> class contains the information about\nmarkup codes in a L«C<RakuAST::Doc::Paragraph>|/type/RakuAST::Doc::Paragraph»\nor another C<RakuAST::Doc::Markup> object.\n\nSupport for L<C<RakuAST>|/type/RakuAST> functionality is available in language version\nC<6.e+> and was added in Rakudo compiler release 2023.02.  In earlier\nlanguage versions it is only available when specifying:\n\n    use experimental :rakuast;\n\n=head2 Object introspection\n\nC<RakuAST::Doc::Markup> objects are typically created when parsing\nRaku Programming Language code that has C<RakuDoc> markers in it.\nSo most developers will only need to know how to introspect the\nobjects created.\n\n=head3 method letter\n\n=begin code :preamble<my $markup>\nsay \"letter = $markup.letter()\";  # B␤\n=end code\n\nReturns the letter of the markup.  This is usually an uppercase\nletter (any Unicode codepoint with the \"Lu\" property), such as\nC<B>, but can also be a letter like C<Δ>.\n\n=head3 method opener\n\n=begin code :preamble<my $markup>\nsay \"opener = $markup.opener()\";  # <␤\n=end code\n\nReturns the string that indicates the opener of the markup.\nThis is typically \"<\", \"<<\" or \"«\".  It is mostly intended to\nbe used for stringification of the C<RakuAST::Doc::Markup>\nobject.\n\n=head3 method closer\n\n=begin code :preamble<my $markup>\nsay \"closer = $markup.closer()\";  # >␤\n=end code\n\nReturns the string that indicates the closer of the markup.\nThis is typically \">\", \">>\" or \"»\".  It is mostly intended to\nbe used for stringification of the C<RakuAST::Doc::Markup>\nobject.\n\n=head3 method atoms\n\n=begin code :preamble<my $markup>\n.say for $markup.atoms;  # and␤\n=end code\n\nReturns a L<C<List>|/type/List> of the atoms.  Note that each element can\neither be a string or another C<RakuAST::Doc::Markup> object.\n\n=head3 method meta\n\n=begin code :preamble<my $markup>\n.say for $markup.meta;\n=end code\n\nReturns a L<C<List>|/type/List> of the metaobjects.  Note that each element\ncan either be a string or another C<RakuAST::Doc::Markup> object.\nThe C<RakuDoc> standard assigns meaning to the meta-information\nof markup for certain letters, such as a URL (in case of C<L>).\n\n=head3 method Str\n\n=begin code :preamble<my $markup>\nput $markup;  # B<and>␤\n=end code\n\nReturns the string for the markup object, with any embedded\nmarkup also stringified.\n\n=head3 method raku\n\n=begin code :preamble<my $markup; use experimental :rakuast>\n# method .gist falls back to .raku\nsay $markup;  # RakuAST::Doc::Markup.new(...\n=end code\n\nReturns the string that is needed for the creation of the markup\nusing L<C<RakuAST>|/type/RakuAST> calls.\n\n=head1 Object creation\n\nOne seldom creates C<RakuAST::Doc::Markup> objects directly.  This\ndocumentation is intended for those few people who'd like to devise\ntheir own way of programmatically building a C<RakuAST::Doc::Markup>\nobject.\n\n=head2 method new\n\n=begin code :method\nmethod new(\n  Str:D  :$letter!,      # markup identifier, e.g. \"B\"\n  Str:D  :$opener = \"<\", # opener marker\n  Str:D  :$closer = \">\", # closer marker\n         :@atoms,        # any atoms of this markup\n         :@meta,         # any meta of this markup\n)\n=end code\n\nThe C<new> method can be called to create a new C<RakuAST::Doc::Markup>\nobject.  It only takes named arguments, with the C<:letter> argument\nbeing mandatory.\n\n=begin code :lang<rakudoc>\nB<and>\n=end code\n\n=begin code :lang<raku> :preamble<use experimental :rakuast>\nmy $markup = RakuAST::Doc::Markup.new(\n  :letter<B>,\n  :atoms(\"and\")\n);\n=end code\n\nNote that all arguments except C<:letter> are optional.  So it is\npossible to create \"empty\" markup as well.\n\n=head3 :letter\n\nThe \"type\" of markup object.  Generally expected to be an uppercase\nletter, but this is not enforced.  The C<RakuDoc> standard assigns\nmeaning to most ASCII uppercase letters, so one would probably do well\nadhering to this standard when using ASCII uppercase letters.\n\n=head3 :opener\n\nThe markup opening sequence marker.  Defaults to C<<\"<\">>.  Mostly\nused for stringification.\n\n=head3 :closer\n\nThe markup closing sequence marker.  Defaults to C<<\">\">>.  Mostly\nused for stringification.\n\n=head3 :atoms\n\nThe actual content of the markup, specified as a L<C<Positional>|/type/Positional>.  Each\nelement can either be a string or another C<RakuAST::Doc::Markup>\nobject.\n\n=head3 :meta\n\nThe meta-information of the markup, specified as a L<C<Positional>|/type/Positional>.\nEach element can either be a string or another C<RakuAST::Doc::Markup>\nobject.  Note that the C<RakuDoc> standard associates certain meaning\nto the meta-information for certain letters, such as the meta-information\nbeing a URL in the case of C<L> being the letter.\n\n=head1 Object modification\n\n=head2 method set-atoms\n\n=begin code :preamble<my $markup>\n$markup.set-atoms;  # reset\n$markup.set-atoms( (\"and\",) );\n=end code\n\nSet the atoms to the given L<C<Positional>|/type/Positional>.  Values are expected\nto be either a string, or a C<RakuAST::Doc::Markup> object.\nIf no values are specified, then the object will have no atoms.\n\n=head2 method add-atom\n\n=begin code :preamble<my $markup>\n$markup.add-atom( (\"foo\",) );\n=end code\n\nAdd an atom to the atoms of the object.  Values are expected\nto be either a string, or a C<RakuAST::Doc::Markup> object.\n\n=head2 method set-meta\n\n=begin code :preamble<my $markup>\n$markup.set-meta;  # reset\n$markup.set-meta( (\"https://raku.org\",) );\n=end code\n\nSet the meta-information to the given L<C<Positional>|/type/Positional>.  Values are\nexpected to be either a string, or a C<RakuAST::Doc::Markup> object.\nIf no values are specified, then the object will have no\nmeta-information.\n\n=head2 method add-meta\n\n=begin code :preamble<my $markup>\n$markup.add-meta( (\"bar\",) );\n=end code\n\nAdd an item to the meta-information of the object.  Values are\nexpected to be either a string, or a C<RakuAST::Doc::Markup>\nobject.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/RakuAST/Doc/Paragraph.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class RakuAST::Doc::Paragraph\n\n=SUBTITLE Contains the information about a RakuDoc paragraph\n\n    class RakuAST::Doc::Paragraph { }\n\nThe C<RakuAST::Doc::Paragraph> class contains the information about a\nlogical paragraph in a C<RakuDoc> block.\n\nSupport for L<C<RakuAST>|/type/RakuAST> functionality is available in language version\nC<6.e+> and was added in Rakudo compiler release 2023.02.  In earlier\nlanguage versions it is only available when specifying:\n\n    use experimental :rakuast;\n\n=head2 Object introspection\n\nC<RakuAST::Doc::Paragraph> objects are typically created when parsing\nRaku Programming Language code that has C<RakuDoc> markers in it.\nSo most developers will only need to know how to introspect the\nobjects created.\n\n=head3 method atoms\n\n=begin code :preamble<my $paragraphs>\n.put for $paragraphs.atoms;\n# Text before ␤B<and>␤ after markup␤\n=end code\n\nReturns the atoms of the paragraph.  These are generally a mix of\nstrings and L«C<RakuAST::Doc::Markup>|/type/RakuAST::Doc::Markup»\nobjects.\n\n=head3 method Str\n\n=begin code :preamble<my $paragraph>\nput $paragraph;  # Text before B<and> after markup␤␤\n=end code\n\nReturns the string for the paragraph, with any markup stringified.\n\n=head3 method raku\n\n=begin code :preamble<my $block>\n# method .gist falls back to .raku\nsay $block;  # RakuAST::Doc::Paragraph.new(...\n=end code\n\nReturns the string that is needed for the creation of the paragraph\nusing L<C<RakuAST>|/type/RakuAST> calls.\n\n=head1 Object creation\n\nOne seldom creates C<RakuAST::Doc::Paragraph> objects directly.  This\ndocumentation is intended for those few people who'd like to devise\ntheir own way of programmatically building a C<RakuAST::Doc::Paragraph>\nobject.\n\n=head2 method new\n\n    method new(*@atoms)\n\nThe C<new> method must be called to create a new C<RakuAST::Doc::Paragraph>\nobject.  It takes any number of positional arguments as the atoms of\nthe logical paragraph, where an atom is either a string or a\nL<C<RakuAST::Doc::Markup>|/type/RakuAST::Doc::Markup> object.\n\nTypically a C<RakuAST::Doc::Paragraph> object is only created if a\nlogical paragraph has at least one markup object.\n\n=begin code :lang<raku> :preamble<use experimental :rakuast>\nmy $paragraph = RakuAST::Doc::Paragraph.new(\n  \"Text before \",\n  RakuAST::Doc::Markup.new(:letter<B>, :atoms(\"and\")),\n  \" after markup\\n\"\n);\n=end code\n\n=head1 Object modification\n\n=head2 method add-atom\n\n=begin code :preamble<my $paragraph>\n$paragraph.add-atom(\"baz\\n\");\n=end code\n\nAdd an atom: should be a string, or a L<C<RakuAST::Doc::Markup>|/type/RakuAST::Doc::Markup>\nobject.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/RakuAST/Doc.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"package\") :category(\"basic\")\n\n=TITLE package RakuAST::Doc\n\n=SUBTITLE Namespace for holding RakuDoc related classes\n\n    package RakuAST::Doc { }\n\nThe C<RakuAST::Doc> package serves as a common namespace for all\nclasses that provide RakuDoc functionality.\n\nSupport for L<C<RakuAST>|/type/RakuAST> functionality is available in language version\nC<6.e+> and was added in Rakudo compiler release 2023.02.  In earlier\nlanguage versions it is only available when specifying:\n\n    use experimental :rakuast;\n\n=head1 Classes\n\nRelations between the C<RakuAST::Doc::> classes:\n\n=for code :lang<ascii-diagram>\n    RakuAST::Doc::Block\n     \\- paragraphs\n         |- string\n         |- RakuAST::Doc::Paragraph\n         |   \\- atoms\n         |       |- string\n         |       \\- RakuAST::Doc::Markup\n         |           \\- atoms\n         |               |- string\n         |               \\- RakuAST::Doc::Markup\n         \\- RakuAST::Doc::Block\n\nNote that this structure is recursive with regards to the\nL«C<RakuAST::Doc::Block>|/type/RakuAST::Doc::Block» object (which can\noccur as an element of the paragraphs of a L<C<RakuAST::Doc::Block>|/type/RakuAST::Doc::Block>),\nand the L«C<RakuAST::Doc::Markup>|/type/RakuAST::Doc::Markup» object\n(which can occur as an element of the atoms of a\nL«C<RakuAST::Doc::Markup>|/type/RakuAST::Doc::Markup»).\n\n=head2 class RakuAST::Doc::Block\n\nThe L<C<RakuAST::Doc::Block>|/type/RakuAST::Doc::Block> object contains the information about a block\nof C<RakuDoc>.  It has a type (\"foo\" in the case of C<=begin foo>)\nand it has zero or more paragraphs.  Each paragraph may consist\nof a string (which implies there is no extra markup in there) or\na L<C<RakuAST::Doc::Paragraph>|/type/RakuAST::Doc::Paragraph> object, or another L<C<RakuAST::Doc::Block>|/type/RakuAST::Doc::Block>\nin the case of C<RakuDoc> blocks embedding other blocks.\n\nA L<C<RakuAST::Doc::Block>|/type/RakuAST::Doc::Block> typically occurs in\nC<RakuAST::StatementList> objects when\nit is the result of parsing Raku Programming Language code, or\nC<RakuDoc> documentation.\n\n=head2 class RakuAST::Doc::Paragraph\n\nThe L«C<RakuAST::Doc::Paragraph>|/type/RakuAST::Doc::Paragraph» object\ncontains the information about the atoms that constitute the paragraph.\nEach atom may be either a string or a L«C<RakuAST::Doc::Markup>|/type/RakuAST::Doc::Markup» object.\n\n=head2 class RakuAST::Doc::Markup\n\nThe L«C<RakuAST::Doc::Markup>|/type/RakuAST::Doc::Markup» object contains\nthe information about a markup atom, and itself contains a list of\natoms.  Each atom may be either a string or a L«C<RakuAST::Doc::Markup>|/type/RakuAST::Doc::Markup»\nobject in the case of embedded markup.\n\n=head2 EXAMPLE\n\nThis small piece of RakuDoc:\n\n=begin code\n=begin rakudoc\nThis is L<B<example>|https://example.com>>.\n=end rakudoc\n=end code\n\nis represented in C<RakuAST::Doc::> objects like this:\n\n=begin code :preamble<use experimental :rakuast>\nRakuAST::Doc::Block.new(\n  type       => \"rakudoc\",\n  paragraphs => (\n    RakuAST::Doc::Paragraph.new(\n      \"This is \",\n      RakuAST::Doc::Markup.new(\n        letter => \"L\",\n        opener => \"<\",\n        closer => \">\",\n        atoms  => (\n          RakuAST::Doc::Markup.new(\n            letter => \"B\",\n            opener => \"<\",\n            closer => \">\",\n            atoms  => (\n              \"example\",\n            )\n          ),\n        ),\n        meta   => (\n          \"https://example.com\",\n        )\n      ),\n      \">.\\n\"\n    ),\n  )\n);\n=end code\n\n=head2 class RakuAST::Doc::Declarator\n\nThe L«C<RakuAST::Doc::Declarator>|/type/RakuAST::Doc::Declarator»\nobject contains the leading and trailing documentation of a\nL<C<RakuAST>|/type/RakuAST> object doing the L<C<RakuAST::Doc::DeclaratorTarget>|/type/RakuAST::Doc::DeclaratorTarget> role.\n\n=head2 role RakuAST::Doc::DeclaratorTarget\n\nThe L«C<RakuAST::Doc::DeclaratorTarget>|/type/RakuAST::Doc::DeclaratorTarget»\nrole is done by L<C<RakuAST>|/type/RakuAST> objects that allow leading and/or trailing\ndocumentation when used in Raku source code.\n\n=head2 EXAMPLE\n\nRaku code with leading and trailing declarator doc:\n\n=begin code\n#| important variable\nmy $foo;  #= really!\n=end code\n\nis represented like this:\n\n=begin code :preamble<use experimental :rakuast>\nRakuAST::VarDeclaration::Simple.new(\n  sigil       => \"\\$\",\n  desigilname => RakuAST::Name.from-identifier(\"foo\")\n).declarator-docs(\n  leading  => (\n    \"important variable\\n\",\n  ),\n  trailing => (\n    \"really!\\n\",\n  )\n);\n=end code\n\nNote that the representation is B<not> showing the actual\nL«C<RakuAST::Doc::Declarator>|/type/RakuAST::Doc::Declarator» object.  This is hidden in the\nC<.declarator-docs> call.\n\nThis is needed to create a single-statement representation\nof the target object (in this case the\nC<RakuAST::VarDeclaration::Simple>\nobject) and its associated L«C<RakuAST::Doc::Declarator>|/type/RakuAST::Doc::Declarator» object.\n\nThat is because objects doing the L<C<RakuAST::Doc::DeclaratorTarget>|/type/RakuAST::Doc::DeclaratorTarget>\nrefer to the associated L<C<RakuAST::Doc::Declarator>|/type/RakuAST::Doc::Declarator> object in\nthe C<.WHY> method.  But conversely, the L<C<RakuAST::Doc::Declarator>|/type/RakuAST::Doc::Declarator>\nobject refers to its subject with the C<.WHEREFORE> method.  So\nthere's a chicken-and-egg problem, which was solved by introducing\nthe C<.declarator-docs> method on objects doing the\nL<C<RakuAST::Doc::DeclaratorTarget>|/type/RakuAST::Doc::DeclaratorTarget> role.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/RakuAST.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE package RakuAST\n\n=SUBTITLE Namespace for holding RakuAST related classes\n\n    package RakuAST { }\n\nThe C<RakuAST> package serves as a common namespace for all classes\nthat provide RakuAST functionality.\n\nSupport for C<RakuAST> functionality is available in language version\nC<6.e+> and was added in Rakudo compiler release 2023.02.  In earlier\nlanguage versions it is only available when specifying:\n\n    use experimental :rakuast;\n\n=head1 Classes\n\nDocumentation of C<RakuAST> classes is ongoing, while the development\nof RakuAST is still ongoing as well.\n\n=head1 Useful methods\n\nTo make developing in RakuAST easier, several helper methods are\navailable.\n\nThe C<AST> method can be called on a string containing Raku source\ncode, and it will return the RakuAST object tree needed to create\nthe AST of the given source code.\n\n=for code :lang<shell>\n$ raku -e 'say Q/\"Hello World\"/.AST.^name'\nRakuAST::StatementList\n\nAnd the gist of such a RakuAST object tree shows the Raku source\ncode to create such a tree:\n\n=for code :lang<shell>\n$ raku -e 'say Q/\"Hello World\"/.AST'\nRakuAST::StatementList.new(\n  RakuAST::Statement::Expression.new(\n    expression => RakuAST::Call::Name.new(\n      name => RakuAST::Name.from-identifier(\"say\"),\n      args => RakuAST::ArgList.new(\n        RakuAST::QuotedString.new(\n          segments   => (\n            RakuAST::StrLiteral.new(\"Hello World\"),\n          )\n        )\n      )\n    )\n  )\n)\n\nThis can be used as a base to create your own RakuAST object trees.\n\nIt is also possible to create a Raku source representation of a\nRakuAST object tree, by calling the C<.DEPARSE> method on it:\n\n=for code :lang<shell>\n$ raku -e 'say Q/\"Hello World\"/.AST.DEPARSE'\nsay(\"Hello World\")\n\nPlease note that the C<.AST> method depends on the Raku grammar,\nwhich may not yet support all of the Raku Programming Language\nfeatures that you want to use.  And vice-versa: the C<.DEPARSE>\nmethod may not be able to create a valid, executable Raku source\nrepresentation, especially if the RakuAST object tree has been\nbuilt \"manually\".\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Range.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class Range\n\n=SUBTITLE Interval of ordered values\n\n    class Range is Cool does Iterable does Positional {}\n\nRanges serve two main purposes: to generate lists of consecutive\nnumbers or strings, and to act as a matcher to check if a number\nor string is within a certain range.\n\nRanges are constructed using one of the four possible range operators,\nwhich consist of two dots, and optionally a caret which indicates that\nthe endpoint marked with it is excluded from the range.\n\n    1 .. 5;  # 1 <= $x <= 5\n    1^.. 5;  # 1 <  $x <= 5\n    1 ..^5;  # 1 <= $x <  5\n    1^..^5;  # 1 <  $x <  5\n\nThe caret is also a prefix operator for constructing numeric ranges\nstarting from zero:\n\n    my $x = 10;\n    say ^$x;     # same as 0 ..^ $x.Numeric\n\nIterating a range (or calling the C<list> method) uses the same semantics as\nthe C<++> prefix and postfix operators, i.e., it calls the C<succ> method on\nthe start point, and then the generated elements.\n\nRanges always go from small to larger elements; if the start point is bigger\nthan the end point, the range is considered empty.\n\n    for 1..5 { .say };           # OUTPUT: «1␤2␤3␤4␤5␤»\n    say ('a' ^..^ 'f').list;     # OUTPUT: «(b c d e)␤»\n    say 5 ~~ ^5;                 # OUTPUT: «False␤»\n    say 4.5 ~~ 0..^5;            # OUTPUT: «True␤»\n    say (1.1..5).list;           # OUTPUT: «(1.1 2.1 3.1 4.1)␤»\n\nUse the L«C<...>|/language/operators#infix_...» sequence operator to produce lists\nof elements that go from larger to smaller values, or to use offsets other than\nincrement-by-1 and other complex cases.\n\nUse C<∞> or C<*> (Whatever) to indicate an end point to be open-ended.\n\n=for code\nfor 1..* { .say };       # start from 1, continue until stopped\nfor 1..∞ { .say };       # the same\n\nBeware that a L<C<WhateverCode>|/type/WhateverCode> end point, instead of a plain\nWhatever, will go through the range operator and create another WhateverCode\nwhich returns a Range:\n\n=for code :ok-test<WHAT>\n# A Whatever produces the 1..Inf range\nsay (1..*).^name;        # OUTPUT: «Range␤»\nsay (1..*);              # OUTPUT: «1..Inf␤»\n# Upper end point is now a WhateverCode\nsay (1..*+20).^name;     # OUTPUT: «{ ... }␤»\nsay (1..*+20).WHAT;      # OUTPUT: «(WhateverCode)␤»\nsay (1..*+20).(22);      # OUTPUT: «1..42␤»\n\nRanges implement L<C<Positional>|/type/Positional> interface, so its elements can\nbe accessed using an index. In a case when the index given is bigger than the\nRange object's size, L<C<Nil>|/type/Nil> object will be returned. The access works\nfor lazy Range objects as well.\n\n=for code\nsay (1..5)[1];  # OUTPUT: «2␤»\nsay (1..5)[10]; # OUTPUT: «Nil␤»\nsay (1..*)[10]; # OUTPUT: «11␤»\n\n=head2 Ranges in subscripts\n\nA Range can be used in a subscript to get a range of values. Please note that\nassigning a Range to a scalar container turns the Range into an item. Use\nbinding, @-sigiled containers or a slip to get what you mean.\n\n    my @numbers =  <4 8 15 16 23 42>;\n    my $range := 0..2;\n    .say for @numbers[$range]; # OUTPUT: «4␤8␤15␤»\n    my @range = 0..2;\n    .say for @numbers[@range]; # OUTPUT: «4␤8␤15␤»\n\n=head2 Shifting and scaling intervals\n\nIt is possible to shift or scale the interval of a range:\n\n    say (1..10) + 1;       # OUTPUT: «2..11␤»\n    say (1..10) - 1;       # OUTPUT: «0..9␤»\n    say (1..10) * 2;       # OUTPUT: «2..20␤»\n    say (1..10) / 2;       # OUTPUT: «0.5..5.0␤»\n\n=head2 Matching against Ranges\n\nYou can use L<smartmatch|/routine/~~> to match against Ranges.\n\n    say 3 ~~ 1..12;          # OUTPUT: «True␤»\n    say 2..3 ~~ 1..12;       # OUTPUT: «True␤»\n\nX<|Methods,in-range>\nI<In Rakudo only>, you can use the C<in-range> method for matching\nagainst a range, which in fact is equivalent to smartmatch except it will throw\nan exception when out of range, instead of returning C<False>:\n\n    say ('א'..'ת').in-range('ע');  # OUTPUT: «True␤»\n\nHowever, if it is not included in the range:\n=for code\nsay ('א'..'ת').in-range('p', \"Letter 'p'\");\n# OUTPUT: «(exit code 1) Letter 'p' out of range. Is: \"p\", should be in \"א\"..\"ת\"␤\n\nThe second parameter to C<in-range> is the optional message that will be printed\nwith the exception. It will print C<Value> by default.\n\n=head1 Methods\n\n=head2 method new\n\n     multi method new(Range: \\min, \\max, :$excludes-min, :$excludes-max)\n\nCreates a new Range with the given minimum and maximum, and with the min and\nmax excluded based on the values passed in the corresponding named arguments.\n\n=head2 method ACCEPTS\n\n     multi method ACCEPTS(Range:D: Mu \\topic)\n     multi method ACCEPTS(Range:D: Range \\topic)\n     multi method ACCEPTS(Range:D: Cool:D \\got)\n     multi method ACCEPTS(Range:D: Complex:D \\got)\n\n\nIndicates if the C<Range> contains (overlaps with) another C<Range>.\nAs an example:\n\n    my $p = Range.new( 3, 5  );\n    my $r = Range.new( 1, 10 );\n\n    say $p.ACCEPTS( $r );    # OUTPUT: «False␤»\n    say $r.ACCEPTS( $p );    # OUTPUT: «True␤»\n    say $r ~~ $p;            # OUTPUT: «False␤»  (same as $p.ACCEPTS( $r )\n    say $p ~~ $r;            # OUTPUT: «True␤»   (same as $r.ACCEPTS( $p )\n\nAn infinite C<Range> always contains any other C<Range>, therefore:\n\n    say 1..10 ~~ -∞..∞;    # OUTPUT: «True␤»\n    say 1..10 ~~ -∞^..^∞;  # OUTPUT: «True␤»\n\nSimilarly, a C<Range> with open boundaries often includes other ranges:\n\n    say 1..2 ~~ *..10;  # OUTPUT: «True␤»\n    say 2..5 ~~ 1..*;   # OUTPUT: «True␤»\n\n\nIt is also possible to use non-numeric ranges, for instance string based\nones:\n\n   say 'a'..'j' ~~ 'b'..'c';  # OUTPUT: «False␤»\n   say 'b'..'c' ~~ 'a'..'j';  # OUTPUT: «True␤»\n   say 'raku' ~~ -∞^..^∞;     # OUTPUT: «True␤»\n   say 'raku' ~~ -∞..∞;       # OUTPUT: «True␤»\n   say 'raku' ~~ 1..*;        # OUTPUT: «True␤»\n\n\nWhen smartmatching a C<Range> of integers with a L<C<Cool>|/type/Cool> (string)\nthe C<ACCEPTS> methods exploits the L<before|/routine/before>\nand L<after|/routine/after> operators in order to check that\nthe L<C<Cool>|/type/Cool> value is overlapping the range:\n\n   say 1..10 ~~ '5';  # OUTPUT: «False␤»\n   say '5' before 1;  # OUTPUT: «False␤»\n   say '5' after 10;  # OUTPUT: «True␤»\n   say '5' ~~ *..10;  # OUTPUT: «False␤»\n\nIn the above example, since the C<'5'> string is I<after> the C<10> integer\nvalue, the C<Range> does not overlap with the specified value.\n\nWhen matching with a L<C<Mu>|/type/Mu> instance (i.e., a generic instance),\nthe L<cmp|/routine/cmp> operator is used.\n\n=head2 method min\n\n    method min(Range:D:)\n\nReturns the start point of the range.\n\n    say (1..5).min;                                   # OUTPUT: «1␤»\n    say (1^..^5).min;                                 # OUTPUT: «1␤»\n\n=head2 method excludes-min\n\n    method excludes-min(Range:D: --> Bool:D)\n\nReturns C<True> if the start point is excluded from the range, and C<False>\notherwise.\n\n    say (1..5).excludes-min;                          # OUTPUT: «False␤»\n    say (1^..^5).excludes-min;                        # OUTPUT: «True␤»\n\n=head2 method max\n\n    method max(Range:D:)\n\nReturns the end point of the range.\n\n    say (1..5).max;                                   # OUTPUT: «5␤»\n    say (1^..^5).max;                                 # OUTPUT: «5␤»\n\n=head2 method excludes-max\n\n    method excludes-max(Range:D: --> Bool:D)\n\nReturns C<True> if the end point is excluded from the range, and C<False>\notherwise.\n\n    say (1..5).excludes-max;                          # OUTPUT: «False␤»\n    say (1^..^5).excludes-max;                        # OUTPUT: «True␤»\n\n=head2 method bounds\n\n    method bounds()\n\nReturns a list consisting of the start and end point.\n\n    say (1..5).bounds;                                # OUTPUT: «(1 5)␤»\n    say (1^..^5).bounds;                              # OUTPUT: «(1 5)␤»\n\n=head2 method infinite\n\n    method infinite(Range:D: --> Bool:D)\n\nReturns C<True> if either end point was declared with C<∞> or C<*>.\n\n    say (1..5).infinite;                              # OUTPUT: «False␤»\n    say (1..*).infinite;                              # OUTPUT: «True␤»\n\n=head2 method is-int\n\n    method is-int(Range:D: --> Bool:D)\n\nReturns C<True> if both end points are L<C<Int>|/type/Int> values.\n\n    say ('a'..'d').is-int;                            # OUTPUT: «False␤»\n    say (1..^5).is-int;                               # OUTPUT: «True␤»\n    say (1.1..5.5).is-int;                            # OUTPUT: «False␤»\n\n=head2 method int-bounds\n\n    proto method int-bounds(|)\n    multi method int-bounds()\n    multi method int-bounds($from is rw, $to is rw --> Bool:D)\n\nIf the C<Range> is an integer range (as indicated by L<is-int|/routine/is-int>), then this\nmethod returns a list with the first and last value it will iterate over\n(taking into account L<excludes-min|/routine/excludes-min> and L<excludes-max|/routine/excludes-max>).  Returns a\nL«C<Failure>|/type/Failure» if it is not an integer range.\n\n    say (2..5).int-bounds;                            # OUTPUT: «(2 5)␤»\n    say (2..^5).int-bounds;                           # OUTPUT: «(2 4)␤»\n\nIf called with (writable) arguments, these will take the values of the\nhigher and lower bound and returns whether integer bounds could be determined\nfrom the C<Range>:\n\n    if (3..5).int-bounds( my $min, my $max) {\n        say \"$min, $max\" ; # OUTPUT: «3, 5␤»\n    }\n    else {\n        say \"Could not determine integer bounds\";\n    }\n\n=head2 method minmax\n\n    multi method minmax(Range:D: --> List:D)\n\nIf the C<Range> is an integer range (as indicated by L<is-int|/routine/is-int>), then this\nmethod returns a list with the first and last value it will iterate over (taking\ninto account L<excludes-min|/routine/excludes-min> and L<excludes-max|/routine/excludes-max>). If the range is not an\ninteger range, the method will return a two element list containing the start\nand end point of the range unless either of L<excludes-min|/routine/excludes-min> or\nL<excludes-max|/routine/excludes-max> are C<True> in which case a L<C<Failure>|/type/Failure> is returned.\n\n    my $r1 = (1..5); my $r2 = (1^..5);\n    say $r1.is-int, ', ', $r2.is-int;                 # OUTPUT: «True, True␤»\n    say $r1.excludes-min, ', ', $r2.excludes-min;     # OUTPUT: «False, True␤»\n    say $r1.minmax, ', ', $r2.minmax;                 # OUTPUT: «(1 5), (2 5)␤»\n\n    my $r3 = (1.1..5.2); my $r4 = (1.1..^5.2);\n    say $r3.is-int, ', ', $r4.is-int;                 # OUTPUT: «False, False␤»\n    say $r3.excludes-max, ', ', $r4.excludes-max;     # OUTPUT: «False, True␤»\n    say $r3.minmax;                                   # OUTPUT: «(1.1 5.2)␤»\n    say $r4.minmax;\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::AdHoc: Cannot return minmax on Range with excluded ends␤»\n\n=head2 method elems\n\n    method elems(Range:D: --> Numeric:D)\n\nReturns the number of elements in the range, e.g. when being iterated over,\nor when used as a L<C<List>|/type/List>.  Returns 0 if the start point is larger than the\nend point, including when the start point was specified as C<∞>. Fails when\nthe Range is lazy, including when the end point was specified as C<∞> or\neither end point was specified as C<*>.\n\n    say (1..5).elems;                                 # OUTPUT: «5␤»\n    say (1^..^5).elems;                               # OUTPUT: «3␤»\n\n=head2 method list\n\n    multi method list(Range:D:)\n\nGenerates the list of elements that the range represents.\n\n    say (1..5).list;                                  # OUTPUT: «(1 2 3 4 5)␤»\n    say (1^..^5).list;                                # OUTPUT: «(2 3 4)␤»\n\n=head2 method flat\n\n    method flat(Range:D:)\n\nGenerates a L«C<Seq>|/type/Seq» containing the elements that the\nrange represents.\n\n=head2 method pick\n\n    multi method pick(Range:D:         --> Any:D)\n    multi method pick(Range:D: $number --> Seq:D)\n\nPerforms the same function as C<Range.list.pick>, but attempts to optimize\nby not actually generating the list if it is not necessary.\n\n=head2 method roll\n\n    multi method roll(Range:D:         --> Any:D)\n    multi method roll(Range:D: $number --> Seq:D)\n\nPerforms the same function as C<Range.list.roll>, but attempts to optimize\nby not actually generating the list if it is not necessary.\n\n=head2 method sum\n\n    multi method sum(Range:D:)\n\nReturns the sum of all elements in the Range. Throws L<C<X::Str::Numeric>|/type/X::Str::Numeric> if an\nelement can not be coerced into Numeric.\n\n    (1..10).sum                                       # 55\n\n=head2 method reverse\n\n    method reverse(Range:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> where all elements that the C<Range> represents have\nbeen reversed. Note that reversing an infinite C<Range> won't produce any\nmeaningful results.\n\n=for code\nsay (1^..5).reverse;                            # OUTPUT: «(5 4 3 2)␤»\nsay ('a'..'d').reverse;                         # OUTPUT: «(d c b a)␤»\nsay (1..∞).reverse;                             # OUTPUT: «(Inf Inf Inf ...)␤»\n\n=head2 method Capture\n\n    method Capture(Range:D: --> Capture:D)\n\nReturns a L<C<Capture>|/type/Capture> with values of L«C<.min>|/type/Range#method_min»\nL«C<.max>|/type/Range#method_max»,\nL«C<.excludes-min>|/type/Range#method_excludes-min»,\nL«C<.excludes-max>|/type/Range#method_excludes-max»,\nL«C<.infinite>|/type/Range#method_infinite», and\nL«C<.is-int>|/type/Range#method_is-int» as named arguments.\n\n=head2 method rand\n\n    method rand(Range:D --> Num:D)\n\nReturns a pseudo-random value belonging to the range.\n\n    say (1^..5).rand;                              # OUTPUT: «1.02405550417031␤»\n    say (0.1..0.3).rand;                           # OUTPUT: «0.2130353370062␤»\n\n=head2 method EXISTS-POS\n\n    multi method EXISTS-POS(Range:D: int \\pos)\n    multi method EXISTS-POS(Range:D: Int \\pos)\n\nReturns C<True> if C<pos> is greater than or equal to zero and lower than\nC<self.elems>. Returns C<False> otherwise.\n\n    say (6..10).EXISTS-POS(2); # OUTPUT: «True␤»\n    say (6..10).EXISTS-POS(7); # OUTPUT: «False␤»\n\n=head2 method AT-POS\n\n    multi method AT-POS(Range:D: int \\pos)\n    multi method AT-POS(Range:D: int:D \\pos)\n\nChecks if the L<C<Int>|/type/Int> position exists and in that case returns the\nelement in that position.\n\n    say (1..4).AT-POS(2) # OUTPUT: «3␤»\n\n=head2 method raku\n\n    multi method raku(Range:D:)\n\nReturns an implementation-specific string that produces an\nL<equivalent|/routine/eqv> object when given to L<EVAL|/routine/EVAL>.\n\n=for code\nsay (1..2).raku # OUTPUT: «1..2␤»\n\n=head2 method fmt\n\n    method fmt(|c)\n\nReturns a string where C<min> and C<max> in the C<Range> have been\nformatted according to C<|c>.\n\nFor more information about parameters, see L<List.fmt|/type/List#method_fmt>.\n\n    say (1..2).fmt(\"Element: %d\", \",\") # OUTPUT: «Element: 1,Element: 2␤»\n\n=head2 method WHICH\n\n    multi method WHICH (Range:D:)\n\nThis returns a string that identifies the object. The string is composed by the\ntype of the instance (C<Range>) and the C<min> and C<max> attributes:\n\n    say (1..2).WHICH # OUTPUT: «Range|1..2␤»\n\n=head2 sub infix:<+>\n\n    multi infix:<+>(Range:D \\r, Real:D \\v)\n    multi infix:<+>(Real:D \\v, Range:D \\r)\n\nTakes a L<C<Real>|/type/Real> and adds that number to both\nboundaries of the C<Range> object. Be careful with\nthe use of parenthesis.\n\n    say (1..2) + 2; # OUTPUT: «3..4␤»\n    say 1..2 + 2;   # OUTPUT: «1..4␤»\n\n=head2 sub infix:<->\n\n    multi infix:<->(Range:D \\r, Real:D \\v)\n\nTakes a L<C<Real>|/type/Real> and subtract that number to both\nboundaries of the C<Range> object. Be careful with\nthe use of parenthesis.\n\n    say (1..2) - 1; # OUTPUT: «0..1␤»\n    say 1..2 - 1;   # OUTPUT: «1..1␤»\n\n=head2 sub infix:<*>\n\n    multi infix:<*>(Range:D \\r, Real:D \\v)\n    multi infix:<*>(Real:D \\v, Range:D \\r)\n\nTakes a L<C<Real>|/type/Real> and multiply both boundaries\nof the C<Range> object by that number.\n\n    say (1..2) * 2; # OUTPUT: «2..4␤»\n\n=head2 sub infix:</>\n\n    multi infix:</>(Range:D \\r, Real:D \\v)\n\nTakes a L<C<Real>|/type/Real> and divide both boundaries\nof the C<Range> object by that number.\n\n    say (2..4) / 2; # OUTPUT: «1..2␤»\n\n=head2 sub infix:<cmp>\n\n    multi infix:<cmp>(Range:D \\a, Range:D \\b --> Order:D)\n    multi infix:<cmp>(Num(Real) \\a, Range:D \\b --> Order:D)\n    multi infix:<cmp>(Range:D \\a, Num(Real) \\b --> Order:D)\n    multi infix:<cmp>(Positional \\a, Range:D \\b --> Order:D)\n    multi infix:<cmp>(Range:D \\a, Positional \\b --> Order:D)\n\nCompares two C<Range> objects. A L«C<Real>|/type/Real»\noperand will be considered as both the starting point and the ending\npoint of a C<Range> to be compared with the other operand.\nA L«C<Positional>|/type/Positional» operand will be compared with the\nlist returned by the L«C<.list> method|/type/Range#method_list»\napplied to the other operand.\nSee L«C«List infix:<cmp>»|/type/List#infix_cmp»\n\n    say (1..2) cmp (1..2); # OUTPUT: «Same␤»\n    say (1..2) cmp (1..3); # OUTPUT: «Less␤»\n    say (1..4) cmp (1..3); # OUTPUT: «More␤»\n    say (1..2) cmp 3;      # OUTPUT: «Less␤»\n    say (1..2) cmp [1,2];  # OUTPUT: «Same␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Rat.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Rat\n\n=SUBTITLE Rational number (limited-precision)\n\n    class Rat is Cool does Rational[Int, uint64] { }\n\nC<Rat> objects store rational numbers as a pair of a numerator and\ndenominator. Number literals with a dot but without exponent produce\nC<Rat>s.\n\n    say 3.1;          # OUTPUT: «3.1␤»      (same as: Rat.new(31, 10))\n    say 3.1.^name;    # OUTPUT: «Rat␤»\n    say 3.1.nude;     # OUTPUT: «(31 10)␤»\n\n    say <1/2>;        # OUTPUT: «0.5␤»      (same as: Rat.new(1, 2))\n    say <1/2>.^name;  # OUTPUT: «Rat␤»\n    say <1/2>.nude;   # OUTPUT: «(1 2)␤»\n\nThus arithmetic with short dotted-decimal numbers does not suffer\nfrom floating point errors.\n\nTo prevent the numerator and denominator from becoming pathologically large,\nthe denominator is limited to 64 bit storage. On overflow of the denominator\nduring an arithmetic operation\na L<C<Num>|/type/Num> (floating-point number) is returned instead.  You can tune this\nbehavior by setting the\nL<C<$*RAT-OVERFLOW>|/language/variables#index-entry-%24*RAT-OVERFLOW> dynamic\nvariable.\n\nFor example this function crudely approximates a square root, and overflows\nthe denominator quickly:\n\n    sub approx-sqrt($n, $iterations) {\n        my $x = $n;\n        $x = ($x + $n / $x) / 2 for ^$iterations;\n        return $x;\n    }\n    say approx-sqrt(2, 5).^name;     # OUTPUT: «Rat␤»\n    say approx-sqrt(2, 10).^name;    # OUTPUT: «Num␤»\n\nIf you want arbitrary precision arithmetic with rational numbers, use the\nL<C<FatRat>|/type/FatRat> type instead.\n\nC<Rat> objects are immutable.\n\n=head1 Methods\n\n=head2 method raku\n\n    multi method raku(Rat:D: --> Str:D)\n\nReturns an implementation-specific string that produces an L<equivalent|/routine/eqv> object\nwhen given to L<EVAL|/routine/EVAL>.\n\n=for code\nsay (1/3).raku;                # OUTPUT: «<1/3>␤»\nsay (2/4).raku;                # OUTPUT: «0.5␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/RatStr.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class RatStr\n\n=SUBTITLE Dual value rational number and string\n\n    class RatStr is Allomorph is Rat {}\n\nC<RatStr> is a dual value type, a subclass of both\nL«C<Allomorph>|/type/Allomorph», hence L«C<Str>|/type/Str», and\nL«C<Rat>|/type/Rat».\n\nSee L«C<Allomorph>|/type/Allomorph» for further details.\n\n=begin code\nmy $rat-str = <42.1>;\nsay $rat-str.^name;       # OUTPUT: «RatStr␤»\n\nmy Rat $rat = $rat-str;   # OK!\nmy Str $str = $rat-str;   # OK!\n\n# ∈ operator cares about object identity\nsay 42.1 ∈ <42.1  55  1>; # OUTPUT: «False␤»\n=end code\n\n=head1 Methods\n\n=head2 method new\n\n    method new(Rat $i, Str $s)\n\nThe constructor requires both the L<C<Rat>|/type/Rat> and the L<C<Str>|/type/Str> value, when constructing one\ndirectly the values can be whatever is required:\n\n    my $f = RatStr.new(42.1, \"forty two and a bit\");\n    say +$f; # OUTPUT: «42.1␤»\n    say ~$f; # OUTPUT: «\"forty two and a bit\"␤»\n\n=head2 method Capture\n\n    method Capture(RatStr:D: --> Capture:D)\n\nEquivalent to L«C<Mu.Capture>|/type/Mu#method_Capture».\n\n=head2 method Numeric\n\n    multi method Numeric(RatStr:D: --> Rat:D)\n    multi method Numeric(RatStr:U: --> Rat:D)\n\nThe C<:D> variant returns the numeric portion of the invocant. The C<:U> variant issues\na warning about using an uninitialized value in numeric context and then returns value C<0.0>.\n\n=head2 method Rat\n\n    method Rat\n\nReturns the L<C<Rat>|/type/Rat> value of the C<RatStr>.\n\n=head2 method Real\n\n    multi method Real(Real:D: --> Rat:D)\n    multi method Real(Real:U: --> Rat:D)\n\nThe C<:D> variant returns the numeric portion of the invocant. The C<:U> variant issues\na warning about using an uninitialized value in numeric context and then returns value C<0.0>.\n\n=head1 Operators\n\n=head2 infix C«===»\n\n    multi infix:<===>(RatStr:D $a, RatStr:D $b)\n\nC<RatStr> Value identity operator. Returns C<True> if the L<C<Rat>|/type/Rat>\nvalues of C<$a> and C<$b> are L<identical|/routine/===> and their L<C<Str>|/type/Str>\nvalues are also L<identical|/routine/===>. Returns C<False> otherwise.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Rational.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"basic\")\n\n=TITLE role Rational\n\n=SUBTITLE Number stored as numerator and denominator\n\n    role Rational[::NuT, ::DeT] does Real { ... }\n\nC<Rational> is the common role for numbers that are stored as pairs of numerator\nand denominator. It is parameterized by the types of the numerator (C<NuT>) and\ndenominator (C<DeT>). By default, these are L<C<Int>|/type/Int>, but other types of\nC<Rational> are possible by using a different parameterization.  In addition,\nC<Rational> objects are immutable throughout their life.\n\n\n    class Positive does Rational[UInt] {};\n    my Positive $one-third = Positive.new(1,3);\n    say $one-third;                         # OUTPUT: «0.333333␤»\n    my Positive $fail =Positive.new(-2,3);  # OUTPUT: «Type check failed in binding to parameter 'nu'; expected UInt but got Int (-2)␤»\n\nPlease note that, since C<DeT> is by default equal to C<NuT>, in this case both\nare instantiated to L<C<UInt>|/type/UInt>. Built into Raku are L<C<Rat>|/type/Rat> and L<C<FatRat>|/type/FatRat>, which\nboth do the C<Rational> role.\n\n=head1 Methods\n\n=head2 method new\n\n    =begin code :preamble<subset NuT of Int; subset DeT of Int>\n    method new(NuT:D $numerator, DeT:D $denominator --> Rational:D)\n    =end code\n\nCreates a new rational object from numerator and denominator, which it\nnormalizes to the lowest terms. The C<$denominator> can be zero, in which\ncase the numerator is normalized to C<-1>, C<0>, or C<1> depending on whether\nthe original is negative, zero, or positive, respectively.\n\n=head2 method Bool\n\n    multi method Bool(Rational:D: --> Bool:D)\n\nReturns C<False> if L<numerator|/routine/numerator> is C<0>, otherwise returns C<True>. This\napplies for C«<0/0>» zero-denominator <C<Rational> as well, despite C«?<0/0>.Num»\nbeing C<True>.\n\n=head2 method Bridge\n\n    method Bridge()\n\nReturns the number, converted to L<C<Num>|/type/Num>.\n\n=head2 method Int\n\n    method Int(Rational:D: --> Int:D)\n\nCoerces the invocant to L<C<Int>|/type/Int> by truncating non-whole portion of the represented\nnumber, if any. If the L<denominator|/routine/denominator> is zero, will L<fail|/routine/fail> with\nL<C<X::Numeric::DivideByZero>|/type/X::Numeric::DivideByZero>.\n\n=head2 method Num\n\n    method Num(Rational:D: --> Num:D)\n\nCoerces the invocant to L<C<Num>|/type/Num> by dividing L<numerator|/routine/numerator> by L<denominator|/routine/denominator>.\nIf L<denominator|/routine/denominator> is C<0>, returns C<Inf>, C<-Inf>, or C<NaN>, based on\nwhether L<numerator|/routine/numerator> is a positive number, negative number, or C<0>,\nrespectively.\n\n=head2 method ceiling\n\n    method ceiling(Rational:D: --> Int:D)\n\nReturn the smallest integer not less than the invocant. If L<denominator|/routine/denominator>\nis zero, L<fails|/routine/fail> with L<C<X::Numeric::DivideByZero>|/type/X::Numeric::DivideByZero>.\n\n=head2 method floor\n\n    method floor(Rational:D: --> Int:D)\n\nReturn the largest integer not greater than the invocant. If L<denominator|/routine/denominator>\nis zero, L<fails|/routine/fail> with L<C<X::Numeric::DivideByZero>|/type/X::Numeric::DivideByZero>.\n\n=head2 method isNaN\n\n    method isNaN(Rational:D: --> Bool:D)\n\nTests whether the invocant's Num value is a NaN, an acronym for I<Not available\nNumber>. That is both its numerator and denominator are zero.\n\n=head2 method numerator\n\n    =begin code :preamble<subset NuT of Int; subset DeT of Int>\n    method numerator(Rational:D: --> NuT:D)\n    =end code\n\nReturns the numerator.\n\n=head2 method denominator\n\n    =begin code :preamble<subset NuT of Int; subset DeT of Int>\n    method denominator(Rational:D: --> DeT:D)\n    =end code\n\nReturns the denominator.\n\n=head2 method nude\n\n    method nude(Rational:D: --> Positional)\n\nReturns a list of the numerator and denominator.\n\n=head2 method norm\n\n    method norm(Rational:D: --> Rational:D)\n\nB<DEPRECATED as of 6.d>. The method is no longer needed, because as of 6.d\nlanguage version, it's required for C<Rational> type to be normalized on\ncreation.\n\nReturns a normalized Rational object, i.e. with positive denominator, and\nnumerator and denominator coprime. The denominator can also be zero, but using\nit in any operation or a conversion to string will result in an exception.\n\n=for code :solo\nuse v6.c;\nmy Rational $by-zero = 3/0;\nsay $by-zero.norm.raku; # OUTPUT: «<1/0>␤»\n\n=for code :skip-test<Illustrates exception>\nsay $by-zero; # OUTPUT: «Attempt to divide by zero when coercing Rational to Str␤\n\n=head2 method base-repeating\n\n    method base-repeating(Rational:D: Int:D() $base = 10)\n\nReturns a list of two strings that, when concatenated, represent the number in\nbase C<$base>. The second element is the one that repeats. For example:\n\n    my ($non-rep, $repeating) = (19/3).base-repeating(10);\n    say $non-rep;                               # OUTPUT: «6.␤»\n    say $repeating;                             # OUTPUT: «3␤»\n    printf '%s(%s)', $non-rep, $repeating;      # OUTPUT: «6.(3)»\n\n19/3 is 6.333333... with the 3 repeating indefinitely.\n\nIf no repetition occurs, the second string is empty:\n\n    say (5/2).base-repeating(10).raku;          # OUTPUT: «(\"2.5\", \"\")␤»\n\nThe precision for determining the repeating group is limited to 1000\ncharacters, above that, the second string is C<???>.\n\nC<$base> defaults to C<10>.\n\n=head2 method Range\n\nReturns a L<Range object|/type/Range> that represents the range of values supported.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Real.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"basic\")\n\n=TITLE role Real\n\n=SUBTITLE Non-complex number\n\n    role Real does Numeric { ... }\n\nCommon role for non-L<C<Complex>|/type/Complex> numbers.\n\n=head1 Methods\n\n=head2 method Bridge\n\n    method Bridge(Real:D:)\n\nDefault implementation coerces the invocant to L<C<Num>|/type/Num> and that's the behavior\nof this method in core C<Real> types. This method primarily exist to make it\neasy to implement custom C<Real> types by users, with the C<Bridge> method\nreturning I<one of> the core C<Real> types (I<NOT> necessarily a L<C<Num>|/type/Num>)\nthat best represent the custom C<Real> type. In turn, this lets all the\ncore operators and methods obtain a usable value they can work with.\n\nAs an example, we can implement a custom C<Temperature> type. It has a unit of\nmeasure and the value, which are given during instantiation. We can implement\ncustom operators or conversion methods that work with this type. When it comes\nto regular mathematical operators, however, we can simply use the C<.Bridge>\nmethod to convert the C<Temperature> to Kelvin expressed in one of the core\nnumeric types:\n\n    class Temperature is Real {\n        has Str:D  $.unit  is required where any <K F C>;\n        has Real:D $.value is required;\n        method new ($value, :$unit = 'K') { self.bless :$value :$unit }\n        # Note: implementing .new() that handles $value of type Temperature is left as an exercise\n\n        method Bridge {\n            when $!unit eq 'F' { ($!value + 459.67) × 5/9 }\n            when $!unit eq 'C' {  $!value + 273.15 }\n            $!value\n        }\n        method gist { self.Str }\n        method Str  { \"$!value degrees $!unit\" }\n    }\n\n    sub postfix:<℃> { Temperature.new: $^value, :unit<C> }\n    sub postfix:<℉> { Temperature.new: $^value, :unit<F> }\n    sub postfix:<K> { Temperature.new: $^value, :unit<K> }\n\n    my $human := 36.6℃;\n    my $book  := 451℉;\n    my $sun   := 5778K;\n    say $human;                # OUTPUT: «36.6 degrees C␤»\n    say $human + $book + $sun; # OUTPUT: «6593.677777777778␤»\n    say 123K + 456K;           # OUTPUT: «579␤»\n\nAs we can see from the last two lines of the output, the type of the bridged\nresult is not forced to be any I<particular> core type. It is a L<C<Rat>|/type/Rat>, when we\ninstantiated C<Temperature> with a L<C<Rat>|/type/Rat> or when conversion was involved, and\nit is an L<C<Int>|/type/Int> when we instantiated C<Temperature> with an L<C<Int>|/type/Int>.\n\n=head2 method Complex\n\n    method Complex(Real:D: --> Complex:D)\n\nConverts the number to a L<C<Complex>|/type/Complex> with the number converted to a L<C<Num>|/type/Num> as\nits real part and 0e0 as the imaginary part.\n\n=head2 method Int\n\n    method Int(Real:D:)\n\nCalls the L«C<Bridge> method|/routine/Bridge» on the invocant and then\nthe L«C<Int> method|/routine/Int» on its return value.\n\n=head2 method Rat\n\n    method Rat(Real:D: Real $epsilon = 1e-6)\n\nCalls the L«C<Bridge> method|/routine/Bridge» on the invocant and then\nthe L«C<Rat> method|/routine/Rat» on its return value with the\nC<$epsilon> argument.\n\n=head2 method Real\n\n    multi method Real(Real:D: --> Real:D)\n    multi method Real(Real:U: --> Real:D)\n\nThe C<:D> variant simply returns the invocant. The C<:U> variant issues a\nwarning about using an uninitialized value in numeric context and then returns\nC<self.new>.\n\n=head2 method Str\n\n    multi method Str(Real:D:)\n\nCalls the L«C<Bridge> method|/routine/Bridge» on the invocant and then\nthe L«C<Str> method|/routine/Str» on its return value.\n\n=head2 method Num\n\n    method Num(Real:D:)\n\nCalls the L«C<Bridge> method|/routine/Bridge» on the invocant and then\nthe L«C<Num> method|/routine/Num» on its return value.\n\n=head2 routine rand\n\n    sub term:<rand> (--> Num:D)\n    method rand(Real:D: --> Real:D)\n\nReturns a pseudo-random number between zero (inclusive) and the number\n(non-inclusive). The L«C<Bridge> method|/routine/Bridge» is used to coerce the\nC<Real> to a numeric that supports L<rand|/routine/rand> method.\n\nThe term form returns a pseudo-random L<C<Num>|/type/Num> between 0e0 (inclusive) and 1e0\n(non-inclusive.)\n\n=head2 method sign\n\n    method sign(Real:D:)\n\nReturns C<-1> if the number is negative, C<0> if it is zero and C<1>\notherwise.\n\n=head2 method round\n\n    method round(Real:D: $scale = 1)\n\nRounds the number to scale C<$scale>. If C<$scale> is 1, rounds to an\ninteger. If scale is C<0.1>, rounds to one digit after the radix point (period or comma), etc.\n\n=head2 method floor\n\n    method floor(Real:D: --> Int:D)\n\nReturn the largest integer not greater than the number.\n\n=head2 method ceiling\n\n    method ceiling(Real:D: --> Int:D)\n\nReturns the smallest integer not less than the number.\n\n=head2 method truncate\n\n    method truncate(Real:D: --> Int:D)\n\nRounds the number towards zero.\n\n=head2 method polymod\n\n    method polymod(Real:D: +@mods)\n\nReturns the remainders after applying sequentially all divisors in the C<@mods>\nargument; the last element of the array will be the last remainder.\n\n    say (1e8+1).polymod(10 xx 8);  # OUTPUT: «(1 0 0 0 0 0 0 0 1)␤»\n\nC<10 xx 8> is simply an array with eight number 10s; the first division by 10\nwill return C<1> as a remainder, while the rest, up to the last, will return 0.\nWith 8 divisors, as above, the result will have one more elements, in this case\nfor the last remainder.\n\n    say ⅔.polymod(⅓);                            # OUTPUT: «(0 2)␤»\n    say 5.Rat.polymod(.3, .2);                   # OUTPUT: «(0.2 0 80)␤»\n\n=head2 method base\n\n    method base(Real:D: Int:D $base where 2..36, $digits? --> Str:D)\n\nConverts the number to a string, using C<$base> as base. For C<$base> larger\nthan ten, capital Latin letters are used.\n\n    255.base(16);            # 'FF'\n\nThe optional C<$digits> argument asks for that many digits of fraction (which\nmay not be negative). If omitted, a reasonable default is chosen based on type.\nFor Int this default is 0. For L<C<Num>|/type/Num>, the default is 8. For\nL<C<Rational>|/type/Rational>, the number of places is scaled to the size of the\ndenominator, with a minimum of 6.\n\nA special value of L«C<Whatever>|/type/Whatever» (C<*>) can be given as\nC<$digits>, which functions the same as when C<$digits> is not specified for all\nC<Real> types except the L<C<Rational>|/type/Rational>s. For L<C<Rational>|/type/Rational>s, the L<C<Whatever>|/type/Whatever>\nindicates that you wish all of the possible digits of the fractional part, but\nuse caution: since there's no detection of repeating fractional parts (the\nalgorithm will eventually stop after generating 2**63 digits).\n\nThe final digit produced is always rounded.\n\n    say pi.base(10, 3);      # OUTPUT: «3.142␤»\n    say (1/128).base(10, *); # OUTPUT: «0.0078125␤»\n    say (1/100).base(10, *); # OUTPUT: «0.01␤»\n    say (1/3)  .base(10, *); # WRONG: endlessly repeating fractional part\n\nFor reverse operation, see L«C<parse-base>|/routine/parse-base»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Regex.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Regex\n\n=SUBTITLE String pattern\n\n    class Regex is Method { }\n\nA regex is a kind of pattern that describes a set of strings. The process of\nfinding out whether a given string is in the set is called I<matching>. The\nresult of such a matching is a L<C<Match>|/type/Match> object, which evaluates to C<True> in\nBoolean context if the string is in the set.\n\nA regex is typically constructed by a regex literal\n\n    rx/ ^ab /;      # describes all strings starting with 'ab'\n    / ^ ab /;       # same\n    rx/ \\d ** 2/;   # describes all strings containing at least two digits\n\nX<|Language,named regex> A named regex can be defined with the C<regex> declarator\nfollowed by its definition in curly braces. Since any regex does L<C<Callable>|/type/Callable>\nintrospection requires referencing via C<&>-sigil.\n\n    my regex R { \\N };\n    say &R.^name; # OUTPUT: «Regex␤»\n\nTo match a string against a regex, you can use the smartmatch operator:\n\n    my $match = 'abc' ~~ rx/ ^ab /;\n    say $match.Bool;                # OUTPUT: «True␤»\n    say $match.orig;                # OUTPUT: «abc␤»\n    say $match.Str;                 # OUTPUT: «ab␤»\n    say $match.from;                # OUTPUT: «0␤»\n    say $match.to;                  # OUTPUT: «2␤»\n\nOr you can evaluate the regex in Boolean context, in which case it matches\nagainst the C<$_> variable\n\n    $_ = 'abc';\n    if / ^ab / {\n        say '\"abc\" begins with \"ab\"';\n    }\n    else {\n        say 'This is a weird alternative Universe';\n    }\n\n=head1 Methods\n\n=head2 method ACCEPTS\n\n    multi method ACCEPTS(Regex:D: Mu --> Match:D)\n    multi method ACCEPTS(Regex:D: @)\n    multi method ACCEPTS(Regex:D: %)\n\nMatches the regex against the argument passed in. If the argument is\nL<C<Positional>|/type/Positional>, it returns the first successful match of any list item. If the\nargument is L<C<Associative>|/type/Associative>, it returns the first successful match of any key.\nOtherwise it interprets the argument as a L<C<Str>|/type/Str> and matches against it.\n\nIn the case of Positional and Associative matches, L<C<Nil>|/type/Nil> is returned on\nfailure.\n\n=head2 method Bool\n\n    multi method Bool(Regex:D: --> Bool:D)\n\nMatches against the caller's L<$_|/syntax/$_> variable, and returns C<True> for a match or\nC<False> for no match.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Routine/WrapHandle.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Routine::WrapHandle\n\n=SUBTITLE Holds all information needed to unwrap a wrapped routine.\n\nclass WrapHandle { ... }\n\nC<WrapHandle> is a I<Rakudo private class> created and returned by\nL<wrap|/type/Routine#method_wrap>. Its only use is to unwrap wrapped routines.\nEither call L<unwrap|/type/Routine#method_unwrap> on a routine object or call\nthe method C<restore> on a C<Routine::WrapHandle> object.\n\n    sub f() { say 'f was called' }\n    my $wrap-handle = &f.wrap({ say 'before'; callsame; say 'after' });\n    f;                    # OUTPUT: «before␤f was called␤after␤»\n    $wrap-handle.restore;\n    f;                    # OUTPUT: «f was called␤»\n\nAs such private class, it may suffer any kind of changes without prior notice.\nIt is only mentioned here since it is visible by the user who checks the return\ntype of the C<Routine.wrap> method.\n\n=head1 Methods\n\n=head2 method restore\n\n    method restore(--> Bool:D)\n\nUnwraps a wrapped routine and returns C<Bool::True> on success.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Routine.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Routine\n\n=SUBTITLE Code object with its own lexical scope and C<return> handling\n\n    class Routine is Block { }\n\nA C<Routine> is a code object meant for units of code larger than\nL<C<Block>|/type/Block>. Routine is the common superclass for L<C<Sub>|/type/Sub> (and\ntherefore operators) and L<C<Method>|/type/Method>, the two primary code objects\nfor code reuse, as well as L<C<Macro>|/type/Macro> and\nL<C<Submethod>|/type/Submethod>.\n\nRoutines serve as a scope limiter for C<return> (i.e. a C<return> returns\nfrom the innermost outer Routine).\n\nThe routine level is also the one at which\nL<multiness|/language/glossary#Multi-dispatch> (multi subs and multi methods)\nare handled. Subroutines can also be declared C<anon>. See the L<documentation\non the C<anon> declarator|/language/variables#The_anon_declarator> for more\ninformation.\n\nRoutines are the lowest objects in the L<C<Code>|/type/Code> hierarchy that can introspect\nthrough the\nL<C<&?ROUTINE> variable|/language/variables#%26%3FROUTINE>, which\nis defined automatically, and contains the corresponding C<Routine> object.\n\n=for code\nclass Foo {\n    submethod bar { &?ROUTINE.^name }\n};\nsay Foo.bar; # OUTPUT: «Submethod␤»\n\n\n=head1 Methods\n\n=head2 method name\n\n    method name(Routine:D: --> Str:D)\n\nReturns the name of the sub or method.\n\n=head2 method package\n\n    method package(Routine:D:)\n\nReturns the package in which the routine is defined.\n\n=head2 method multi\n\n    method multi(Routine:D: --> Bool:D)\n\nReturns C<True> if the routine is a multi sub or method. Note that the name of a\nmulti sub refers to its L<C<proto>|/syntax/proto> and this method would return\nfalse if called on it. It needs to be called on the candidates themselves:\n\n    multi foo ($, $) {};\n    say &foo.multi;             # OUTPUT: «False␤»\n    say &foo.candidates».multi; # OUTPUT: «(True)␤»\n\n=head2 method candidates\n\n    method candidates(Routine:D: --> Positional:D)\n\nReturns a list of multi candidates, or a one-element list with itself\nif it's not a multi\n\n=head2 method cando\n\n    method cando(Capture $c)\n\nReturns a possibly-empty list of candidates that can be called with the\ngiven L<C<Capture>|/type/Capture>, ordered by narrowest candidate first. For\nmethods, the first element of the Capture needs to be the invocant:\n\n    .signature.say for \"foo\".^can(\"comb\")[0].cando: \\(Cool, \"o\");\n    # OUTPUT: «(Cool $: Str $matcher, $limit = Inf, *%_)␤»\n\n=head2 method wrap\n\n    method wrap(Routine:D: &wrapper)\n\nWraps (i.e. in-place modifies) the routine. That means a call to this routine\nfirst calls C<&wrapper>, which then can (but doesn't have to) call the\noriginal routine with the C<callsame>, C<callwith>, C<nextsame> and\nC<nextwith> L<dispatchers|/language/functions#Re-dispatching>.\nThe return value from the routine is also the return value from the wrapper.\n\nC<wrap> returns an instance of a private class called\nL<C<Routine::WrapHandle>|/type/Routine::WrapHandle>,\nwhich you can pass to L<unwrap|/routine/unwrap> to restore the original routine.\n\n=head2 method unwrap\n\n    method unwrap($wraphandle)\n\nRestores the original routine after it has been wrapped with\nL<wrap|/routine/wrap>. While the signature allows any type to be passed, only\nthe L<C<Routine::WrapHandle>|/type/Routine::WrapHandle> type returned from\nC<wrap> can usefully be.\n\n=head2 method is-wrapped\n\n    method is-wrapped()\n\nReturns C<True> or C<False>, depending on the whether or not the C<Routine> is wrapped.\n\n=head2 method yada\n\n    method yada(Routine:D: --> Bool:D)\n\nReturns C<True> if the routine is a stub\n\n    say (sub f() { ... }).yada;      # OUTPUT: «True␤»\n    say (sub g() { 1;  }).yada;      # OUTPUT: «False␤»\n\n=head2 trait is cached\n\n    multi trait_mod:<is>(Routine $r, :$cached!)\n\nCauses the return value of a routine to be stored, so that when subsequent calls\nwith the same list of arguments are made, the stored value can be returned\nimmediately instead of re-running the routine.N<This is still in experimental\nstage. Please check\nL<the corresponding section in the experimental features document|/language/experimental#cached>>\n\nUseful when storing and returning the computed value is much faster than\nre-computing it every time, and when the time saved trumps the cost of the\nuse of more memory.\n\nEven if the arguments passed to the routine are \"reference types\" (such as\nobjects or arrays), then for the purpose of caching they will only be compared\nbased on their contents. Thus the second invocation will hit the cache in this\ncase:\n\n=for code :skip-test<compile time error>\nsay foo( [1, 2, 3] );   # runs foo\nsay foo( [1, 2, 3] );   # doesn't run foo, uses cached value\n\nSince it's still at the experimental stage, you will have to insert the C<use\nexperimental :cached;> statement in any module or script that uses it.\n\n=begin code\nuse experimental :cached;\n\nsub nth-prime(Int:D $x where * > 0) is cached {\n    say \"Calculating {$x}th prime\";\n    return (2..*).grep(*.is-prime)[$x - 1];\n}\n\nsay nth-prime(43);\nsay nth-prime(43);\nsay nth-prime(43);\n=end code\n\nproduces this output:\n\n=begin code :lang<text>\nCalculating 43th prime\n191\n191\n191\n=end code\n\nB<Note>: This feature is not thread-safe.\n\n=head2 trait is pure\n\n    multi trait_mod:<is>(Routine $r, :$pure!)\n\nMarks a subroutine as I<pure>, that is, it asserts that for the same input, it\nwill always produce the same output without any additional side effects.\n\nThe C<is pure> trait is a promise by the programmer to the compiler that it can\nconstant-fold calls to such functions when the arguments are known at compile\ntime.\n\n    sub syllables() is pure {\n        say \"Generating syllables\";\n        my @vowels = <a e i o u>;\n        return  @vowels.append: <k m n sh d r t y> X~ @vowels;\n    }\n\nYou can mark function as pure even if they throw exceptions in edge cases\nor if they modify temporary objects; hence the C<is pure> trait can cover\ncases that the compiler cannot deduce on its own. On the other hand, you might\nnot want to constant-fold functions that produce a large return value (such\nas the string or list repetition operators, infix C<x> and C<xx>) even if they\nare pure, to avoid large precompilation files.\n\nTo see it an action with a particular compiler you can try this example:\n\n    =begin code :preamble<sub syllables {}>\n    BEGIN { say ‘Begin’ }\n    say ‘Start’;\n    say (^100).map: { syllables().pick(4).join(\"\") };\n\n\n    # Example output:\n    # Begin\n    # Generating syllables\n    # Start\n    # (matiroi yeterani shoriyuru...\n    =end code\n\n\nEssentially this allows the compiler to perform some operations at\ncompile time. The benefits of constant-folding I<may> include better\nperformance, especially in cases when the folded code is precompiled.\n\nIn addition, using a pure function or operator in sink context (that is,\nwhere the result is discarded) may lead to a warning. The code\n\n    sub double($x) is pure { 2 * $x };\n    double(21);\n    say \"anything\";\n    # WARNING: «Useless use of \"double(21)\" in expression \"double(21)\" in sink context (line 2)»\n\nIf you want to apply this trait to a C<multi>, you need to apply it to the\nC<proto>; it will not work otherwise, at least in versions 2018.08 and below.\n\n=head2 trait is rw\n\n    multi trait_mod:<is>(Routine $r, :$rw!)\n\nWhen a routine is modified with this trait, its return value will be writable.\nThis is useful when returning variables or writable elements of hashes or\narrays, for example:\n\n=begin code\nsub walk(\\thing, *@keys) is rw {\n    my $current := thing;\n    for @keys -> $k {\n        if $k ~~ Int {\n            $current := $current[$k];\n        }\n        else {\n            $current := $current{$k};\n        }\n    }\n    $current;\n}\n\nmy %hash;\nwalk(%hash, 'some', 'key', 1, 2) = 'autovivified';\n\nsay %hash<some><key>[1][2];\n=end code\n\nproduces\n\n=begin code :lang<output>\nautovivified\n=end code\n\nNote that C<return> marks return values as read only; if you need an early exit\nfrom an C<is rw> routine, you have to use X<C<return-rw>|Reference,return-rw> instead.\n\n=head2 trait is export\n\n    multi trait_mod:<is>(Routine $r, :$export!)\n\nMarks a routine as exported to the rest of the world\n\n=begin code\nmodule Foo {\n    sub double($x) is export {\n        2 * $x\n    }\n}\n\nimport Foo;         # makes sub double available\nsay double 21;      # 42\n=end code\n\nFrom inside another file you'd say C<use Foo;> to load a module and import the\nexported functions.\n\nSee L<Exporting and Selective Importing Modules|/language/using-modules/code#Exporting_and_selective_importing>\nfor more details.\n\n=head2 trait is DEPRECATED\n\n    multi trait_mod:<is>(Routine:D $r, :$DEPRECATED!)\n\nMarks a C<Routine> as deprecated; that is, it should no longer be used going forward,\nand will eventually be removed. An optional message specifying the replacement\nfunctionality can be specified\n\nBy having both the original (deprecated) and new C<Routine> available simultaneously,\nyou can avoid a breaking change in a single release, by allowing users time and instructions\non how to update their code. Remove the deprecated version only after at least\none release that includes both the warning and the new C<Routine>.\n\nThis code\n\n=begin code\nsub f() is DEPRECATED('the literal 42') { 42 }\nsay f();\n=end code\n\nproduces this output:\n\n=begin code :lang<text>\n42\nSaw 1 occurrence of deprecated code.\n================================================================================\nSub f (from GLOBAL) seen at:\n  deprecated.raku, line 2\nPlease use the literal 42 instead.\n--------------------------------------------------------------------------------\nPlease contact the author to have these occurrences of deprecated code\nadapted, so that this message will disappear!\n=end code\n\n=head2 trait is hidden-from-backtrace\n\n    multi trait_mod:<is>(Routine:D, :$hidden-from-backtrace!)\n\nHides a routine from showing up in a default backtrace. For example\n\n=begin code\nsub inner { die \"OH NOEZ\" };\nsub outer { inner() };\nouter();\n=end code\n\nproduces the error message and backtrace\n\n=begin code :lang<text>\nOH NOEZ\n  in sub inner at bt.raku:1\n  in sub outer at bt.raku:2\n  in block <unit> at bt.raku:3\n=end code\n\nbut if C<inner> is marked with C<hidden-from-backtrace>\n\n=begin code\nsub inner is hidden-from-backtrace { die \"OH NOEZ\" };\nsub outer { inner() };\nouter();\n=end code\n\nthe error backtrace does not show it:\n\n=begin code :lang<text>\nOH NOEZ\n  in sub outer at bt.raku:2\n  in block <unit> at bt.raku:3\n=end code\n\n=begin comment\n\nTODO: explain export tags\n\n=end comment\n\nX<|Traits,is default>\n=head2 trait is default\n\n    multi trait_mod:<is>(Routine:D $r, :$default!)\n\nThere is a special trait for C<Routine>s called C<is default>. This trait is\ndesigned as a way to disambiguate C<multi> calls that would normally throw an\nerror because the compiler would not know which one to use. This means that\ngiven the following two C<Routine>s, the one with the C<is default> trait will\nbe called.\n\n    multi f() is default { say \"Hello there\" }\n    multi f() { say \"Hello friend\" }\n    f();   # OUTPUT: «\"Hello there\"␤»\n\nThe C<is default> trait can become very useful for debugging and other uses but\nkeep in mind that it will only resolve an ambiguous dispatch between two\nC<Routine>s of the same precedence. If one of the C<Routine>s is narrower than\nanother, then that one will be called. For example:\n\n=begin code\nmulti f() is default { say \"Hello there\" }\nmulti f(:$greet) { say \"Hello \" ~ $greet }\nf();   # \"Use of uninitialized value $greet...\"\n=end code\n\nIn this example, the C<multi> without C<is default> was called because it was\nactually narrower than the L<C<Sub>|/type/Sub> with it.\n\n\n=head2 trait is raw\n\n    multi trait_mod:<is>(Routine:D $r, :$raw!)\n\nGives total access to the data structure returned by the routine.\n\n=for code\nmy @zipi = <zape zapatilla>;\nsub þor() is raw {\n    return @zipi\n};\nþor()[1] = 'pantuflo';\nsay @zipi;  # OUTPUT: «[zape pantuflo]␤»\n\n=head2 trait is test-assertion\n\n    multi trait_mod:<is>(Routine:D, :$test-assertion!)\n\nDeclares that a routine generates test output (aka TAP). When\nfailures are reported, the calling routine's location is used instead\nof this routine. For example:\n\n=begin code\nuse Test;\nsub foo-test($value) is test-assertion {\n    is $value, 42, \"is the value 42?\";\n}\nfoo-test(666);    # <-- error is reported on this line\n=end code\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Scalar.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Scalar\n\n=SUBTITLE A mostly transparent container used for indirections\n\n    class Scalar {}\n\nA C<Scalar> is an internal indirection, that is, a way to refer indirectly to a\nvalue, which is, for most purposes, invisible during ordinary use of Raku. It is\nthe default container type associated with the C<$> sigil. A literal C<Scalar>\nmay be placed around any literal by enclosing the value in C<$(…)>. This\nnotation will appear in the output of a C<.raku> method in certain places where\nit is important to note the presence of C<Scalar>s.\n\nWhen a value is assigned to a C<$>-sigiled variable, the variable will\nactually bind to a C<Scalar>, which in turn will bind to the value.\nWhen a C<Scalar> is assigned to a C<$>-sigiled variable, the value\nbound to by that C<Scalar> will be bound to the C<Scalar> which that\nvariable was bound to (a new one will be created if necessary.)\n\nIn addition, C<Scalar>s delegate all method calls to the value which they\ncontain. As such, C<Scalar>s are for the most part invisible. There is, however,\none important place where C<Scalar>s have a visible impact: a C<Scalar>\ncontainer will shield its content from\nL<flattening|/language/subscripts#index-entry-flattening_> by most Raku core list\noperations.\n\n=for code\nsay |(1,2,$(3,4));       # OUTPUT: «12(3 4)␤»\n\nThese C<Scalar> containers can also be created on the fly by assigning to an\nL<anonymous scalar variable|/language/variables#The_$_variable>:\n\n=for code\nsay |(1,2, $ = (3,4)); # OUTPUT: «12(3 4)␤»\n\nA C<$>-sigiled variable may be bound directly to a value with no\nintermediate C<Scalar> using the binding operator C<:=>. You can\ntell if this has been done by examining the output of the\nintrospective pseudo-method C<.VAR>:\n\n    my $a = 1;\n    $a.^name.say;     # OUTPUT: «Int␤»\n    $a.VAR.^name.say; # OUTPUT: «Scalar␤»\n    my $b := 1;\n    $b.^name.say;     # OUTPUT: «Int␤»\n    $b.VAR.^name.say; # OUTPUT: «Int␤»\n\nThis same thing happens when values are assigned to an element of\nan L<C<Array>|/type/Array>, however, L<C<List>|/type/List>s directly contain their values:\n\n    my @a = 1, 2, 3;\n    @a[0].^name.say;            # OUTPUT: «Int␤»\n    @a[0].VAR.^name.say;        # OUTPUT: «Scalar␤»\n    [1, 2, 3][0].^name.say;     # OUTPUT: «Int␤»\n    [1, 2, 3][0].VAR.^name.say; # OUTPUT: «Scalar␤»\n    (1, 2, 3)[0].^name.say;     # OUTPUT: «Int␤»\n    (1, 2, 3)[0].VAR.^name.say; # OUTPUT: «Int␤»\n\nArray elements may be bound directly to values using C<:=> as well; however,\nthis is discouraged as it may lead to confusion. Doing so will break exact\nround-tripping of C<.raku> output – since L<C<Array>|/type/Array>s are assumed to place\nC<Scalar>s around each element, C<Scalar>s are not denoted with C<$> in the\noutput of C<Array.raku>.\n\n    [1, $(2, 3)].raku.say;     # OUTPUT: «[1, (2, 3)]␤»\n    (1, $(2, 3)).raku.say;     # OUTPUT: «(1, $(2, 3))␤»\n\nBinding a C<Scalar> to a C<$>-sigiled variable replaces the existing\nC<Scalar> in that variable, if any, with the given C<Scalar>.\nThat means more than one variable may refer to the same C<Scalar>.\nBecause the C<Scalar> may be mutated, this makes it possible to\nalter the value of both variables by altering only one of them:\n\n    my $a = 1;\n    my $b := $a;\n    $b = 2;\n    $a.say;       # OUTPUT: «2␤»\n\nX<|Syntax,\\ (sigilless scalar)>\nRaku allows the use of constants with a\nL<static single assignment (SSA)|https://en.wikipedia.org/wiki/Static_single_assignment_form>\nstyle which bind directly to their value with no intervening C<Scalar>\ncontainer, even when assignment (C<=>) is used. They may be forced to use a\nC<Scalar> by assigning a C<$>-sigiled variable to them, at which point, they\nbehave entirely like C<$>-sigiled variables.\n\n    my \\c = 1;\n    c.^name.say;             # OUTPUT: «Int␤»\n    c.VAR.^name.say;         # OUTPUT: «Int␤»\n    my $a = 1;\n    my \\d = $a;              # just \"my \\d = $ = 1\" works, too\n    d.^name.say;             # OUTPUT: «Int␤»\n    d.VAR.^name.say;         # OUTPUT: «Scalar␤»\n    d = 2;                   # ok\n    c = 2;                   # fails\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Assignment::RO: Cannot modify an immutable Int␤»\n\n=head1 Atomic operations on Scalar\n\nA C<Scalar> can have its value changed using a hardware-supported atomic\ncompare and swap operation. This is useful when implementing lock free data\nstructures and algorithms. It may also be fetched and assigned to in an\n\"atomic\" fashion, which ensures appropriate memory barriering and prevents\nunwanted optimizations of memory accesses.\n\nA C<Scalar> that will be used with an atomic operation should B<always> be\nexplicitly initialized with a value before any atomic operations are\nperformed upon it. This is to avoid races with lazy allocation and\nauto-vivification. For example:\n\n=for code :preamble<no strict;>\ncas(@a[5], $expected, $value)\n\nWill work in principle since an L<C<Array>|/type/Array> consists of C<Scalar> containers.\nHowever, the container is only bound into the array upon initial assignment.\nTherefore, there would be a race to do that binding. The C<Scalar> atomic\noperations will never check for or do any such auto-vivification, so as to\nmake such bugs much more evident (rather than only observed under stress).\n\n=head1 Introspection\n\n=head2 method of\n\n    method of(Scalar:D: --> Mu)\n\nReturns the type constraint of the container.\n\nExample:\n\n    my Cool $x = 42;\n    say $x.VAR.of;                  # OUTPUT: «(Cool)␤»\n\n=head2 method default\n\n    method default(Scalar:D: --> Str)\n\nReturns the default value associated with the container.\n\nExample:\n\n    my $x is default(666) = 42;\n    say $x.VAR.default;             # OUTPUT: «666␤»\n\n=head2 method name\n\n    method name(Scalar:D: --> Str)\n\nReturns the name associated with the container.\n\nExample:\n\n    my $x = 42;\n    say $x.VAR.name;                # OUTPUT: «$x␤»\n\n=head2 method dynamic\n\n    method dynamic(Scalar:D: --> Bool)\n\nIt will return C<False> for scalars.\n\nExample:\n\n    my $*FOO = 42;\n    say $*FOO.VAR.dynamic;          # OUTPUT: «True␤»\n\nNote that you have to use the C<VAR> method in order to get that information.\n\n    my $s is dynamic = [1, 2, 3];\n    say $s.dynamic;                          # OUTPUT: «False␤»  (wrong, don't do this)\n    say $s.VAR.dynamic;                      # OUTPUT: «True␤»   (correct approach)\n\n=head1 Routines\n\n=head2 sub atomic-assign\n\n    multi atomic-assign($target is rw, $value)\n\nPerforms an atomic assignment of C<$value> into the C<Scalar> C<$target>. The\nC<atomic-assign> routine ensures that any required barriers are performed such\nthat the changed value will be \"published\" to other threads.\n\n=head2 sub atomic-fetch\n\n    multi atomic-fetch($target is rw)\n\nPerforms an atomic read of the value in the C<Scalar> C<$target> and returns\nthe read value. Using this routine instead of simply using the variable\nensures that the latest update to the variable from other threads will be seen,\nboth by doing any required hardware barriers and also preventing the compiler\nfrom lifting reads. For example:\n\n    my $started = False;\n    start { atomic-assign($started, True) }\n    until atomic-fetch($started) { }\n\nIs certain to terminate, while in:\n\n    my $started = False;\n    start { atomic-assign($started, True) }\n    until $started { }\n\nIt would be legal for a compiler to observe that C<$started> is not updated in\nthe loop, and so lift the read out of the loop, thus causing the program to\nnever terminate.\n\n=head2 sub cas\n\n    multi cas(Mu $target is rw, Mu \\expected, Mu \\value)\n    multi cas(Mu $target is rw, &operation)\n\nPerforms an atomic compare and swap of the value in the C<Scalar> C<$target>.\nThe first form has semantics like:\n\n=for code :preamble<no strict;>\nmy $seen = $target;\nif $seen<> =:= $expected<> {\n    $target = $value;\n}\nreturn $seen;\n\nExcept it is performed as a single hardware-supported atomic instruction, as\nif all memory access to C<$target> were blocked while it took place. Therefore\nit is safe to attempt the operation from multiple threads without any other\nsynchronization. Since it is a reference comparison, this operation is usually\nnot sensible on value types.\n\nFor example:\n\n    constant NOT_STARTED = Any.new;\n    constant STARTED = Any.new;\n    my $master = NOT_STARTED;\n    await start {\n        if cas($master, NOT_STARTED, STARTED) === NOT_STARTED {\n            say \"Master!\"\n        }\n    } xx 4\n\nWill reliably only ever print C<Master!> one time, as only one of the threads\nwill be successful in changing the C<Scalar> from C<NOT_STARTED> to\nC<STARTED>.\n\nThe second form, taking a code object, will first do an atomic fetch of the\ncurrent value and invoke the code object with it. It will then try to do an\natomic compare and swap of the target, using the value passed to the code\nobject as C<expected> and the result of the code object as C<value>. If\nthis fails, it will read the latest value, and retry, until a CAS operation\nsucceeds.\n\nTherefore, an item could be added to the head of a linked list in a lock free\nmanner as follows:\n\n    class Node {\n        has $.value;\n        has Node $.next;\n    }\n    my Node $head = Node;\n    await start {\n        for ^1000 -> $value {\n            cas $head, -> $next { Node.new(:$value, :$next) }\n        }\n    } xx 4;\n\nThis will reliably build up a linked list of 4000 items, with 4 nodes with\neach value ranging from 0 up to 999.\n\nB<Note>: Before Rakudo release 2020.12, C<$target>, C<expected> and\nC<value> had an L«C<Any>|/type/Any» type constraint.\n\n=head1 Operators\n\n=head2 infix ⚛=\n\n    multi infix:<⚛=>($target is rw, $value)\n\nPerforms an atomic assignment of C<$value> into the C<Scalar> C<$target>. The\nC<⚛=> operator ensures that any required barriers are performed such that the\nchanged value will be \"published\" to other threads.\n\n=head2 prefix ⚛\n\n    multi prefix:<⚛>($target is rw)\n\nPerforms an atomic read of the value in the C<Scalar> C<$target> and returns\nthe read value. Using this operator instead of simply using the variable\nensures that the latest update to the variable from other threads will be seen,\nboth by doing any required hardware barriers and also preventing the compiler\nfrom lifting reads. For example:\n\n    my $started = False;\n    start { $started ⚛= True }\n    until ⚛$started { }\n\nIs certain to terminate, while in:\n\n    my $started = False;\n    start { $started ⚛= True }\n    until $started { }\n\nIt would be legal for a compiler to observe that C<$started> is not updated in\nthe loop, and so lift the read out of the loop, thus causing the program to\nnever terminate.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Scheduler.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"domain-specific\")\n\n=TITLE role Scheduler\n\n=SUBTITLE Scheme for automatically assigning tasks to threads\n\n    role Scheduler {\n        has &.uncaught_handler is rw\n    }\n\nA scheduler is a piece of code that determines which resources to use to run\nwhich task, and when. This role contains code that will be the same for all\nkinds of schedulers.\n\nSome operations for example on L<C<Proc::Async>|/type/Proc::Async>,\nL<C<Promise>|/type/Promise>, L<C<Supply>|/type/Supply> allow you to specify a\nscheduler explicitly; they generally expect those schedulers to follow the\ninterface defined by C<Scheduler>.\n\n=head1 Methods\n\n=head2 method uncaught_handler\n\n    method uncaught_handler() is rw\n\nRW-Accessor for the handler that is caught for uncaught exceptions from the\ncode that is being scheduled and run.\n\n=head2 method cue\n\n    method cue(&code, Instant :$at, :$in, :$every, :$times = 1; :&catch --> Cancellation)\n\nSchedules a callable (C<&code>) for execution and returns an instantiated\nL<C<Cancellation>|/type/Cancellation> object to cancel the scheduling of the\ncode for execution (which is especially important if you specify the C<:every\n( time )> named parameter). The adverbs control when and how the code is run:\n\n=item C<$at> can be an L<C<Instant>|/type/Instant> before which the code won't be\nrun.\nAlternatively C<$in> is the number of seconds (possibly fractional) to wait\nbefore running the code. If C<$at> is in the past or C<$in> is negative,\nthe delay is treated as zero. Implementations may equate to zero\nvery small values (e.g. lower than 0.001s) of C<$in> or result of\nC<$at> - L<now|/routine/now>.\n\n=item If C<$every> is specified, it is interpreted as the number of seconds\n(possibly fractional) to wait before re-executing the code. Implementations\nmay treat too-small values as lowest resolution they support, possibly\nwarning in such situations; e.g. treating C<0.0001> as C<0.001>.\n\n=item C<$times> tells the scheduler how many times to run the code.\n\n=item C<&catch> is called with the L<C<Exception>|/type/Exception> as its sole\nargument\nif C<&code> dies.\n\n=item If C<$at> or C<$in> are C<Inf>, C<&code> will never be run; if\nC<$every> is\nC<Inf>, C<&code> will only be run once. If any of the three are C<-Inf>,\nC<&code> will be run immediately. If any of the three are C<NaN>, an\nL<C<X::Scheduler::CueInNaNSeconds>|/type/X::Scheduler::CueInNaNSeconds> exception\nwill be thrown. This only applies to releases 2019.05 and later.\n\nOne should call the C<cancel> method on the returned L<C<Cancellation>|/type/Cancellation> object\nto cancel the (possibly repeated) cueing of the code.\n\n=head2 method loads\n\n    method loads()\n\nThis is a method stub, should be re-implemented when subclassing.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Semaphore.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Semaphore\n\n=SUBTITLE Control access to shared resources by multiple threads\n\n  class Semaphore { }\n\nProtect your shared code, data or device access using semaphores. An example is\na printer manager managing a pool of printers without the need of storing print\njobs when all printers are occupied. The next job is just blocked until a\nprinter becomes available.\n\n  class print-manager {\n    has Array $!printers;\n    has Semaphore $!print-control;\n\n    method BUILD( Int:D :$nbr-printers ) {\n      for ^$nbr-printers -> $pc {\n        $!printers[$pc] = { :name{\"printer-$pc\"} };\n      }\n\n      $!print-control .= new($nbr-printers);\n    }\n\n    method find-available-printer-and-print-it($job) { say \"Is printed!\"; }\n\n    method print( $print-job ) {\n      $!print-control.acquire;\n\n      self.find-available-printer-and-print-it($print-job);\n\n      $!print-control.release;\n    }\n  }\n\nAnother example is a protection around code updating sensitive data. In such a\ncase the semaphore is typically initialized to 1.\n\nIt is important to have a release on every exit of your program! While this is\nobvious, it is easy to fall in traps such as throwing an exception caused by some\nevent. When the program dies there is no problem. When the exception is caught\nyour program might eventually come back to the acquire method and will hang\nindefinitely.\n\n=head1 Methods\n\n=head2 method new\n\n  method new( int $permits )\n\nInitialize the semaphore with the number of permitted accesses. E.g. when set to\n2, program threads can pass the acquire method twice until it blocks on the\nthird time acquire is called.\n\n=head2 method acquire\n\n  method acquire()\n\nAcquire access. When other threads have called the method before and the\nnumber of permits are used up, the process blocks until threads passed before\nreleases the semaphore.\n\n=head2 method try_acquire\n\n  method try_acquire(--> Bool)\n\nSame as acquire but will not block. Instead it returns C<True> if access is\npermitted or C<False> otherwise.\n\n=head2 method release\n\n  method release()\n\nRelease the semaphore raising the number of permissions. Any blocked thread will\nget access after that.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Seq.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class Seq\n\n=SUBTITLE An iterable, potentially lazy sequence of values\n\n    class Seq is Cool does Iterable does Sequence { }\n\nA C<Seq> represents anything that can produce a sequence of values. A\nC<Seq> is born in a state where iterating it will consume the values.\nCalling C<.cache> on a C<Seq> will make it store the generated values\nfor later access.\n\nA high-level construct to generate a C<Seq> is L«C<gather/take>|/syntax/gather%20take»,\nas well as many built-in methods like L«C<map>|/routine/map» and\nL«C<grep>|/routine/grep», low-level constructors to create a\nC<Seq> from an iterator or from looping constructs are available too.\n\nA C<Seq> can also be constructed with the\nL«sequence operator C<...>|/language/operators#infix_...» or one of its\nvariants.\n\n    my $s = (1...5);\n    say $s;              # OUTPUT: «(1 2 3 4 5)␤»\n    say $s.^name;        # OUTPUT: «Seq␤»\n\nAssigning the values of a C<Seq> to an array consumes a C<Seq> that is\nnot lazy. Use the C<lazy> statement prefix to avoid a C<Seq> from being\niterated during the assignment:\n\n=begin code\n# The Seq created by gather ... take is consumed on the spot here.\nmy @a = gather do { say 'consuming...'; take 'one' };  # OUTPUT: «consuming...␤»\n\n# The Seq here is only consumed as we iterate over @a later.\nmy @a = lazy gather do { say 'consuming...'; take 'one' };  # outputs nothing.\n.say for @a;  # OUTPUT: «consuming...␤one␤»\n=end code\n\nA typical use case is L<method C<lines> in C<IO::Handle>|/type/IO::Handle#routine_lines>,\nwhich could use a lot of memory if it stored all the lines read from the\nfile. So\n\n=begin code\nfor open('README.md').lines -> $line {\n    say $line;\n}\n=end code\n\nwon't keep all lines from the file in memory.\n\nThis implies that you cannot iterate the same C<Seq> object twice (otherwise\nit couldn't throw away old values), so this dies:\n\n    my @a = 1, 2, 3;\n    my @b = <a b c>;\n    my \\c = @a Z=> @b;\n    .say for c;\n    .say for c; # fails\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Seq::Consumed: This Seq has already been iterated, and its values consumed\n    # (you might solve this by adding .cache on usages of the Seq, or\n    # by assigning the Seq into an array)»\n\n\nB<Caution:> No program should ever assume a C<Seq> may only be iterated once\neven if not cached by the program. Caching is a volatile state exposed to the\ndeveloper as an optimization. The C<Seq> may become cached by many operations,\nincluding calling C<.raku> (C<.perl> before release 2019.11) on the C<Seq> (if\ncalled prior to a non-cached iteration). From version 6.d, C<.raku> (again,\nC<.perl> before release 2019.11) can be called on consumed C<Seq>. If a program\nassumes a C<Seq> can only iterate once, but then is later changed to call one of\nthese operations during the loop, that assumption will fail.\n\nOn a cached C<Seq>, the cached list is used when C<&infix:<eqv>>, C<.Slip>,\nC<.join>, C<.List>, C<.list>, C<.eager>, C<.Array> and C<.is-lazy> are called.\n\nYou can smartmatch a regex with C<Seq>, even if it's infinite\n\n    my @fib = 1,1, *+* ... *;\n    say @fib[^1000] ~~ /^9999/; # OUTPUT: «Nil␤»\n\nHowever, infinite or lazy C<Seq> will be vivified when doing the match,\nleading to possibly infinite loops, so be sure to limit search somehow.\n\n=head1 Methods\n\n=head2 method new\n\n=for code\nproto method new(Seq: |) {*}\nmulti method new(Seq: Iterator:D $iter)\nmulti method new(Seq:)\n\nCreates a new C<Seq> object from the supplied iterator passed as the single\nargument. Creates an empty C<Seq> if called with no argument.\n\n=head2 method iterator\n\n    method iterator(Seq:D:)\n\nIf the C<Seq> is not cached, returns the underlying iterator and marks\nthe invocant as consumed. If called on an already consumed sequence,\nthrows an error of type L<C<X::Seq::Consumed>|/type/X::Seq::Consumed>.\n\nOtherwise returns an iterator over the cached list.\n\n=head2 method is-lazy\n\n    method is-lazy(Seq:D:)\n\nReturns C<True> if and only if the underlying iterator or cached list\nconsiders itself lazy. If called on an already consumed sequence, throws\nan error of type L<C<X::Seq::Consumed>|/type/X::Seq::Consumed>.\n\n=head2 method Seq\n\n     multi method Seq(Seq:D:)\n\nClones the object.\n\n\n=head2 method Capture\n\n     method Capture()\n\nCoerces the object to a L<C<List>|/type/List>, which is in turn coerced into a L<C<Capture>|/type/Capture>.\n\n=head2 method elems\n\n    method elems(Seq:D:)\n\nReturns the number of values in the sequence. If this number cannot be\npredicted, the C<Seq> is cached and evaluated till the end.\n\nBecause an infinite sequence cannot be evaluated till the end, such a\nsequence I<should> be declared lazy. Calling C<.elems> on a lazy C<Seq>\nL<fail|/routine/fail>s with L<C<X::Cannot::Lazy>|/type/X::Cannot::Lazy>.\n\n=head2 method from-loop\n\n    multi method from-loop(&body, :$label)\n    multi method from-loop(&body, &cond, :$repeat!, :$label)\n    multi method from-loop(&body, &cond, :$label)\n    multi method from-loop(&body, &cond, &afterwards, :$label)\n\nThese methods create new C<Seq>-based callbacks.\n\nIn general, it produces an infinite C<Seq> by calling C<&body> each time a new\nelement is requested, using the return value from C<&body> as the item. This\nemulates (or implements) a C<loop { body }> construct.\n\nWhen the multi includes C<&cond>, it's invoked before each call to\nC<&body>, and terminates\nthe sequence if C<&cond> returns a false value. If C<$repeat> is set to a true\nvalue, the first call to C<&cond> is omitted, and C<&body> called right away.\nThis emulates (or implements) C<while cond { body }> and\nC<repeat { body } while cond> loops.\n\nIf present, C<&afterward> will be called after each call to C<&body>.\n\n=head2 method sink\n\n    method sink(--> Nil)\n\nCalls L<C<sink-all>|/routine/sink-all> if it is an L<C<Iterator>|/type/Iterator>, C<sink> if the Sequence is a list.\n\n    say (1 ... 1000).sink; # OUTPUT: «Nil␤»\n\nThis is something you might want to do for the side effects of producing those values.\n\n=head2 method skip\n\n    multi method skip(Seq:D:)\n    multi method skip(Seq:D: Whatever)\n    multi method skip(Seq:D: Callable:D $w)\n    multi method skip(Seq:D: Int() $n)\n    multi method skip(Seq:D: $skip, $produce)\n\nReturns a Seq containing whatever is left of the invocant after\nthrowing away C<$n> of the next available values. Negative values of\nC<$n> count as 0.  Also can take a L<C<WhateverCode>|/type/WhateverCode> to indicate how many values\nto skip from the end.  Will block on lazy Seqs until the requested\nnumber of values have been discarded.\n\n    say (1..5).Seq.skip;      # OUTPUT: «(2 3 4 5)␤»\n    say (1..5).Seq.skip(3);   # OUTPUT: «(4 5)␤»\n    say (1..5).Seq.skip(5);   # OUTPUT: «()␤»\n    say (1..5).Seq.skip(-1);  # OUTPUT: «(1 2 3 4 5)␤»\n\nCalling it with L<C<Whatever>|/type/Whatever> will return an empty C<Seq>:\n\n    say <1 2 3>.Seq.skip(*);  # OUTPUT: «()␤»\n\nThe multi that uses a Callable is intended mainly to be used this way:\n\n    say (1..5).Seq.skip(*-3); # OUTPUT: «(3 4 5)␤»\n\nInstead of throwing away the first C<$n> elements, it throws away everything\nI<but> the elements indicated by the WhateverCode, in this case all but the\nlast three elements.\n\nAs of language version C<6.e> (early implementation exists in Rakudo\ncompiler 2022.12+), it is also possible to specify multiple argument values.\nThese are then interpreted as number of values to produce, then skip, then\nproduce, etc.\n\n    say (1..12).Seq.skip(2,3,4); # OUTPUT: «(3 4 5 10 11 12)␤»\n\nThis first skipped 2 values, then produced 3 values (3, 4, 5), skipped 4 values\nand then produced the rest (10, 11, 12).\n\nIf the final value specified is in a \"produce\" position, then the rest of the\nC<Seq> will be skipped.  If the final value is in a \"skip\" position, then the\nrest of the C<Seq> will be produced.\n\n    say (1..10).Seq.skip(2,3,1,2); # OUTPUT: «(3 4 5 7 8)␤»\n    say (1..10).Seq.skip(2,3,1);   # OUTPUT: «(3 4 5 7 8 9 10)␤»\n\nIf a L<C<Whatever>|/type/Whatever> is specified in a \"produce\" position, it will cause the rest\nof the C<Seq> to be produced.  Otherwise, it will cause the rest if the C<Seq>\nto be skipped.\n\n    say (1..10).Seq.skip(2,*);   # OUTPUT: «(3 4 5 6 7 8 9 10)␤»\n    say (1..10).Seq.skip(2,3,*); # OUTPUT: «(3 4 5)␤»\n\nIf you want to start with producing values instead of skipping, specify B<0>\nas the first value.\n\n    say (1..10).Seq.skip(0,3,4); # OUTPUT: «(1 2 3 8 9 10)␤»\n\nIf you want an unending repeating pattern of skips and produces, you can\nspecify the arguments as an unending C<Seq> themselves.\n\n    say (^20).Seq.skip(|(2,3) xx *); # OUTPUT: «(0 1 5 6 10 11 15 16)␤»\n\n=head2 multi method slice\n\n    method slice(Seq:D: *@indices --> Seq:D)\n\nAvailable as of the 2021.02 release of the Rakudo compiler.\n\nThe C<slice> method takes a number of monotonically increasing indices for\nwhich to produce the value from the invocant in a new C<Seq>.  Indices can\nbe single numbers or ranges, as long they are increasing in value.\n\nThis provides a more efficient way of getting specific values out of a\nC<Seq> than either caching the C<Seq> or converting it to a L<C<List>|/type/List> or\nL<C<Array>|/type/Array>.\n\n    say (1..10).Seq.slice(0, 3..6, 8);  # OUTPUT: «(1 4 5 6 7 9)␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Sequence.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"composite\")\n\n=TITLE role Sequence\n\n=SUBTITLE Common methods of sequences\n\n    role Sequence does PositionalBindFailover { }\n\nThis role implements a series of methods for converting sequences and\naccessing their elements. These methods should work on all sequences:\nserial L<C<Seq>|/type/Seq>, ordered parallel L<C<HyperSeq>|/type/HyperSeq>,\nand unordered parallel L<C<RaceSeq>|/type/RaceSeq>.\n\nThese methods have in common that they all access the underlying\niterator if the sequence has not been\nL<cached|/type/PositionalBindFailover#method_cache> yet. Therefore they\nwill throw an error of type L<C<X::Seq::Consumed>|/type/X::Seq::Consumed>\nif called on a L<C<Seq>|/type/Seq> that was already consumed.\n\n=head1 Methods\n\n=head2 method Str\n\n    multi method Str(::?CLASS:D:)\n\nL<Stringifies|/type/List#method_Str> the\nL<cached|/type/PositionalBindFailover#method_cache> sequence.\n\n=head2 method Stringy\n\n    multi method Stringy(::?CLASS:D:)\n\nCalls C<.Stringy> on the\nL<cached|/type/PositionalBindFailover#method_cache> sequence.\n\n=head2 method Numeric\n\n    method Numeric(::?CLASS:D:)\n\nReturns the number of elements in the\nL<cached|/type/PositionalBindFailover#method_cache> sequence.\n\n=head2 method AT-POS\n\n    multi method AT-POS(::?CLASS:D: Int:D $idx)\n    multi method AT-POS(::?CLASS:D: int $idx)\n\nReturns the element at position C<$idx> in the\nL<cached|/type/PositionalBindFailover#method_cache> sequence.\n\n=head2 method EXISTS-POS\n\n    multi method EXISTS-POS(::?CLASS:D: Int:D $idx)\n    multi method EXISTS-POS(::?CLASS:D: int $idx)\n\nReturns a L<C<Bool>|/type/Bool> indicating whether there is an element at position\nC<$idx> in the L<cached|/type/PositionalBindFailover#method_cache>\nsequence.\n\n=head2 method eager\n\n    method eager(::?CLASS:D: --> List:D)\n\nReturns an eagerly evaluated L<C<List>|/type/List> based on the invocant\nsequence, and marks it as consumed.\nIf called on an already consumed L<C<Seq>|/type/Seq>, throws an error of type\nL<C<X::Seq::Consumed>|/type/X::Seq::Consumed>.\n\n    my $s = lazy 1..5;\n\n    say $s.is-lazy; # OUTPUT: «True␤»\n    say $s.eager;   # OUTPUT: «(1 2 3 4 5)␤»\n\n    say $s.eager;\n    CATCH {\n        when X::Seq::Consumed {\n            say 'Throws exception if already consumed';\n        }\n    }\n    # OUTPUT: «Throws exception if already consumed␤»\n\n=head2 method fmt\n\n    method fmt($format = '%s', $separator = ' ' --> Str:D)\n\nL<Formats|/type/List#method_fmt> the\nL<cached|/type/PositionalBindFailover#method_cache> sequence.\n\n=head2 method gist\n\n    multi method gist(::?CLASS:D:)\n\nReturns the L<gist|/type/List#method_gist> of the\nL<cached|/type/PositionalBindFailover#method_cache> sequence.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Set.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class Set\n\n=SUBTITLE Immutable collection of distinct objects\n\n    class Set does Setty { }\n\nA C<Set> is an immutable set, meaning a collection of distinct elements in no\nparticular order. (For I<mutable> sets, see L<C<SetHash>|/type/SetHash> instead.)\n\nObjects/values of any type are allowed as set elements. Within a C<Set>, every\nelement is guaranteed to be unique (in the sense that no two elements would\ncompare positively with the L<===|/routine/===> operator):\n\n=begin code\nmy $fruits = set <peach apple orange apple apple>;\n\nsay $fruits.elems;      # OUTPUT: «3␤»\nsay $fruits.keys.sort;  # OUTPUT: «apple orange peach␤»\n=end code\n\nC<Set>s can be treated as object hashes using the C<{ }> postcircumfix operator,\nwhich returns the value C<True> for keys that are elements of the set, and\nC<False> for keys that aren't:\n\n    my $fruits = set <peach apple orange apple apple>;\n    say $fruits<apple>;  # OUTPUT: «True␤»\n    say $fruits<kiwi>;   # OUTPUT: «False␤»\n\n=head1 Creating C<Set> objects\n\nC<Set>s can be composed using the L<set|#sub set> subroutine (or C<Set.new>, for\nwhich it is a shorthand). Any positional parameters, regardless of their type,\nbecome elements of the set:\n\n    my $n = set \"zero\" => 0, \"one\" => 1, \"two\" => 2;\n    say $n.keys.raku;        # OUTPUT: «(:two(2), :zero(0), :one(1)).Seq␤»\n    say $n.keys.map(&WHAT);  # OUTPUT: «((Pair) (Pair) (Pair))␤»\n\nAlternatively, the C<.Set> coercer (or its functional form, C<Set()>) can be\ncalled on an existing object to coerce it to a C<Set>. Its semantics depend on\nthe type and contents of the object. In general it evaluates the object in list\ncontext and creates a set with the resulting items as elements, although for\nHash-like objects or Pair items, only the keys become elements of the set - and\nkeys mapped to values which boolify to C<False> are skipped:\n\n    my $n = (\"zero\" => 0, \"one\" => 1, \"two\" => 2).Set;\n    say $n.keys.raku;        # OUTPUT: «(\"one\", \"two\").Seq␤»\n    say $n.keys.map(&WHAT);  # OUTPUT: «((Str) (Str))␤»\n\nFurthermore, you can get a C<Set> by using set operators (see next section) on\nobjects of other types such as L<C<List>|/type/List>, which will act like they\ninternally call C<.Set> on them before performing the operation. Be aware of\nthe tight precedence of those operators though, which may require you to use\nparentheses around arguments:\n\n    say (1..5) (^) 4;  # OUTPUT: «Set(1 2 3 5)␤»\n\nYou can also create a C<Set> with the C<.new> method.\n\n    my $fruits = Set.new( <peach apple orange apple apple> );\n\nSince 6.d (2019.03 and later) you can also use this syntax for parameterization\nof the C<Set>, to specify which type of values are acceptable:\n\n    # only allow strings (Str) in the Set\n    my $fruits = Set[Str].new( <peach apple orange apple apple> );\n\n    # only allow whole numbers (Int) in the Set\n    my $fruits = Set[Int].new( <peach apple orange apple apple> );\n    # Type check failed in binding; expected Int but got Str (\"peach\")\n\nFinally, you can create C<Set> masquerading as a hash (actually, declare a\nvariable L<C<Associative>|/type/Associative> by using the corresponding sigil) by using the C<is>\ntrait:\n\n    my %s is Set = <a b c>;\n    say %s<a>;  # OUTPUT: «True␤»\n    say %s<d>;  # OUTPUT: «False␤»\n\nSince 6.d (2019.03 and later), this syntax also allows you to specify the\ntype of values you would like to allow:\n\n    # limit to strings\n    my %s is Set[Str] = <a b c>;\n    say %s<a>;  # OUTPUT: «True␤»\n    say %s<d>;  # OUTPUT: «False␤»\n\n    # limit to whole numbers\n    my %s is Set[Int] = <a b c>;\n    # Type check failed in binding; expected Int but got Str (\"a\")\n\n=head1 Operators\n\nSee L<Operators with set\nsemantics|/language/setbagmix#Operators_with_set_semantics> for a complete\nlist of \"set operators\" applicable to, among other types, C<Set>.\n\nExamples:\n\n=begin code\nmy ($a, $b) = set(1, 2, 3), set(2, 4);\n\nsay $a (<) $b;  # OUTPUT: «False␤»\nsay $a (&) $b;  # OUTPUT: «Set(2)␤»\nsay $a (^) $b;  # OUTPUT: «Set(1 3 4)␤»\n\n# Unicode versions:\nsay $a ⊂ $b;  # OUTPUT: «False␤»\nsay $a ∩ $b;  # OUTPUT: «Set(2)␤»\nsay $a ⊖ $b;  # OUTPUT: «Set(1 3 4)␤»\n=end code\n\n=head1 Subroutines\n\n=head2 sub set\n\n    sub set(*@args --> Set)\n\nCreates a C<Set> from the given C<@args>\n\n=head1 See Also\n\nL<Sets, Bags, and Mixes|/language/setbagmix>\n\n=end pod\n"
  },
  {
    "path": "doc/Type/SetHash.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class SetHash\n\n=SUBTITLE Mutable collection of distinct objects\n\n    class SetHash does Setty { }\n\nA C<SetHash> is a mutable set, meaning a collection of distinct elements in no\nparticular order. (For I<immutable> sets, see L<C<Set>|/type/Set> instead.)\n\nObjects/values of any type are allowed as set elements. Within a L<C<Set>|/type/Set>, every\nelement is guaranteed to be unique (in the sense that no two elements would\ncompare positively with the L<===|/routine/===> operator):\n\n=begin code\nmy $fruits = <peach apple orange apple apple>.SetHash;\n\nsay $fruits.elems;      # OUTPUT: «3␤»\nsay $fruits.keys.sort;  # OUTPUT: «apple orange peach␤»\n=end code\n\nJust like L<C<Set>|/type/Set>s, C<SetHash>es can be treated as object hashes using the C<{ }>\npostcircumfix operator, which returns the value C<True> for keys that are\nelements of the set, and C<False> for keys that aren't.\n\n=begin code\nmy $fruits = <peach apple orange apple apple>.SetHash;\n\nsay $fruits<apple>;     # OUTPUT: «True␤»\nsay $fruits<kiwi>;      # OUTPUT: «False␤»\n=end code\n\nUnlike L<C<Set>|/type/Set>s, C<SetHash>es are mutable.  You can add an item or list of items\nto the C<SetHash> with the C<set> method and can remove an item or list of items\nwith the C<unset> method:\n\n=begin code\nmy $fruits = <peach>.SetHash;\n$fruits.set('apple');\nsay $fruits;            # OUTPUT: «SetHash(apple peach)␤»\n\n$fruits.unset('peach');\nsay $fruits;            # OUTPUT: «SetHash(apple)␤»\n\n$fruits.set(<kiwi banana apple>);\nsay $fruits;            # OUTPUT: «SetHash(apple banana kiwi)␤»\n\n$fruits.unset(<apple banana kiwi>);\nsay $fruits;            # OUTPUT: «SetHash()␤»\n=end code\n\nBe careful not to confuse the C<set> method, which adds an item to a C<SetHash>\nwith the L<C<Set>|/type/Set> method, which converts the mutable C<SetHash> into an immutable\nL<C<Set>|/type/Set>.\n\nAs an alternative to using the C<set> and C<unset> methods, you can also add or\nremove set elements by assigning a value that boolifies to C<True> or C<False>,\nrespectively:\n\n=begin code\nmy $fruits = <peach apple orange>.SetHash;\n\n$fruits<apple kiwi> = False, True;\nsay $fruits.keys.sort;  # OUTPUT: «kiwi orange peach␤»\n=end code\n\nHere is a convenient shorthand idiom for adding and removing SetHash elements\nusing assignment:\n\n=begin code\nmy SetHash $fruits .= new;\nsay $fruits<cherry>;      # OUTPUT: «False␤»\n$fruits<cherry>++;\nsay $fruits<cherry>;      # OUTPUT: «True␤»\n$fruits<apple banana kiwi>»++; # Add multiple elements\n\n$fruits<cherry>--;\nsay $fruits<cherry>;      # OUTPUT: «False␤»\n$fruits<banana kiwi>»--; # Remove multiple elements\n=end code\n\n=head1 Creating C<SetHash> objects\n\nC<SetHash>es can be composed using C<SetHash.new>. Any positional parameters,\nregardless of their type, become elements of the set:\n\n    my $n = SetHash.new: \"zero\" => 0, \"one\" => 1, \"two\" => 2;\n    say $n.keys.raku;        # OUTPUT: «(:two(2), :zero(0), :one(1)).Seq␤»\n    say $n.keys.map(&WHAT);  # OUTPUT: «((Pair) (Pair) (Pair))␤»\n\nAlternatively, the C<.SetHash> coercer (or its functional form, C<SetHash()>)\ncan be called on an existing object to coerce it to a C<SetHash>. Its semantics\ndepend on the type and contents of the object. In general it evaluates the\nobject in list context and creates a set with the resulting items as elements,\nalthough for Hash-like objects or Pair items, only the keys become elements of\nthe set - and keys mapped to values which boolify to C<False> are skipped:\n\n    my $n = (\"zero\" => 0, \"one\" => 1, \"two\" => 2).SetHash;\n    say $n.keys.raku;        # OUTPUT: «(\"one\", \"two\").Seq␤»\n    say $n.keys.map(&WHAT);  # OUTPUT: «((Str) (Str))␤»\n\nIt is also possible to initialize a single key with the use of C<{}>:\n\n    my $sh = SetHash.new;\n    $sh{ 'key1' } = True;\n    $sh{ 'key2' } = 'Hello World!';\n    $sh{ 'key3' } = 0;  # does not store the key since 0.Bool is False\n    say $sh;            # OUTPUT: «SetHash(key1 key2)␤»\n    say $sh.keys.raku;  # OUTPUT: «(\"key1\", \"key2\").Seq␤»\n\nor, in order to initialize more than one key at the same time, use a list\nassignment:\n\n   my $sh = SetHash.new;\n   $sh{ 'a', 'b', 'c' } = True, False, True;\n   say $sh.keys.raku;  # OUTPUT: «(\"a\", \"c\").Seq␤»\n\nYou can also create C<SetHash> masquerading as a hash by using the C<is> trait:\n\n    my %sh is SetHash = <a b c>;\n    say %sh<a>;  # OUTPUT: «True␤»\n    say %sh<d>;  # OUTPUT: «False␤»\n\nSince 6.d (2019.03 and later) it is also possible to specify the type of values\nyou would like to allow in a C<SetHash>.  This can either be done when calling\nC<.new>:\n\n    # only allow Pairs\n    my $n = SetHash[Pair].new: \"zero\" => 0, \"one\" => 1, \"two\" => 2;\n\nor using the masquerading syntax:\n\n    # only allow strings\n    my %sh is SetHash[Str] = <a b c>;\n    say %sh<a>;  # OUTPUT: «True␤»\n    say %sh<d>;  # OUTPUT: «False␤»\n\n    # only allow whole numbers\n    my %sh is SetHash[Int] = <a b c>;\n    # Type check failed in binding; expected Int but got Str (\"a\")\n\n=head1 Operators\n\nSee L<Operators with set\nsemantics|/language/setbagmix#Operators_with_set_semantics> for a complete\nlist of \"set operators\" applicable to, among other types, C<SetHash>.\n\nExamples:\n\n=begin code\nmy ($a, $b) = SetHash.new(1, 2, 3), SetHash.new(2, 4);\n\nsay $a (<) $b;  # OUTPUT: «False␤»\nsay $a (&) $b;  # OUTPUT: «SetHash(2)␤»\nsay $a (^) $b;  # OUTPUT: «SetHash(1 3 4)␤»\nsay $a (|) $b;  # OUTPUT: «SetHash(1 2 3 4)␤»\n\n# Unicode versions:\nsay $a ⊂ $b;  # OUTPUT: «False␤»\nsay $a ∩ $b;  # OUTPUT: «SetHash(2)␤»\nsay $a ⊖ $b;  # OUTPUT: «SetHash(1 3 4)␤»\nsay $a ∪ $b;  # OUTPUT: «SetHash(1 2 3 4)␤»\n=end code\n\n=head1 Methods\n\n=head2 method set\n\n    method set(SetHash:D: \\to-set --> Nil)\n\nWhen given single key, C<set> adds it to the C<SetHash>.  When given a\nL<C<List>|/type/List>, L<C<Array>|/type/Array>, L<C<Seq>|/type/Seq>, or any other type that C<does> the\nL<C«Iterator»|/type/Iterator> Role, C<set> adds each element of the\nL<C<Iterator>|/type/Iterator> as a key to the C<SetHash>.\n\nI<Note:> since release 2020.02.\n\n=head2 method unset\n\n    method unset(SetHash:D: \\to-unset --> Nil)\n\nWhen given single key, C<unset> removes it from the C<SetHash>.  When\ngiven a L<C<List>|/type/List>, L<C<Array>|/type/Array>, L<C<Seq>|/type/Seq>, or any other type that C<does> the\nL<C«Iterator»|/type/Iterator> Role, C<unset> removes each element of\nthe L<C<Iterator>|/type/Iterator> from the C<SetHash> (if it was present as a key).\n\nI<Note:> since release 2020.02.\n\n=head1 See Also\n\nL<Sets, Bags, and Mixes|/language/setbagmix>\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Setty.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"composite\")\n\n=TITLE role Setty\n\n=SUBTITLE Collection of distinct objects\n\n    role Setty does QuantHash { }\n\nA role for collections which make sure that each element can only appear once.\nSee L<C<Set>|/type/Set> and L<C<SetHash>|/type/SetHash>.\n\n=head1 Methods\n\n=head2 method new-from-pairs\n\n    method new-from-pairs(*@pairs --> Setty:D)\n\nConstructs a Setty object from a list of L«C<Pair> objects|/type/Pair»\ngiven as positional arguments:\n\n    say Set.new-from-pairs: 'butter' => 0.22, 'salt' => 0, 'sugar' => 0.02;\n    # OUTPUT: «Set(butter sugar)␤»\n\nB<Note:> be sure you aren't accidentally passing the Pairs as positional arguments;\nthe quotes around the keys in the above example are significant.\n\n=head2 method grab\n\n    method grab($count = 1)\n\nRemoves and returns C<$count> elements chosen at random (without repetition)\nfrom the set.\n\nIf C<*> is passed as C<$count>, or C<$count> is greater than or equal to the\nsize of the set, then all its elements are removed and returned in random order.\n\nOnly works on mutable sets; When used on an immutable set, it results in an\nexception.\n\n=head2 method grabpairs\n\n    method grabpairs($count = 1)\n\nRemoves C<$count> elements chosen at random (without repetition) from the set,\nand returns a list of L<C<Pair>|/type/Pair> objects whose keys are the grabbed elements and\nwhose values are C<True>.\n\nIf C<*> is passed as C<$count>, or C<$count> is greater than or equal to the\nsize of the set, then all its elements are removed and returned as L<C<Pair>|/type/Pair>s in\nthe aforementioned way in random order.\n\nOnly works on mutable sets; When used on an immutable set, it results in an\nexception.\n\n=head2 method pick\n\n    multi method pick($count = 1)\n\nReturns C<$count> elements chosen at random (without repetition) from the set.\n\nIf C<*> is passed as C<$count>, or C<$count> is greater than or equal to the\nsize of the set, then all its elements are returned in random order (shuffled).\n\n=head2 method pickpairs\n\n    multi method pickpairs(Setty:D: --> Pair:D)\n    multi method pickpairs(Setty:D: $count --> Seq:D)\n\nReturns a L<C<Pair>|/type/Pair> or a L<C<Seq>|/type/Seq> of L<C<Pair>|/type/Pair>s depending on the candidate of the method\nbeing invoked. Each L<C<Pair>|/type/Pair> returned has an element of the invocant as its key and\nC<True> as its value. In contrast to L<grabpairs|#method grabpairs>, the elements\nare 'picked' without replacement.\n\nIf C<*> is passed as C<$count>, or C<$count> is greater than or equal to the number\nof L<elements|#method elems> of the invocant, then all element/C<True> L<C<Pair>|/type/Pair>s from\nthe invocant are returned in a random sequence; i.e. they are returned shuffled;\n\nNote that each C<pickpairs> invocation maintains its own private state and has\nno effect on subsequent C<pickpairs> invocations.\n\n    my $numbers = set (4, 2, 3);\n    say $numbers.pickpairs;                           # OUTPUT: «4 => True␤»\n    say $numbers.pickpairs(1);                        # OUTPUT: «(3 => True)␤»\n    say $numbers.pickpairs(*);                        # OUTPUT: «(2 => True 4 => True 3 => True)␤»\n\n=head2 method roll\n\n    multi method roll($count = 1)\n\nReturns a lazy list of C<$count> elements, each randomly selected from the set.\nEach random choice is made independently, like a separate die roll where each\ndie face is a set element.\n\nIf C<*> is passed as C<$count>, the list is infinite.\n\n=head2 method antipairs\n\n    multi method antipairs(Setty:D: --> Seq:D)\n\nReturns all elements in the set and C<True> as a L<C<Seq>|/type/Seq> of L<C<Pair>|/type/Pair>s,\nwhere the element itself is the value, i.e. the opposite of method C<pairs>.\n\n    my $s = Set.new(1, 2, 3, 1);\n    say $s.antipairs.sort;                            # OUTPUT: «(True => 1 True => 2 True => 3)␤»\n\n=head2 method keys\n\n    multi method keys(Setty:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> of all elements of the set.\n\n    my $s = Set.new(1, 2, 3);\n    say $s.keys;                                      # OUTPUT: «(3 1 2)␤»\n\n=head2 method values\n\n    multi method values(Setty:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> containing as many C<True> values as the set has elements.\n\n    my $s = Set.new(1, 2, 3);\n    say $s.values;                                    # OUTPUT: «(True True True)␤»\n\n=head2 method kv\n\n    multi method kv(Setty:D: --> Seq:D)\n\nReturns a L<C<Seq>|/type/Seq> of the set's elements and C<True> values interleaved.\n\n    my $s = Set.new(1, 2, 3);\n    say $s.kv;                                        # OUTPUT: «(3 True 1 True 2 True)␤»\n\n=head2 method elems\n\n    method elems(Setty:D: --> Int)\n\nThe number of elements of the set.\n\n=head2 method total\n\n    method total(Setty:D: --> Int)\n\nThe total of all the values of the L<C<QuantHash>|/type/QuantHash> object. For a C<Setty>\nobject, this is just the number of elements.\n\n=head2 method minpairs\n\n    multi method minpairs(Setty:D: --> Seq:D)\n\nReturns the value of L«C<self.pairs>|/routine/pairs»\n(as all Pairs have minimum values). See also\nL«C<Any.minpairs>|/routine/minpairs»\n\n=head2 method maxpairs\n\n    multi method maxpairs(Setty:D: --> Seq:D)\n\nReturns the value of L«C<self.pairs>|/routine/pairs»\n(as all Pairs have maximum values). See also\nL«C<Any.maxpairs>|/routine/maxpairs»\n\n=head2 method default\n\n    method default(--> False)\n\nReturns the default value of the invocant, i.e. the value which is returned\nwhen trying to access an element in the C<Setty> object which has not been\npreviously initialized or when accessing an element which has explicitly\nbeen set to L<C<Nil>|/type/Nil> or C<False>.\n\n    my $s1 = SetHash.new(1, 2, 3);\n    say $s1{2};                                           # OUTPUT: «True␤»\n    $s1{2} = Nil;\n    say $s1{2};                                           # OUTPUT: «False␤»\n    # access non initialized element\n    say $s1{4};                                           # OUTPUT: «False␤»\n\n=head2 method ACCEPTS\n\n    method ACCEPTS($other)\n\nReturns C<True> if C<$other> and C<self> contain all the same elements,\nand no others.\n\n=head2 method Bag\n\n    method Bag(Setty:D: --> Bag:D)\n\nReturns a L<C<Bag>|/type/Bag> containing the elements of the invocant.\n\n    my Bag $b = Set.new(1, 2, 3).Bag;\n    say $b;                                           # OUTPUT: «Bag(3 1 2)␤»\n\nThe quantity of the elements in this created bag will be set to one:\n\n    say (1,2,3).Bag{1};                              # OUTPUT: «1␤»\n\n\n=head2 method BagHash\n\n    method BagHash(Setty:D: --> BagHash:D)\n\nReturns a L<C<BagHash>|/type/BagHash> containing the elements of the invocant.\n\n    my BagHash $b = Set.new(1, 2, 3).BagHash;\n    say $b;                                           # OUTPUT: «BagHash(1 2 3)␤»\n\n=head2 method Bool\n\n    multi method Bool(Setty:D: --> Bool:D)\n\nReturns C<True> if the invocant contains at least one element.\n\n    my $s1 = Set.new(1, 2, 3);\n    say $s1.Bool;                                     # OUTPUT: «True␤»\n\n    my $s2 = $s1 ∩ Set.new(4, 5);                     # set intersection operator\n    say $s2.Bool;                                     # OUTPUT: «False␤»\n\n=head2 method Mix\n\n    method Mix(Setty:D: --> Mix:D)\n\nReturns a L<C<Mix>|/type/Mix> containing the elements of the invocant.\n\n    my Mix $b = Set.new(1, 2, 3).Mix;\n    say $b;                                           # OUTPUT: «Mix(3 1 2)␤»\n\nThe elements of the returned L<C<Mix>|/type/Mix> will have weights equal to 1:\n\n    say (1,2,3).Mix{3};                               # OUTPUT: «1␤»\n\n=head2 method MixHash\n\n    method MixHash(Setty:D: --> MixHash:D)\n\nReturns a L<C<MixHash>|/type/MixHash> containing the elements of the invocant.\n\n    my MixHash $b = Set.new(1, 2, 3).MixHash;\n    say $b;                                           # OUTPUT: «MixHash(1 2 3)␤»\n\n=head1 See Also\n\nL<Sets, Bags, and Mixes|/language/setbagmix>\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Signal.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"enum\") :category(\"domain-specific\")\n\n=TITLE enum Signal\n\n=SUBTITLE List of supported signals\n\n    enum Signal ()\n\nA dynamically generated L<enum|/language/enumeration> containing numeric/named values for\nsupported signals.  For example:\n\n    say Signal.keys.sort[^3] # show the first 3 alphabetically\n    # OUTPUT: «(SIGABRT SIGALRM SIGBREAK)»\n\nSee L<related routines|/routine/signal>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Signature.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Signature\n\n=SUBTITLE Parameter list pattern\n\n    class Signature { }\n\nA signature is a static description of the L<parameter|/type/Parameter> list\nof a code object.  That is, it describes what and how many arguments\nyou need to pass to the code or function in order to call it.\n\nPassing arguments to a signature I<binds> the arguments, contained in\na L<C<Capture>|/type/Capture>, to the signature.\n\nFor information on signature literals, see L<here|/language/signatures>.\n\n=head1 Methods\n\n=head2 method params\n\n    method params(Signature:D: --> Positional)\n\nReturns the list of L<C<Parameter>|/type/Parameter> objects that make up the signature.\n\n=head2 method arity\n\n    method arity(Signature:D: --> Int:D)\n\nReturns the I<minimal> number of positional arguments required to satisfy\nthe signature.\n\n=head2 method count\n\n    method count(Signature:D: --> Real:D)\n\nReturns the I<maximal> number of positional arguments which can be bound\nto the signature. Returns C<Inf> if there is a slurpy positional parameter.\n\n=head2 method returns\n\nWhatever the Signature's return constraint is:\n\n    :($a, $b --> Int).returns # OUTPUT: «(Int)»\n\n=head2 method ACCEPTS\n\n    multi method ACCEPTS(Signature:D: Signature $topic)\n    multi method ACCEPTS(Signature:D: Capture $topic)\n    multi method ACCEPTS(Signature:D: Mu \\topic)\n\nIf C<$topic> is a C<Signature> returns C<True> if anything\naccepted by C<$topic> would also be accepted by the invocant, otherwise returns\nC<False>:\n\n    :($a, $b) ~~ :($foo, $bar, $baz?);   # OUTPUT: «True»\n    :(Int $n) ~~ :(Str);                 # OUTPUT: «False»\n\nThe C<$topic> is a L<C<Capture>|/type/Capture>, returns C<True> if it can be bound\nto the invocant, i.e., if a function with invocant's C<Signature> would be able\nto be called with the C<$topic>:\n\n    \\(1, 2, :foo) ~~ :($a, $b, :foo($bar)); # OUTPUT: «True»\n    \\(1, :bar)    ~~ :($a);                 # OUTPUT: «False»\n\nLastly, the candidate with C<Mu \\topic> converts C<topic> to\nL<C<Capture>|/type/Capture> and follows the same semantics as\nL<C<Capture>|/type/Capture> C<$topic>:\n\n    <a b c d>  ~~ :(Int $a);      # OUTPUT: «False»\n    42         ~~ :(Int);         # OUTPUT: «False» (Int.Capture throws)\n    set(<a b>) ~~ :(:$a, :$b);    # OUTPUT: «True»\n\nSince L«C<where> clauses|/language/signatures#index-entry-where_clause»\nare not introspectable, the method cannot determine whether two signatures\nL<ACCEPTS|/type/Signature#method_ACCEPTS> the same sort of C<where>-constrained\nparameters. Such comparisons will return C<False>. This includes signatures with\nliterals, which are just sugar for the C<where>-constraints:\n\n    say :(42) ~~ :($ where 42)    # OUTPUT: «False␤»\n\n=head2 method Capture\n\n    method Capture()\n\nThrows L<C<X::Cannot::Capture>|/type/X::Cannot::Capture>.\n\n=head1 Runtime creation of Signature objects (6.d, 2019.03 and later)\n\n=for code :preamble<role Type {}>\nSignature.new(params => (...), returns => Type, arity => 1, count => 1.Num)\n\nIn some situations, specifically when working with the MetaObject Protocol,\nit makes sense to create C<Signature> objects programmatically.  For this\npurpose, you can call the C<new> method with the following named parameters:\n\n=item params\n\nA list of L<C<Parameter>|/type/Parameter> objects for this signature.\n\n=item returns\n\nAny constraint the return value should match.  Defaults to L<C<Mu>|/type/Mu>, which\neffectively implies no return value constraint check.\n\n=item arity\n\nThe I<minimal> number of positional arguments required to satisfy the\nsignature.  Defaults to the number of L<C<Parameter>|/type/Parameter> objects given with\nthe C<params> parameter.\n\n=item count\n\nThe I<maximal> number of positional arguments which can be bound to the\nsignature. Defaults to the C<arity> if not specified.  Specify C<Inf> if\nthere is a slurpy positional parameter.\n\nI<Warning>: although the logical type of the C<count> parameter is integer,\nthe value assigned to it must explicitly be of type L<C<Num>|/type/Num>. If any other\ntype is used, the C<new> method silently fails and returns an empty signature.\nThe same trouble occurs when the value assigned to the C<arity> parameter is\nnot of type L<C<Int>|/type/Int>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Slip.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class Slip\n\n=SUBTITLE A kind of List that automatically flattens into an outer container\n\n    class Slip is List {}\n\nA C<Slip> is a L<C<List>|/type/List> that automatically flattens into an outer List\n(or other list-like container or iterable).\n\nFor example it allows you to write a L<map|/routine/map> that produces more than\none value into the result without nesting:\n\n=for code\nsay <a b c>.map({ ($_, $_.uc).Slip }).join('|');        # OUTPUT: «a|A|b|B|c|C␤»\n\nIn contrast, when returning an ordinary List, the resulting list is nested:\n\n=for code\nsay <a b c>.map({ $_, $_.uc }).join('|');               # OUTPUT: «a A|b B|c C␤»\n\nTo create a C<Slip>, either coerce another list-like type to it by calling the\nC<Slip> method, or use the C<slip> subroutine:\n\n    # This says \"1\" and then says \"2\", rather than saying \"(1 2)\"\n    .say for gather {\n        take slip(1, 2);\n    }\n\nA C<Slip> may also be created by using the L«C<prefix:<|>>|/language/operators#prefix_|» operator.  This differs\nfrom the C<slip> subroutine in both precedence and treatment of single\narguments. In fact, C<prefix:<|>> only takes a single argument, so in that way,\nit behaves closer to the C<.Slip> method than the C<slip> subroutine.\n\n=for code\nmy $l = (1, 2, 3);\nsay (1, slip 2, 3).raku;  # says (1, 2, 3)          , slips 2, 3 into (1, …)\nsay (0, slip $l, 4).raku; # says (0, $(1, 2, 3), 4) , $l does not break apart\nsay (0, slip $l).raku;    # says (0, 1, 2, 3)       , slips from $l into (0, …)\nsay (0, $l.Slip).raku;    # says (0, 1, 2, 3)       , slips from $l into (0, …)\nsay (0, $l.Slip, 4).raku; # says (0, 1, 2, 3, 4)    , slips from $l into (0, …, 4)\nsay (|$l).raku;           # says slip(1, 2, 3)      , breaks apart $l\nsay (0, (|$l, 4), 5);     # says (0 (1 2 3 4) 5)    , slips from $l into (…, 4)\nsay (0, ($l.Slip, 4), 5); # says (0 (1 2 3 4) 5)    , slips from $l into (…, 4)\nsay (0, (slip $l, 4), 5); # says (0 (1 2 3) 4 5)    , slips ($l, 4) into (0, …, 5)\nsay (0, ($l, 4).Slip, 5); # says (0 (1 2 3) 4 5)    , slips ($l, 4) into (0, …, 5)\n\nLoops that do not want to produce a value for an iteration use C<Slip>s, rather\nthan empty L<C<List>|/type/List>s to do so, as do C<if> statements that do not run their\nblocks.\n\nPlease note that C<prefix:<|>> will also apply parameters in a slippy manner to\na routine call. It does not forward a C<Slip> to the called routine, that\nincludes C<return> and C<take>.\n\n    my \\l = gather for 1..10 -> $a, $b { take |($a, $b) }; say l.raku;\n    # OUTPUT: «((1, 2), (3, 4), (5, 6), (7, 8), (9, 10)).Seq␤»\n    my \\m= gather for 1..10 -> $a, $b { take ($a, $b).Slip }; say m.raku;\n    # OUTPUT: «(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).Seq␤»\n\n=head1 Methods\n\n=head2 method List\n\n    multi method List(Slip:D: --> List:D)\n\nTurns it into a list.\n\n=head2 sub slip\n\n    multi slip(--> Empty)\n    multi slip(@args --> Slip:D)\n    multi slip(+args --> Slip:D)\n\nCreates a C<Slip> from its arguments by calling\nL<C<.Slip>|/routine/Slip> on the object formed by them. Returns\nL<C<Empty>|/type/Slip#constant_Empty> if called with void arguments.\n\n=head1 Constants\n\n=head2 constant Empty\n\nC<Empty> is a C<Slip> of the empty L<C<List>|/type/List>.\n\n    say \"\".comb ~~ Empty;\n    # OUTPUT: «True␤»\n\nFor example, these constructs with a failing test return C<Empty>:\n\n    do if 0 {};\n    (42 if 0);\n    do with Any {};\n    (42 with Any);\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Stash.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class Stash\n\n=SUBTITLE Table for \"our\"-scoped symbols\n\n    class Stash is Hash { }\n\nA C<Stash> is a hash that is used for symbol tables at the package scoping level\nin Raku.\n\nTo get a Stash, you can call the C<.WHO> pseudo-method on a package (because it\nanswers the question I<who lives here?>), or if you write the package name as\na literal, append two colons:\n\n    class Boring {\n        class Nested { };\n        our sub package_sub { }\n        my sub lexical { };\n        method a_method() { }\n    }\n    say Boring::.^name;             # OUTPUT: «Stash␤»\n    say Boring.WHO === Boring::;    # OUTPUT: «True␤»\n\nSince it inherits from L<C<Hash>|/type/Hash>, you can use all the usual hash\nfunctionality:\n\n=for code :skip-test<compile time error>\nsay Boring::.keys.sort;         # OUTPUT: «(&package_sub Nested)␤»\nsay Boring::<Nested>;           # OUTPUT: «(Nested)␤»\n\nAs the example above shows only \"our\"-scoped things appear in the C<Stash>\n(nested classes are \"our\" by default, but can be excluded with \"my\".)  Lexicals\nand methods are not included in a Stash, since they do not live in the package\ntable.  Lexicals live in a separate lexical pad, which is only visible from\ninside the scope.  Methods (in the case that the package is also a class) have\na separate method table, and are accessible through introspection on the\nclass itself, via C<.can> and C<.^methods>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Str.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Str\n\n=SUBTITLE String of characters\n\n    class Str is Cool does Stringy { }\n\nBuilt-in class for strings. Objects of type C<Str> are\nL<immutable|/language/faq#If_Str_is_immutable,_how_does_s///_work?_If_Int_is_immutable,_how_does_$i%2B%2B_work?>.\n\n=head1 Methods\n\n=head2 routine chop\n\n     multi method chop(Str:D:)\n     multi method chop(Str:D: Int() $n)\n\nReturns the string with C<$n> characters removed from the end.\nThe original string is left unchanged.\nThe C<$n> positional is converted to L<C<Int>|/type/Int>\nbeforehand.\n\n    say \"Whateverable\".chop(3.6);  # OUTPUT: «Whatevera␤»\n    my $string= \"Whateverable\";\n    say $string.chop(\"3\");         # OUTPUT: «Whatevera␤»\n\nCalls without an argument remove just one character.\nIf the string contains fewer characters than are to be chopped,\nthe result is the empty string.\n\n=head2 routine chomp\n\n    multi        chomp(Str:D  --> Str:D)\n    multi method chomp(Str:D: --> Str:D)\n\nReturns the string with a logical newline (any codepoint that has the\nC<NEWLINE> property) removed from the end.\n\nExamples:\n\n    say chomp(\"abc\\n\");       # OUTPUT: «abc␤»\n    say \"def\\r\\n\".chomp;      # OUTPUT: «def␤» NOTE: \\r\\n is a single grapheme!\n    say \"foo\\r\".chomp;        # OUTPUT: «foo␤»\n\n=head2 method contains\n\n    multi method contains(Str:D: Str:D $needle --> Bool)\n    multi method contains(Str:D: Str:D $needle, Int:D $pos --> Bool)\n    multi method contains(Str:D: Str:D $needle, :m(:$ignoremark)! --> Bool)\n    multi method contains(Str:D: Str:D $needle, :i(:$ignorecase)!, :m(:$ignoremark) --> Bool)\n    multi method contains(Str:D: Str:D $needle, Int:D $pos, :m(:$ignoremark)! --> Bool)\n    multi method contains(Str:D: Str:D $needle, Int:D $pos, :i(:$ignorecase)!, :m(:$ignoremark) --> Bool)\n    multi method contains(Str:D: Regex:D $needle --> Bool)\n    multi method contains(Str:D: Regex:D $needle, Int:D $pos --> Bool)\n\nGiven a C<Str> invocant (known as the I<haystack>) and a first argument\n(known as the C<$needle>), it searches for the C<$needle> in the I<haystack>\nfrom the beginning of the string and returns C<True> if C<$needle> is found.\nIf the optional parameter C<$pos> is provided, then C<contains> will\nsearch the I<haystack> starting from C<$pos> characters into the string.\n\n    say \"Hello, World\".contains('Hello');      # OUTPUT: «True␤»\n    say \"Hello, World\".contains('hello');      # OUTPUT: «False␤»\n    say \"Hello, World\".contains('Hello', 1);   # OUTPUT: «False␤»\n    say \"Hello, World\".contains(',');          # OUTPUT: «True␤»\n    say \"Hello, World\".contains(',', 3);       # OUTPUT: «True␤»\n    say \"Hello, World\".contains(',', 10);      # OUTPUT: «False␤»\n\nIn the first case, C<contains> searches for the C<'Hello'> string on the\ninvocant right from the start of the invocant string and returns C<True>.\nIn the third case, the C<'Hello'> string is not found since we have\nstarted looking from the second position (index 1) in C<'Hello, World'>.\n\nC<$needle> can also be of type L<C<Cool>|/type/Cool>, which will be coerced to C<Str>.\nSimilarly, C<$pos> can be of type L<C<Cool>|/type/Cool>, which will be coerced to L<C<Int>|/type/Int>.\n(Technically, these cases will take a detour over L<C<Cool.contains>|/type/Cool#method_contains>,\nwhich does the coercions and then calls C<Str.contains>.)\n\n    say \"Hello, 12345\".contains(5, \"10.0\");    # OUTPUT: «True␤»\n\nSince Rakudo release 2020.02, the C<$needle> can also be\na L<C<Regex>|/type/Regex> in which case the C<contains> method\nquickly returns whether the regex matches the string at least\nonce. No L<C<Match>|/type/Match> objects are created, so this is\nrelatively fast.\n\n    say 'Hello, World'.contains(/\\w <?before ','>/);    # OUTPUT: «True␤»\n    say 'Hello, World'.contains(/\\w <?before ','>/, 5); # OUTPUT: «False␤»\n\nSince Rakudo release 2020.02, if the optional named parameter\nC<:ignorecase>, or C<:i>, is specified, the search for C<$needle>\nignores the distinction between uppercase, lowercase, and titlecase\nletters.\n\n    say \"Hello, World\".contains(\"world\");              # OUTPUT: «False␤»\n    say \"Hello, World\".contains(\"world\", :ignorecase); # OUTPUT: «True␤»\n\nSince Rakudo release 2020.02, if the optional named parameter\nC<:ignoremark>, or C<:m>, is specified, the search for C<$needle>\nonly considers base characters, and ignores additional marks such as\ncombining accents.\n\n    say \"abc\".contains(\"ä\");               # OUTPUT: «False␤»\n    say \"abc\".contains(\"ä\", :ignoremark);  # OUTPUT: «True␤»\n\nNote that because of how a L<C<List>|/type/List> or L<C<Array>|/type/Array> is\nL<coerced|/type/List#method_Str> into a C<Str>, the results may\nsometimes be surprising.\n\n    say <Hello, World>.contains('Hello');    # OUTPUT: «True␤»\n    say <Hello, World>.contains('Hello', 0); # OUTPUT: «True␤»\n    say <Hello, World>.contains('Hello', 1); # OUTPUT: «False␤»\n\nSee L<traps|/language/traps#Lists_become_strings,_so_beware_.contains()>.\n\n=head2 routine lc\n\n    multi        lc(Str:D  --> Str:D)\n    multi method lc(Str:D: --> Str:D)\n\nReturns a lowercase version of the string.\n\nExamples:\n\n    lc(\"A\"); # OUTPUT: «\"a\"»\n    \"A\".lc;  # OUTPUT: «\"a\"»\n\n=head2 routine uc\n\n    multi        uc(Str:D  --> Str:D)\n    multi method uc(Str:D: --> Str:D)\n\nReturns an uppercase version of the string.\n\n=head2 routine fc\n\n    multi        fc(Str:D  --> Str:D)\n    multi method fc(Str:D: --> Str:D)\n\nDoes a Unicode \"fold case\" operation suitable for doing caseless\nstring comparisons.  (In general, the returned string is unlikely to\nbe useful for any purpose other than comparison.)\n\n=head2 routine tc\n\n    multi        tc(Str:D  --> Str:D)\n    multi method tc(Str:D: --> Str:D)\n\nDoes a Unicode \"titlecase\" operation, that is changes the first character in\nthe string to titlecase, or to uppercase if the character has no titlecase\nmapping.\n\n=head2 routine tclc\n\n    multi        tclc(Str:D  --> Str:D)\n    multi method tclc(Str:D: --> Str:D)\n\nTurns the first character to titlecase, and all other characters to lowercase.\n\n=head2 routine wordcase\n\n=for code\nmulti        wordcase(Cool $x  --> Str)\nmulti        wordcase(Str:D $x --> Str)\nmulti method wordcase(Str:D: :&filter = &tclc, Mu :$where = True --> Str)\n\nReturns a string in which C<&filter> has been applied to all the words\nthat match C<$where>. By default, this means that the first letter of\nevery word is capitalized, and all the other letters lowercased.\n\n=head2 method unival\n\n    multi method unival(Str:D: --> Numeric)\n\nReturns the numeric value that the first codepoint in the invocant represents,\nor C<NaN> if it's not numeric.\n\n    say '4'.unival;     # OUTPUT: «4␤»\n    say '¾'.unival;     # OUTPUT: «0.75␤»\n    say 'a'.unival;     # OUTPUT: «NaN␤»\n\n=head2 method univals\n\n    multi method univals(Str:D: --> List)\n\nReturns a list of numeric values represented by each codepoint in the invocant\nstring, and C<NaN> for non-numeric characters.\n\n    say \"4a¾\".univals;  # OUTPUT: «(4 NaN 0.75)␤»\n\n=head2 routine chars\n\n    multi        chars(Cool  $x --> Int:D)\n    multi        chars(Str:D $x --> Int:D)\n    multi        chars(str   $x --> int)\n    multi method chars(Str:D:   --> Int:D)\n\nReturns the number of characters in the string in graphemes. On the JVM,\nthis currently erroneously returns the number of codepoints instead.\n\n=head2 method encode\n\n    multi method encode(Str:D $encoding = 'utf8', :$replacement, Bool() :$translate-nl = False, :$strict)\n\nReturns a L<C<Blob>|/type/Blob> which represents the original string in the given\nencoding and normal form. The actual return type is as specific as\npossible, so C<$str.encode('UTF-8')> returns a L<C<utf8>|/type/utf8> object,\nC<$str.encode('ISO-8859-1')> a C<buf8>. If C<:translate-nl> is set to\nC<True>, it will translate newlines from C<\\n> to C<\\r\\n>, but only in\nWindows. C<$replacement> indicates how characters are going to be\nreplaced in the case they are not available in the current encoding,\nwhile C<$strict> indicates whether unmapped codepoints will still\ndecode; for instance, codepoint 129 which does not exist in\nC<windows-1252>.\n\n    my $str = \"Þor is mighty\";\n    say $str.encode(\"ascii\", :replacement( 'Th') ).decode(\"ascii\");\n    # OUTPUT: «Thor is mighty␤»\n\nIn this case, any unknown character is going to be substituted by C<Th>. We know\nin advance that the character that is not known in the C<ascii> encoding is\nC<Þ>, so we substitute it by its latin equivalent, C<Th>. In the absence of any\nreplacement set of characters, C<:replacement> is understood as a L<C<Bool>|/type/Bool>:\n\n=for code :preamble<my $str = \"Þor is mighty\";>\nsay $str.encode(\"ascii\", :replacement).decode(\"ascii\"); # OUTPUT: «?or is mighty␤»\n\nIf C<:replacement> is not set or assigned a value, the error C<Error encoding\nASCII string: could not encode codepoint 222> will be issued (in this case,\nsince þ is codepoint 222).\n\nSince the L<C<Blob>|/type/Blob> returned by C<encode> is the original string in normal form,\nand every element of a L<C<Blob>|/type/Blob> is a byte, you can obtain the length in bytes of\na string by calling a method that returns the size of the L<C<Blob>|/type/Blob> on it:\n\n=for code\nsay \"þor\".encode.bytes; # OUTPUT: «4␤»\nsay \"þor\".encode.elems; # OUTPUT: «4␤»\n\n=head2 method index\n\n    multi method index(Str:D: Cool:D $needle, :i(:$ignorecase), :m(:$ignoremark) --> Int:D)\n    multi method index(Str:D: Str:D $needle, :i(:$ignorecase), :m(:$ignoremark) --> Int:D)\n    multi method index(Str:D: Cool:D $needle, Cool:D $pos, :i(:$ignorecase), :m(:$ignoremark) --> Int:D)\n    multi method index(Str:D: Str:D $needle, Int:D $pos, :i(:$ignorecase), :m(:$ignoremark) --> Int:D)\n    multi method index(Str:D: @needles --> Int:D)\n    multi method index(Str:D: @needles, :m(:$ignoremark)! --> Int:D)\n    multi method index(Str:D: @needles, :i(:$ignorecase)!, :m(:$ignoremark) --> Int:D)\n\nSearches for C<$needle> in the string starting from C<$pos> (if present). It\nreturns the offset into the string where C<$needle> was found, and L<C<Nil>|/type/Nil> if it\nwas not found.\n\nSince Rakudo release 2020.02, if the optional named parameter\nC<:ignorecase>, or C<:i>, is specified, the search for C<$needle> ignores\nthe distinction between uppercase, lowercase and titlecase letters. In\naddition, if the optional named parameter C<:ignoremark>, or C<:m>, is\nspecified, the search for C<$needle> only considers base characters, and ignores\nadditional marks such as combining accents.\n\nSince Rakudo release 2020.05, C<index> accepts a list of needles to search\nthe string with, and return the lowest index found or L<C<Nil>|/type/Nil>.\n\nExamples:\n\n    say \"Camelia is a butterfly\".index(\"a\");         # OUTPUT: «1␤»\n    say \"Camelia is a butterfly\".index(\"a\", 2);      # OUTPUT: «6␤»\n    say \"Camelia is a butterfly\".index(\"er\");        # OUTPUT: «17␤»\n    say \"Camelia is a butterfly\".index(\"Camel\");     # OUTPUT: «0␤»\n    say \"Camelia is a butterfly\".index(\"Onion\");     # OUTPUT: «Nil␤»\n    say \"Camelia is a butterfly\".index(<a e i u>);   # OUTPUT: «1␤»\n    say \"Camelia is a butterfly\".index(<a c>, :i);   # OUTPUT: «0␤»\n    say \"Camelia is a butterfly\".index(('w', 'x'));  # OUTPUT: «Nil␤»\n\n    say \"Hello, World\".index(\"world\");               # OUTPUT: «Nil␤»\n    say \"Hello, World\".index(\"world\", :ignorecase);  # OUTPUT: «7␤»\n\n    say \"abc\".index(\"ä\");                            # OUTPUT: «Nil␤»\n    say \"abc\".index(\"ä\", :ignoremark);               # OUTPUT: «0␤»\n    say \"abc\".index(\"x\").defined ?? 'OK' !! 'NOT';   # OUTPUT: «NOT␤»\n\nOther forms of C<index>, including subs, are\nL<inherited from C<Cool>|/type/Cool#routine_index>.\n\n=head2 routine rindex\n\n    multi method rindex(Str:D: Str:D $needle --> Int:D)\n    multi method rindex(Str:D: Str:D $needle, Int:D $pos --> Int:D)\n    multi method rindex(Str:D: @needles --> Int:D)\n\nReturns the last position of C<$needle> in the string not after C<$pos>.\nReturns L<C<Nil>|/type/Nil> if C<$needle> wasn't found.\n\nSince Rakudo release 2020.05, C<rindex> accepts a list of needles to search\nthe string with, and return the highest index found or L<C<Nil>|/type/Nil>.\n\nExamples:\n\n    say \"aardvark\".rindex: \"a\";       # OUTPUT: «5␤»\n    say \"aardvark\".rindex: \"a\", 0;    # OUTPUT: «0␤\n    say \"aardvark\".rindex: \"t\";       # OUTPUT: «Nil␤»\n    say \"aardvark\".rindex: <d v k>;   # OUTPUT: «7␤»\n\nOther forms of C<rindex>, including subs, are\nL<inherited from C<Cool>|/type/Cool#routine_rindex>.\n\n=head2 method indices\n\n    multi method indices(Str:D: Str:D $needle, :i(:$ignorecase), :m(:$ignoremark), :$overlap --> List:D)\n    multi method indices(Str:D: Str:D $needle, Int:D $start, :i(:$ignorecase), :m(:$ignoremark), :$overlap --> List:D)\n\nSearches for all occurrences of C<$needle> in the string starting from position\nC<$start>, or zero if it is not specified, and returns a L<C<List>|/type/List> with all offsets\nin the string where C<$needle> was found, or an empty list if it was not found.\n\nIf the optional parameter C<:overlap> is specified the search continues from the\nindex directly following the previous match, otherwise the search will continue\nafter the previous match.\n\n    say \"banana\".indices(\"a\");              # OUTPUT: «(1 3 5)␤»\n    say \"banana\".indices(\"ana\");            # OUTPUT: «(1)␤»\n    say \"banana\".indices(\"ana\", :overlap);  # OUTPUT: «(1 3)␤»\n    say \"banana\".indices(\"ana\", 2);         # OUTPUT: «(3)␤»\n\nSince Rakudo release 2020.02, if the optional named parameter\nC<:ignorecase>, or C<:i>, is specified, the search for C<$needle>\nignores the distinction between uppercase, lowercase and titlecase\nletters.\n\n    say \"banAna\".indices(\"a\");              # OUTPUT:«(1 5)␤»\n    say \"banAna\".indices(\"a\", :ignorecase); # OUTPUT:«(1 3 5)␤»\n\nSince Rakudo 2020.02, if the optional named parameter C<:ignoremark>,\nor C<:m>, is specified, the search for C<$needle> only considers base\ncharacters, and ignores additional marks such as combining accents.\n\n    say \"tête-à-tête\".indices(\"te\");              # OUTPUT:«(2 9)␤»\n    say \"tête-à-tête\".indices(\"te\", :ignoremark); # OUTPUT:«(0 2 7 9)␤»\n\n=head2 method match\n\n    method match($pat, :continue(:$c), :pos(:$p), :global(:$g), :overlap(:$ov), :exhaustive(:$ex), :st(:$nd), :rd(:$th), :$nth, :$x --> Match)\n\nPerforms a match of the string against C<$pat> and returns a\nL<C<Match>|/type/Match> object if there is a successful match; it returns L<C<Nil>|/type/Nil>\notherwise. Matches are stored in the L<default match variable\nC<$/>|/language/variables#index-entry-match_variable>. If C<$pat> is not a\nL<C<Regex>|/type/Regex> object, match will coerce the argument to a Str and then\nperform a literal match against C<$pat>.\n\nA number of optional named parameters can be specified, which alter how the match is performed.\n\n=item :continue\n\nThe C<:continue> adverb takes as an argument the position where the regex should\nstart to search. If no position is specified for C<:c> it will default to 0\nunless C<$/> is set, in which case it defaults to C<$/.to>.\n\n=item :pos\n\nTakes a position as an argument. Fails if regex cannot be matched from that position, unlike C<:continue>.\n\n=item :global\n\nInstead of searching for just one match and returning a L<C<Match>|/type/Match> object, search\nfor every non-overlapping match and return them in a L<C<List>|/type/List>.\n\n=item :overlap\n\nFinds all matches including overlapping matches, but only returns one match from\neach starting position.\n\n=item :exhaustive\n\nFinds all possible matches of a regex, including overlapping matches and matches\nthat start at the same position.\n\n=item :st, :nd, :rd, :nth\n\nReturns the nth match in the string. The argument can be a L<C<Numeric>|/type/Numeric> or\nan L<C<Iterable>|/type/Iterable> producing monotonically increasing numbers (that is, the\nnext produced number must be larger than the previous one). The L<C<Iterable>|/type/Iterable>\nwill be lazily L<reified|/language/glossary#Reify> and if\nnon-monotonic sequence is encountered an exception will be thrown.\n\nIf L<C<Iterable>|/type/Iterable> argument is provided the return value and C<$/> variable\nwill be set to a possibly-empty L<C<List>|/type/List> of L<C<Match>|/type/Match> objects.\n\n=item :x\n\nTakes as an argument the number of matches to return, stopping once the\nspecified number of matches has been reached. The value must be a L<C<Numeric>|/type/Numeric> or\na L<C<Range>|/type/Range>; other values will cause C<.match> to return a L<C<Failure>|/type/Failure> containing\nan L<C<X::Str::Match::x>|/type/X::Str::Match::x> exception.\n\nExamples:\n=begin code\n\nsay \"properly\".match('perl');                     # OUTPUT: «｢perl｣␤»\nsay \"properly\".match(/p.../);                     # OUTPUT: «｢prop｣␤»\nsay \"1 2 3\".match([1,2,3]);                       # OUTPUT: «｢1 2 3｣␤»\nsay \"a1xa2\".match(/a./, :continue(2));            # OUTPUT: «｢a2｣␤»\nsay \"abracadabra\".match(/ a .* a /, :exhaustive);\n# OUTPUT: «(｢abracadabra｣ ｢abracada｣ ｢abraca｣ ｢abra｣ ｢acadabra｣ ｢acada｣ ｢aca｣ ｢adabra｣ ｢ada｣ ｢abra｣)␤»\nsay 'several words here'.match(/\\w+/,:global);    # OUTPUT: «(｢several｣ ｢words｣ ｢here｣)␤»\nsay 'abcdef'.match(/.*/, :pos(2));                # OUTPUT: «｢cdef｣␤»\nsay \"foo[bar][baz]\".match(/../, :1st);            # OUTPUT: «｢fo｣␤»\nsay \"foo[bar][baz]\".match(/../, :2nd);            # OUTPUT: «｢o[｣␤»\nsay \"foo[bar][baz]\".match(/../, :3rd);            # OUTPUT: «｢ba｣␤»\nsay \"foo[bar][baz]\".match(/../, :4th);            # OUTPUT: «｢r]｣␤»\nsay \"foo[bar][baz]bada\".match('ba', :x(2));       # OUTPUT: «(｢ba｣ ｢ba｣)␤»\n=end code\n\n=head2 method Numeric\n\n    method Numeric(Str:D: --> Numeric:D)\n\nCoerces the string to L<C<Numeric>|/type/Numeric> using semantics equivalent to L<val|/routine/val> routine.\nL<Fails|/routine/fail> with L<C<X::Str::Numeric>|/type/X::Str::Numeric> if the coercion to a number cannot be done.\n\nOnly Unicode characters with property C<Nd>, as well as leading and trailing\nwhitespace are allowed, with the special case of the empty string being coerced\nto C<0>. Synthetic codepoints (e.g. C<\"7\\x[308]\">) are forbidden.\n\nWhile C<Nl> and C<No> characters can be used as numeric literals in the\nlanguage, their conversion via C<Str.Numeric> will fail, by design; the same\nwill happen with synthetic numerics (composed of numbers and diacritic marks).\nSee L«unival|/routine/unival» if you need to coerce such characters to\nL<C<Numeric>|/type/Numeric>. +, - and the Unicode MINUS SIGN − are all allowed.\n\n=for code\n\" −33\".Numeric;       # OUTPUT: «-33␤»\n\n=head2 method Num\n\n    method Num(Str:D: --> Num:D)\n\nCoerces the string to L«C<Num>|/type/Num», using the same rules as\nL«C<Str.Numeric>|/type/Str#method_Numeric» and handling negative zero,\nC<-0e0>, and positive zero, C<0e0>.\n\n=begin code\nmy Str $s = \"-0/5\";\nsay (.self, .^name) given $s.Numeric;  # OUTPUT: «(0 Rat)␤»\nsay (.self, .^name) given $s.Num;      # OUTPUT: «(-0 Num)␤»\n=end code\n\n=head2 method Int\n\n    method Int(Str:D: --> Int:D)\n\nCoerces the string to L<C<Int>|/type/Int>, using the same rules as\nL«C<Str.Numeric>|/type/Str#method_Numeric».\n\n=head2 method Rat\n\n    method Rat(Str:D: --> Rational:D)\n\nCoerces the string to a L<C<Rat>|/type/Rat> object, using the same rules as\nL«C<Str.Numeric>|/type/Str#method_Numeric». If the denominator is larger\nthan 64-bits is it still kept and no degradation to L<C<Num>|/type/Num> occurs.\n\n=head2 method Bool\n\n    method Bool(Str:D: --> Bool:D)\n\nReturns C<False> if the string is empty, C<True> otherwise.\n\n=head2 routine parse-base\n\n    multi        parse-base(Str:D $num, Int:D $radix --> Numeric)\n    multi method parse-base(Str:D $num: Int:D $radix --> Numeric)\n\nPerforms the reverse of L«C<base>|/routine/base» by converting a string\nwith a base-C<$radix> number to its L«C<Numeric>|/type/Numeric»\nequivalent. Will L«C<fail>|/routine/fail» if radix is not in range C<2..36>\nor if the string being parsed contains characters that are not valid\nfor the specified base.\n\n    1337.base(32).parse-base(32).say; # OUTPUT: «1337␤»\n    'Raku'.parse-base(36).say;        # OUTPUT: «1273422␤»\n    'FF.DD'.parse-base(16).say;       # OUTPUT: «255.863281␤»\n\nSee also: L«syntax for number literals|/syntax/Number%20literals»\n\n=head2 routine parse-names\n\n    sub    parse-names(Str:D $names  --> Str:D)\n    method parse-names(Str:D $names: --> Str:D)\n\nB<DEPRECATED>. Use L<uniparse|/routine/uniparse> instead. Existed in Rakudo implementation as a proof of viability\nimplementation before being renamed and will be removed when 6.e language is released.\n\n=head2 routine uniparse\n\n    sub    uniparse(Str:D $names  --> Str:D)\n    method uniparse(Str:D $names: --> Str:D)\n\nTakes string with comma-separated Unicode names of characters and\nreturns a string composed of those characters. Will L«C<fail>|/routine/fail»\nif any of the characters' names are empty or not recognized. Whitespace\naround character names is ignored.\n\n    say \"I {uniparse 'TWO HEARTS'} Raku\"; # OUTPUT: «I 💕 Raku␤»\n    'TWO HEARTS, BUTTERFLY'.uniparse.say; # OUTPUT: «💕🦋␤»\n\nSee L<uniname|/routine/uniname> and L<uninames|/routine/uninames> for routines\nthat work in the opposite direction with a single codepoint and multiple\ncodepoints respectively.\n\nNote that unlike C<\\c[...]> construct available in string interpolation,\nC<uniparse> does not accept decimal numerical values. Use L<chr|/routine/chr> routine to\nconvert those:\n\n    say \"\\c[1337]\"; # OUTPUT: «Թ␤»\n    say '1337'.chr; # OUTPUT: «Թ␤»\n\nI<Note:> before being standardized in 2017.12, this routine was known\nunder its working name of L<parse-names|/routine/parse-names>. This denomination will be removed in the 6.e version.\n\n=head2 method samecase\n\n  multi method samecase(Str:D: Str:D $pattern --> Str:D)\n\nReturns a copy of the invocant with case information for each individual\ncharacter changed according to C<$pattern>.\n\nB<Note>: The pattern string can contain three types of characters,\ni.e. uppercase, lowercase and caseless. For a given character in\nC<$pattern> its case information determines the case of the corresponding\ncharacter in the result.\n\nIf the invocant is longer than C<$pattern>, the case information from\nthe last character of C<$pattern> is applied to the remaining characters\nof the invocant.\n\n    say \"raKu\".samecase(\"A_a_\"); # OUTPUT: «Raku␤»\n    say \"rAKU\".samecase(\"Ab\");   # OUTPUT: «Raku␤»\n\n=head2 routine split\n\n=for code :method\nmulti        split(  Str:D $delimiter, Str:D $input, $limit = Inf,\n  :$skip-empty, :$v, :$k, :$kv, :$p)\n=for code :method\nmulti        split(Regex:D $delimiter, Str:D $input, $limit = Inf,\n  :$skip-empty, :$v, :$k, :$kv, :$p)\n=for code :method\nmulti        split(List:D $delimiters, Str:D $input, $limit = Inf,\n  :$skip-empty, :$v, :$k, :$kv, :$p)\n=for code :method\nmulti method split(Str:D:   Str:D $delimiter, $limit = Inf,\n  :$skip-empty, :$v, :$k, :$kv, :$p)\n=for code :method\nmulti method split(Str:D: Regex:D $delimiter, $limit = Inf,\n  :$skip-empty, :$v, :$k, :$kv, :$p)\n=for code :method\nmulti method split(Str:D: List:D $delimiters, $limit = Inf,\n  :$skip-empty, :$v, :$k, :$kv, :$p)\n\nSplits a string up into pieces based on delimiters found in the string.\n\nIf C<$delimiter> is a string, it is used literally. An empty string\neffectively returns all characters of the string separately (plus an\nempty string at the begin and at the end).\n\nC<$delimiter> also can be passed as a L<C<Regex>|/type/Regex>.\n\nIf a list is used, then each of its elements\nwill be considered a delimiter based on its type as mentioned above.\n\nThe optional C<$limit> indicates in how many segments the string should be\nsplit, if possible.  It defaults to B<Inf> (or B<*>, whichever way you look at\nit), which means \"as many as possible\". Note that specifying negative limits\nwill not produce any meaningful results.\n\nA number of optional named parameters can be specified, which alter the\nresult being returned.  The C<:v>, C<:k>, C<:kv> and C<:p> named parameters\nall perform a special action with regards to the delimiter found.\n\n=item :skip-empty\n\nIf specified, do not return empty strings before or after a delimiter.\n\n=item :v\n\nAlso return the delimiter.  If the delimiter was a regular expression, then\nthis will be the associated L<C<Match>|/type/Match> object. Since this stringifies as the\ndelimiter string found, you can always assume it is the delimiter string if\nyou're not interested in further information about that particular match.\n\n=item :k\n\nAlso return the B<index> of the delimiter.  Only makes sense if a list of\ndelimiters was specified: in all other cases, this will be B<0>.\n\n=item :kv\n\nAlso return both the B<index> of the delimiter, as well as the delimiter.\n\n=item :p\n\nAlso return the B<index> of the delimiter and the delimiter as a L<C<Pair>|/type/Pair>.\n\nExamples:\n\n    say split(\";\", \"a;b;c\").raku;           # OUTPUT: «(\"a\", \"b\", \"c\").Seq␤»\n    say split(\";\", \"a;b;c\", :v).raku;       # OUTPUT: «(\"a\", \";\", \"b\", \";\", \"c\").Seq␤»\n    say split(\";\", \"a;b;c\", 2).raku;        # OUTPUT: «(\"a\", \"b;c\").Seq␤»\n    say split(\";\", \"a;b;c\", 2, :v).raku;    # OUTPUT: «(\"a\", \";\", \"b;c\").Seq␤»\n    say split(\";\", \"a;b;c,d\").raku;         # OUTPUT: «(\"a\", \"b\", \"c,d\").Seq␤»\n    say split(/\\;/, \"a;b;c,d\").raku;        # OUTPUT: «(\"a\", \"b\", \"c,d\").Seq␤»\n    say split(<; ,>, \"a;b;c,d\").raku;       # OUTPUT: «(\"a\", \"b\", \"c\", \"d\").Seq␤»\n    say split(/<[;,]>/, \"a;b;c,d\").raku;    # OUTPUT: «(\"a\", \"b\", \"c\", \"d\").Seq␤»\n    say split(<; ,>, \"a;b;c,d\", :k).raku;   # OUTPUT: «(\"a\", 0, \"b\", 0, \"c\", 1, \"d\").Seq␤»\n    say split(<; ,>, \"a;b;c,d\", :kv).raku;  # OUTPUT: «(\"a\", 0, \";\", \"b\", 0, \";\", \"c\", 1, \",\", \"d\").Seq␤»\n\n    say \"\".split(\"x\").raku;                 # OUTPUT: «(\"\",).Seq␤»\n    say \"\".split(\"x\", :skip-empty).raku;    # OUTPUT: «().Seq␤»\n\n    say \"abcde\".split(\"\").raku;             # OUTPUT: «(\"\", \"a\", \"b\", \"c\", \"d\", \"e\", \"\").Seq␤»\n    say \"abcde\".split(\"\",:skip-empty).raku; # OUTPUT: «(\"a\", \"b\", \"c\", \"d\", \"e\").Seq␤»\n\n=head2 routine comb\n\n    multi        comb(Str:D   $matcher, Str:D $input, $limit = Inf)\n    multi        comb(Regex:D $matcher, Str:D $input, $limit = Inf, Bool :$match)\n    multi        comb(Int:D $size, Str:D $input, $limit = Inf)\n    multi method comb(Str:D $input:)\n    multi method comb(Str:D $input: Str:D   $matcher, $limit = Inf)\n    multi method comb(Str:D $input: Regex:D $matcher, $limit = Inf, Bool :$match)\n    multi method comb(Str:D $input: Int:D $size, $limit = Inf)\n\nSearches for C<$matcher> in C<$input> and returns a L<C<Seq>|/type/Seq> of non-overlapping\nmatches limited to at most C<$limit> matches.\n\nIf C<$matcher> is a Regex, each L<C<Match>|/type/Match> object is converted to a C<Str>,\nunless C<$match> is set (available as of the 2020.01 release of the Rakudo\ncompiler).\n\nIf no matcher is supplied, a Seq of characters in the string is returned,\nas if the matcher was C<rx/./>.\n\nExamples:\n\n    say \"abc\".comb.raku;                 # OUTPUT: «(\"a\", \"b\", \"c\").Seq␤»\n    say \"abc\".comb(:match).raku;         # OUTPUT: «(｢a｣ ｢b｣ ｢c｣)␤»\n    say 'abcdefghijk'.comb(3).raku;      # OUTPUT: «(\"abc\", \"def\", \"ghi\", \"jk\").Seq␤»\n    say 'abcdefghijk'.comb(3, 2).raku;   # OUTPUT: «(\"abc\", \"def\").Seq␤»\n    say comb(/\\w/, \"a;b;c\").raku;        # OUTPUT: «(\"a\", \"b\", \"c\").Seq␤»\n    say comb(/\\N/, \"a;b;c\").raku;        # OUTPUT: «(\"a\", \";\", \"b\", \";\", \"c\").Seq␤»\n    say comb(/\\w/, \"a;b;c\", 2).raku;     # OUTPUT: «(\"a\", \"b\").Seq␤»\n    say comb(/\\w\\;\\w/, \"a;b;c\", 2).raku; # OUTPUT: «(\"a;b\",).Seq␤»\n    say comb(/.<(.)>/, \"<>[]()\").raku;   # OUTPUT: «(\">\", \"]\", \")\").Seq␤»\n\nIf the matcher is an integer value, C<comb> behaves as if the matcher\nwas C<rx/ . ** {1..$matcher} />, but which is optimized to be much faster.\n\nNote that a Regex matcher may control which portion of the matched text\nis returned by using features which explicitly set the top-level capture.\n\n    multi        comb(Pair:D $rotor, Str:D $input, $limit = Inf, Bool :$partial)\n    multi method comb(Str:D $input: Pair:D $rotor, $limit = Inf, Bool :$partial)\n\nAvailable as of 6.e language version (early implementation exists in Rakudo\ncompiler 2022.12+).  The C<rotor> pair indicates the number of characters\nto fetch as the key (the \"size\"), and the number of \"steps\" forward to take\nafterwards.  Its main intended use is to provide a way to create\nL<N-grams|https://en.wikipedia.org/wiki/N-gram> from strings in an efficient\nmanner.  By default only strings of the specified size will be produced.\nThis can be overridden by specifying the named argument C<:partial> with a\ntrue value.\n\nExamples:\n\n    say \"abcde\".comb(3 => -2);             # OUTPUT: «(abc bcd cde)␤»\n    say \"abcde\".comb(3 => -2, :partial);   # OUTPUT: «(abc bcd cde de e)␤»\n    say \"abcdefg\".comb(3 => -2, 2);        # OUTPUT: «(abc bcd)␤»\n    say comb(3 => -2, \"abcde\");            # OUTPUT: «(abc bcd cde)␤»\n    say comb(5 => -2, \"abcde\", :partial);  # OUTPUT: «(abc bcd cde de e)␤»\n    say comb(5 => -2, \"abcdefg\", 2);       # OUTPUT: «(abc bcd)␤»\n\n=head2 routine lines\n\n    multi method lines(Str:D: $limit, :$chomp = True)\n    multi method lines(Str:D: :$chomp = True)\n\nReturns a L<C<Seq>|/type/Seq> of lines. By default, it chomps line endings the same as a\ncall to C<$input.comb( / ^^ \\N* /, $limit )> would. To keep line endings,\nset the optional named parameter C<$chomp> to C<False>.\n\nExamples:\n\n    say lines(\"a\\nb\").raku;    # OUTPUT: «(\"a\", \"b\").Seq␤»\n    say lines(\"a\\nb\").elems;   # OUTPUT: «2␤»\n    say \"a\\nb\".lines.elems;    # OUTPUT: «2␤»\n    say \"a\\n\".lines.elems;     # OUTPUT: «1␤»\n\n    # Keep line endings\n    say lines(:!chomp, \"a\\nb\").raku;  # OUTPUT: «(\"a\\n\", \"b\").Seq␤»\n    say \"a\\n\".lines(:!chomp).elems;   # OUTPUT: «1␤»\n\nYou can limit the\nnumber of lines returned by setting the C<$limit> variable to a non-zero,\nnon-C<Infinity> value:\n\n    say <not there yet>.join(\"\\n\").lines( 2 ); # OUTPUT: «(not there)␤»\n\nB«DEPRECATED as of C<6.d> language», the C<:count> argument was used\nto return the total number of lines:\n\n    say <not there yet>.join(\"\\n\").lines( :count ); # OUTPUT: «3␤»\n\nUse L<elems|/routine/elems> call on the returned L<C<Seq>|/type/Seq> instead:\n\n    say <not there yet>.join(\"\\n\").lines.elems; # OUTPUT: «3␤»\n\n=head2 routine words\n\n    multi method words(Str:D: $limit)\n    multi method words(Str:D:)\n\nReturns a L<C<Seq>|/type/Seq> of non-whitespace bits, i.e. the same as a call to\nC<$input.comb( / \\S+ /, $limit )> would.\n\nExamples:\n\n    say \"a\\nb\\n\".words.raku;       # OUTPUT: «(\"a\", \"b\").Seq␤»\n    say \"hello world\".words.raku;  # OUTPUT: «(\"hello\", \"world\").Seq␤»\n    say \"foo:bar\".words.raku;      # OUTPUT: «(\"foo:bar\",).Seq␤»\n    say \"foo:bar\\tbaz\".words.raku; # OUTPUT: «(\"foo:bar\", \"baz\").Seq␤»\n\nIt can also be used as a subroutine, turning the first argument into the\ninvocant. C<$limit> is optional, but if it is provided (and not equal to\nC<Inf>), it will return only the first C<$limit> words.\n\n    say words(\"I will be very brief here\", 2); # OUTPUT: «(I will)␤»\n\n\n=head2 routine flip\n\n    multi        flip(Str:D  --> Str:D)\n    multi method flip(Str:D: --> Str:D)\n\nReturns the string reversed character by character.\n\nExamples:\n\n    \"Raku\".flip;  # OUTPUT: «ukaR»\n    \"ABBA\".flip;  # OUTPUT: «ABBA»\n\n=head2 method starts-with\n\n    multi method starts-with(Str:D: Str(Cool) $needle, :i(:$ignorecase), :m(:$ignoremark) --> Bool:D)\n\nReturns C<True> if the invocant is identical to or starts with C<$needle>.\n\n    say \"Hello, World\".starts-with(\"Hello\");     # OUTPUT: «True␤»\n    say \"https://raku.org/\".starts-with('ftp');  # OUTPUT: «False␤»\n\nSince Rakudo release 2020.02, if the optional named parameter\nC<:ignorecase>, or C<:i>, is specified, the comparison of the invocant\nand C<$needle> ignores the distinction between uppercase, lowercase\nand titlecase letters.\n\n    say \"Hello, World\".starts-with(\"hello\");              # OUTPUT: «False␤»\n    say \"Hello, World\".starts-with(\"hello\", :ignorecase); # OUTPUT: «True␤»\n\nSince Rakudo 2020.02, if the optional named parameter C<:ignoremark>,\nor C<:m>, is specified, the comparison of the invocant and C<$needle>\nonly considers base characters, and ignores additional marks such as\ncombining accents.\n\n    say \"abc\".starts-with(\"ä\");              # OUTPUT: «False␤»\n    say \"abc\".starts-with(\"ä\", :ignoremark); # OUTPUT: «True␤»\n\n=head2 method ends-with\n\n    multi method ends-with(Str:D: Str(Cool) $needle, :i(:$ignorecase), :m(:$ignoremark) --> Bool:D)\n\nReturns C<True> if the invocant is identical to or ends with C<$needle>.\n\n    say \"Hello, World\".ends-with('Hello');      # OUTPUT: «False␤»\n    say \"Hello, World\".ends-with('ld');         # OUTPUT: «True␤»\n\nSince Rakudo release 2020.02, if the optional named parameter\nC<:ignorecase>, or C<:i>, is specified, the comparison of the invocant\nand C<$needle> ignores the distinction between uppercase, lowercase\nand titlecase letters.\n\n    say \"Hello, World\".ends-with(\"world\");              # OUTPUT: «False␤»\n    say \"Hello, World\".ends-with(\"world\", :ignorecase); # OUTPUT: «True␤»\n\nSince Rakudo 2020.02, if the optional named parameter C<:ignoremark>,\nor C<:m>, is specified, the comparison of the invocant and C<$needle>\nonly considers base characters, and ignores additional marks such as\ncombining accents.\n\n    say \"abc\".ends-with(\"ç\");              # OUTPUT: «False␤»\n    say \"abc\".ends-with(\"ç\", :ignoremark); # OUTPUT: «True␤»\n\n=head2 method subst\n\n    multi method subst(Str:D: $matcher, $replacement = \"\", *%options)\n\nReturns the invocant string where C<$matcher> is replaced by C<$replacement>\n(or the original string, if no match was found). If no C<$replacement> is\nprovided, the empty string is used (i.e., matched string(s) are removed).\n\nThere is an in-place syntactic variant of C<subst> spelled\nC<s/matcher/replacement/> and with\nadverb following the C<s> or inside the matcher.\n\nC<$matcher> can be a L<C<Regex>|/type/Regex>, or a literal C<Str>. Non-Str matcher arguments of\ntype L<C<Cool>|/type/Cool> are coerced to C<Str> for literal matching. If a L<C<Regex>|/type/Regex>\nC<$matcher> is used, the L«C<$/> special variable|/syntax/$$SOLIDUS» will be set\nto L<C<Nil>|/type/Nil> (if no matches occurred), a L<C<Match>|/type/Match> object, or a L<C<List>|/type/List> of L<C<Match>|/type/Match>\nobjects (if multi-match options like C<:g> are used).\n\n=head3 Literal replacement substitution\n\n    my $some-string = \"Some foo\";\n    my $another-string = $some-string.subst(/foo/, \"string\"); # gives 'Some string'\n    $some-string.=subst(/foo/, \"string\"); # in-place substitution. $some-string is now 'Some string'\n\n    say \"multi-hyphenate\".subst(\"-\"); # OUTPUT: «multihyphenate␤»\n\n=head3 Callable\n\nThe replacement can be a L<C<Callable>|/type/Callable> in which the current L<C<Match>|/type/Match> object will\nbe placed in the C<$/> variable, as well as the C<$_> topic variable. Using a\nL<C<Callable>|/type/Callable> as replacement is how you can refer to any of the captures created\nin the regex:\n\n    # Using capture from $/ variable (the $0 is the first positional capture)\n    say 'abc123defg'.subst(/(\\d+)/, { \" before $0 after \" });\n    # OUTPUT: «abc before 123 after defg␤»\n\n    # Using capture from $/ variable (the $<foo> is a named capture)\n    say 'abc123defg'.subst(/$<foo>=\\d+/, { \" before $<foo> after \" });\n    # OUTPUT: «abc before 123 after defg␤»\n\n    # Using WhateverCode to operate on the Match given in $_:\n    say 'abc123defg'.subst(/(\\d+)/, \"[ \" ~ *.flip ~ \" ]\");\n    # OUTPUT: «abc[ 321 ]defg␤»\n\n    # Using a Callable to generate substitution without involving current Match:\n    my $i = 41;\n    my $str = \"The answer is secret.\";\n    say $str.subst(/secret/, {++$i}); # The answer to everything\n    # OUTPUT: «The answer is 42.␤»\n\n=head3 Adverbs\n\nThe following adverbs are supported\n\n=begin table\n\n    short                       | long        | meaning\n    ============================+=============+================\n    :g                          | :global     | tries to match as often as possible\n    :nth(Int|Callable|Whatever) |             | only substitute the nth match; aliases: :st, :nd, :rd, and :th\n    :ss                         | :samespace  | preserves whitespace on substitution\n    :ii                         | :samecase   | preserves case on substitution\n    :mm                         | :samemark   | preserves character marks (e.g. 'ü' replaced with 'o' will result in 'ö')\n    :x(Int|Range|Whatever)      |             | substitute exactly $x matches\n\n=end table\n\nNote that only in the C<s///> form C<:ii> implies C<:i> and C<:ss> implies\nC<:s>. In the method form, the C<:s> and C<:i> modifiers must be added to the\nregex, not the C<subst> method call.\n\n\n=head3 More Examples\n\nHere are other examples of usage:\n\n    my $str = \"Hey foo foo foo\";\n\n    say $str.subst(/foo/, \"bar\", :g);           # OUTPUT: «Hey bar bar bar␤»\n    say $str.subst(/\\s+/, :g);                  # OUTPUT: «Heyfoofoofoo␤»\n\n    say $str.subst(/foo/, \"bar\", :x(0));        # OUTPUT: «Hey foo foo foo␤»\n    say $str.subst(/foo/, \"bar\", :x(1));        # OUTPUT: «Hey bar foo foo␤»\n    # Can not match 4 times, so no substitutions made\n    say $str.subst(/foo/, \"bar\", :x(4));        # OUTPUT: «Hey foo foo foo␤»\n    say $str.subst(/foo/, \"bar\", :x(2..4));     # OUTPUT: «Hey bar bar bar␤»\n    # Replace all of them, identical to :g\n    say $str.subst(/foo/, \"bar\", :x(*));        # OUTPUT: «Hey bar bar bar␤»\n\n    say $str.subst(/foo/, \"bar\", :nth(3));      # OUTPUT: «Hey foo foo bar␤»\n    # Replace last match\n    say $str.subst(/foo/, \"bar\", :nth(*));      # OUTPUT: «Hey foo foo bar␤»\n    # Replace next-to-last last match\n    say $str.subst(/foo/, \"bar\", :nth(*-1));    # OUTPUT: «Hey foo bar foo␤»\n\nThe C<:nth> adverb has readable English-looking variants:\n\n    say 'ooooo'.subst: 'o', 'x', :1st; # OUTPUT: «xoooo␤»\n    say 'ooooo'.subst: 'o', 'x', :2nd; # OUTPUT: «oxooo␤»\n    say 'ooooo'.subst: 'o', 'x', :3rd; # OUTPUT: «ooxoo␤»\n    say 'ooooo'.subst: 'o', 'x', :4th; # OUTPUT: «oooxo␤»\n\n\n=head2 method subst-mutate\n\nB<NOTE:> I<<< C<.subst-mutate> is deprecated in the 6.d version, and will be\nremoved in future ones. You can use L<subst|/routine/subst> with L«C<.=> method\ncall assignment operator|/routine/.=» or L«C<s///> substitution\noperator|/language/operators#s///_in-place_substitution» instead. >>>\n\nWhere L<subst|/routine/subst> returns the modified string and leaves the\noriginal unchanged, it is possible to mutate the original string by using\nC<subst-mutate>. If the match is successful, the method returns a\nL<C<Match>|/type/Match> object representing the successful match, otherwise returns\nL<C<Nil>|/type/Nil>. If C<:nth> (or one of its aliases) with\nL<C<Iterable>|/type/Iterable> value, C<:g>, C<:global>, or C<:x> arguments are\nused, returns a L<C<List>|/type/List> of L<C<Match>|/type/Match> objects, or an empty\nL<C<List>|/type/List> if no matches occurred.\n\n    my $some-string = \"Some foo\";\n    my $match = $some-string.subst-mutate(/foo/, \"string\");\n    say $some-string;  # OUTPUT: «Some string␤»\n    say $match;        # OUTPUT: «｢foo｣␤»\n    $some-string.subst-mutate(/<[oe]>/, '', :g); # remove every o and e, notice the :g named argument from .subst\n\nIf a L<C<Regex>|/type/Regex> C<$matcher> is used, the\nL«C<$/> special variable|/syntax/$$SOLIDUS» will be set to L<C<Nil>|/type/Nil> (if no\nmatches occurred), a L<C<Match>|/type/Match> object, or a L<C<List>|/type/List> of L<C<Match>|/type/Match> objects (if\nmulti-match options like C<:g> are used).\n\n=head2 routine substr\n\n    multi        substr(Str:D $s, $from, $chars?  --> Str:D)\n    multi        substr(Str:D $s, Range  $from-to --> Str:D)\n    multi method substr(Str:D $s: $from, $chars?  --> Str:D)\n    multi method substr(Str:D $s: Range $from-to  --> Str:D)\n\nReturns a substring of the original string, between the indices specified by\nC<$from-to>'s endpoints (coerced to L<C<Int>|/type/Int>) or from index C<$from> and of\nlength C<$chars>.\n\nBoth C<$from> and C<$chars> can be specified as L<C<Callable>|/type/Callable> and the\nreturned value will be used as the value for the argument. C<$from> is invoked with the L<length|/routine/chars> of the original string, while C<$chars> is invoked with remaining character count after C<$from>. If C<$from> or\nC<$chars> are not L<C<Callable>|/type/Callable>, they'll be coerced to L<C<Int>|/type/Int>.\n\nIf C<$chars> is omitted or is larger than the available characters,\nthe string from C<$from> until the end of the string is returned.\nIf C<$from-to>'s starting index or C<$from> is less than\nzero, L<C<X::OutOfRange>|/type/X::OutOfRange> exception is thrown. The C<$from-to>'s ending index is\npermitted to extend past the end of string, in which case it will be equivalent\nto the index of the last character.\n\n    say substr(\"Long string\", 3..6);     # OUTPUT: «g st␤»\n    say substr(\"Long string\", 6, 3);     # OUTPUT: «tri␤»\n    say substr(\"Long string\", 6);        # OUTPUT: «tring␤»\n    say substr(\"Long string\", 6, *-1);   # OUTPUT: «trin␤»\n    say substr(\"Long string\", *-3, *-1); # OUTPUT: «in␤»\n\n=head2 method substr-eq\n\n    multi method substr-eq(Str:D:  Str(Cool) $test-string, Int(Cool) $from, :i(:$ignorecase), :m(:$ignoremark) --> Bool)\n    multi method substr-eq(Cool:D: Str(Cool) $test-string, Int(Cool) $from, :i(:$ignorecase), :m(:$ignoremark) --> Bool)\n\nReturns C<True> if the C<$test-string> exactly matches the C<String> object,\nstarting from the given initial index C<$from>.  For example, beginning with\nthe string C<\"foobar\">, the substring C<\"bar\"> will match from index 3:\n\n    my $string = \"foobar\";\n    say $string.substr-eq(\"bar\", 3);    # OUTPUT: «True␤»\n\nHowever, the substring C<\"barz\"> starting from index 3 won't match even\nthough the first three letters of the substring do match:\n\n    my $string = \"foobar\";\n    say $string.substr-eq(\"barz\", 3);   # OUTPUT: «False␤»\n\nNaturally, to match the entire string, one merely matches from index 0:\n\n    my $string = \"foobar\";\n    say $string.substr-eq(\"foobar\", 0); # OUTPUT: «True␤»\n\nSince Rakudo release 2020.02, if the optional named parameter\nC<:ignorecase>, or C<:i>, is specified, the comparison of the invocant\nand C<$test-string> ignores the distinction between uppercase,\nlowercase and titlecase letters.\n\n    say \"foobar\".substr-eq(\"Bar\", 3);              # OUTPUT: «False␤»\n    say \"foobar\".substr-eq(\"Bar\", 3, :ignorecase); # OUTPUT: «True␤»\n\nSince Rakudo release 2020.02, if the optional named parameter\nC<:ignoremark>, or C<:m>, is specified, the comparison of the\ninvocant and C<$test-string> only considers base characters, and\nignores additional marks such as combining accents.\n\n    say \"cliché\".substr-eq(\"che\", 3);              # OUTPUT: «False␤»\n    say \"cliché\".substr-eq(\"che\", 3, :ignoremark); # OUTPUT: «True␤»\n\nSince this method is inherited from the L<C<Cool>|/type/Cool> type, it also works on\nintegers.  Thus the integer C<42> will match the value C<342> starting from\nindex 1:\n\n    my $integer = 342;\n    say $integer.substr-eq(42, 1);      # OUTPUT: «True␤»\n\nAs expected, one can match the entire value by starting at index 0:\n\n    my $integer = 342;\n    say $integer.substr-eq(342, 0);     # OUTPUT: «True␤»\n\nAlso using a different value or an incorrect starting index won't match:\n\n    my $integer = 342;\n    say $integer.substr-eq(42, 3);      # OUTPUT: «False␤»\n    say $integer.substr-eq(7342, 0);    # OUTPUT: «False␤»\n\n=head2 method substr-rw\n\n    method substr-rw($from, $length = *)\n\nA version of C<substr> that returns a L<C<Proxy>|/type/Proxy> functioning as a\nwritable reference to a part of a string variable. Its first argument, C<$from>\nspecifies the index in the string from which a substitution should occur, and\nits last argument, C<$length> specifies how many characters are to be replaced.\nIf not specified, C<$length> defaults to the length of the string.\n\nFor example, in its method form, if one wants to take the string C<\"abc\">\nand replace the second character (at index 1) with the letter C<\"z\">, then\none does this:\n\n    my $string = \"abc\";\n    $string.substr-rw(1, 1) = \"z\";\n    $string.say;                         # OUTPUT: «azc␤»\n\nNote that new characters can be inserted as well:\n\n    my $string = 'azc';\n    $string.substr-rw(2, 0) = \"-Zorro-\"; # insert new characters BEFORE the character at index 2\n    $string.say;                         # OUTPUT: «az-Zorro-c␤»\n\nC<substr-rw> also has a function form, so the above examples can also be\nwritten like so:\n\n    my $string = \"abc\";\n    substr-rw($string, 1, 1) = \"z\";\n    $string.say;                          # OUTPUT: «azc␤»\n    substr-rw($string, 2, 0) = \"-Zorro-\";\n    $string.say;                          # OUTPUT: «az-Zorro-c␤»\n\nIt is also possible to alias the writable reference returned by C<substr-rw>\nfor repeated operations:\n\n    my $string = \"A character in the 'Flintstones' is: barney\";\n    $string ~~ /(barney)/;\n    my $ref := substr-rw($string, $0.from, $0.to-$0.from);\n    $string.say;\n    # OUTPUT: «A character in the 'Flintstones' is: barney␤»\n    $ref = \"fred\";\n    $string.say;\n    # OUTPUT: «A character in the 'Flintstones' is: fred␤»\n    $ref = \"wilma\";\n    $string.say;\n    # OUTPUT: «A character in the 'Flintstones' is: wilma␤»\n\n=head2 routine samemark\n\n    multi  samemark(Str:D $string, Str:D $pattern --> Str:D)\n    method samemark(Str:D: Str:D $pattern --> Str:D)\n\nReturns a copy of C<$string> with the mark/accent information for each\ncharacter changed such that it matches the mark/accent of the corresponding\ncharacter in C<$pattern>. If C<$string> is longer than C<$pattern>, the\nremaining characters in C<$string> receive the same mark/accent as the last\ncharacter in C<$pattern>. If C<$pattern> is empty no changes will be made.\n\nExamples:\n\n    say 'åäö'.samemark('aäo');                        # OUTPUT: «aäo␤»\n    say 'åäö'.samemark('a');                          # OUTPUT: «aao␤»\n\n    say samemark('Räku', 'a');                        # OUTPUT: «Raku␤»\n    say samemark('aöä', '');                          # OUTPUT: «aöä␤»\n\n=head2 method succ\n\n    method succ(Str:D: --> Str:D)\n\nReturns the string incremented by one.\n\nString increment is \"magical\". It searches for the last alphanumeric\nsequence that is not preceded by a dot, and increments it.\n\n    '12.34'.succ;      # OUTPUT: «13.34»\n    'img001.png'.succ; # OUTPUT: «img002.png»\n\nThe actual increment step works by mapping the last alphanumeric\ncharacter to a character range it belongs to, and choosing the next\ncharacter in that range, carrying to the previous letter on overflow.\n\n    'aa'.succ;   # OUTPUT: «ab»\n    'az'.succ;   # OUTPUT: «ba»\n    '109'.succ;  # OUTPUT: «110»\n    'α'.succ;    # OUTPUT: «β»\n    'a9'.succ;   # OUTPUT: «b0»\n\nString increment is Unicode-aware, and generally works for scripts where a\ncharacter can be uniquely classified as belonging to one range of characters.\n\n=head2 method pred\n\n    method pred(Str:D: --> Str:D)\n\nReturns the string decremented by one.\n\nString decrementing is \"magical\" just like string increment (see\nL<succ|/routine/succ>). It fails on underflow\n\n=for code\n'b0'.pred;           # OUTPUT: «a9»\n'a0'.pred;           # OUTPUT: Failure\n'img002.png'.pred;   # OUTPUT: «img001.png»\n\n=head2 routine ord\n\n    multi        ord(Str:D  --> Int:D)\n    multi method ord(Str:D: --> Int:D)\n\nReturns the codepoint number of the base characters of the first grapheme\nin the string.\n\nExample:\n\n    ord(\"A\"); # 65\n    \"«\".ord;  # 171\n\n=head2 method ords\n\n    multi method ords(Str:D: --> Seq)\n\nReturns a list of Unicode codepoint numbers that describe the codepoints making up the string.\n\nExample:\n\n    \"aå«\".ords; # (97 229 171)\n\nStrings are represented as graphemes. If a character in the string is represented by multiple\ncodepoints, then all of those codepoints will appear in the result of C<ords>. Therefore, the\nnumber of elements in the result may not always be equal to L<chars|/routine/chars>, but will be equal to\nL<codes|/routine/codes>; L<codes|/routine/codes> computes the codepoints in a different way, so the result might be faster.\n\nThe codepoints returned will represent the string in L<C<NFC>|/type/NFC>. See the L<C<NFD>|/type/NFD>, L<C<NFKC>|/type/NFKC>, and\nL<C<NFKD>|/type/NFKD> methods if other forms are required.\n\n=head2 method trans\n\n    multi method trans(Str:D: Pair:D \\what, *%n --> Str)\n    multi method trans(Str:D: *@changes, :complement(:$c), :squash(:$s), :delete(:$d) --> Str)\n\nReplaces one or many characters with one or many characters. Ranges are\nsupported, both for keys and values. Regexes work as keys. In case a list of\nkeys and values is used, substrings can be replaced as well. When called with\nC<:complement> anything but the matched value or range is replaced with a\nsingle value; with C<:delete> the matched characters without corresponding\nreplacement are removed. Combining C<:complement> and C<:delete> will remove\nanything but the matched values, I<unless replacement characters have been\nspecified>, in which case, C<:delete> would be ignored. The adverb C<:squash>\nwill reduce repeated matched characters to a single character.\n\nExample:\n\n    my $str = 'say $x<b> && $y<a>';\n    $str.=trans( '<' => '«' );\n    $str.=trans( '<' => '«', '>' => '»' );\n\n    $str.=trans( [ '<'   , '>'   , '&' ] =>\n                 [ '&lt;', '&gt;', '&amp;' ]);\n\n    $str.=trans( ['a'..'y'] => ['A'..'z'] );\n\n    \"abcdefghij\".trans(/<[aeiou]> \\w/ => '');                     # OUTPUT: «cdgh»\n\n    \"a123b123c\".trans(['a'..'z'] => 'x', :complement);            # OUTPUT: «axxxbxxxc»\n    \"aaa1123bb123c\".trans('a'..'z' => 'A'..'Z', :squash);         # OUTPUT: «A1123B123C»\n    \"aaa1123bb123c\".trans('a'..'z' => 'x', :complement, :squash); # OUTPUT: «aaaxbbxc»\n\nIn general, the strings will have the same length after the substitution:\n\n    say \"a123b123c\".trans('23' => '4');   # OUTPUT: «a144b144c␤»\n    say \"a123b123c\".trans('123' => 'þð'); # OUTPUT: «aþðþbþðþc␤»\n\nC<:squash> and C<:delete> will have the same effect in this case making it a\nstrict substitution:\n\n    say \"a123b123c\".trans('123' => 'þð', :squash); # OUTPUT: «aþðbþðc␤»\n    say \"a123b123c\".trans('123' => 'þð', :delete); # OUTPUT: «aþðbþðc␤»\n\nC<:delete> will also remove non-matched characters from the original string:\n\n    say \"abc\".trans(\"abc\".comb => 1..2, :delete);  # OUTPUT: «12␤»\n\n\nPlease note that the behavior of the two versions of the multi method is\nslightly different. The first form will transpose only one character if the\norigin is also one character:\n\n=begin code\nsay \"abcd\".trans( \"a\" => \"zz\" );  # OUTPUT: «zbcd␤»\nsay \"abcd\".trans( \"ba\" => \"yz\" ); # OUTPUT: «zycd␤»\n=end code\n\nIn the second case, behavior is as expected, since the origin is more than one\nchar long. However, if the L<C<Pair>|/type/Pair> in the multi method does not have a C<Str> as\nan origin or target, it is handled to the second multi method, and behavior\nchanges:\n\n    say \"abcd\".trans: [\"a\"] => [\"zz\"]; # OUTPUT: «zzbcd␤»\n\nIn this case, neither origin nor target in the L<C<Pair>|/type/Pair> are C<Str>; the method\nwith the L<C<Pair>|/type/Pair> signature then calls the second, making this call above\nequivalent to C«\"abcd\".trans: [\"a\"] => [\"zz\"],» (with the comma behind, making\nit a L<C<Positional>|/type/Positional>, instead of a L<C<Pair>|/type/Pair>), resulting in the behavior shown as\noutput.\n\n=head2 method indent\n\n    multi method indent(Int $steps where { $_ == 0 } )\n    multi method indent(Int $steps where { $_ > 0  } )\n    multi method indent($steps where { .isa(Whatever) || .isa(Int) && $_ < 0 } )\n\nIndents each line of the string by C<$steps>. If C<$steps> is negative,\nit outdents instead. If C<$steps> is L<C<*>|/routine/*>, then the string is\noutdented to the margin:\n\n    \"  indented by 2 spaces\\n    indented even more\".indent(*)\n        eq \"indented by 2 spaces\\n  indented even more\"\n\n=head2 method trim\n\n    method trim(Str:D: --> Str)\n\nRemove leading and trailing whitespace. It can be used both as a method\non strings and as a function. When used as a method it will return\nthe trimmed string. In order to do in-place trimming, one needs to write\nC<.=trim>\n\n\n    my $line = '   hello world    ';\n    say '<' ~ $line.trim ~ '>';        # OUTPUT: «<hello world>␤»\n    say '<' ~ trim($line) ~ '>';       # OUTPUT: «<hello world>␤»\n    $line.trim;\n    say '<' ~ $line ~ '>';             # OUTPUT: «<   hello world    >␤»\n    $line.=trim;\n    say '<' ~ $line ~ '>';             # OUTPUT: «<hello world>␤»\n\nSee also L<trim-trailing|/routine/trim-trailing> and L<trim-leading|/routine/trim-leading>.\n\n=head2 method trim-trailing\n\n    method trim-trailing(Str:D: --> Str)\n\nRemoves the whitespace characters from the end of a string. See also L<trim|/routine/trim>.\n\n=head2 method trim-leading\n\n    method trim-leading(Str:D: --> Str)\n\nRemoves the whitespace characters from the beginning of a string. See also L<trim|/routine/trim>.\n\n=head2 method NFC\n\n    method NFC(Str:D: --> NFC:D)\n\nReturns a codepoint string in L<C<NFC>|/type/NFC> format (Unicode\nNormalization Form C / Composed).\n\n=head2 method NFD\n\n    method NFD(Str:D: --> NFD:D)\n\nReturns a codepoint string in L<C<NFD>|/type/NFD> format (Unicode\nNormalization Form D / Decomposed).\n\n=head2 method NFKC\n\n    method NFKC(Str:D: --> NFKC:D)\n\nReturns a codepoint string in L<C<NFKC>|/type/NFKC> format (Unicode Normalization\nForm KC / Compatibility Composed).\n\n=head2 method NFKD\n\n    method NFKD(Str:D: --> NFKD:D)\n\nReturns a codepoint string in L<C<NFKD>|/type/NFKD> format (Unicode Normalization\nForm KD / Compatibility Decomposed).\n\n=head2 method ACCEPTS\n\n    multi method ACCEPTS(Str:D: $other)\n\nReturns C<True> if the string is L<the same as|/routine/eq> C<$other>.\n\n=head2 method Capture\n\n    method Capture()\n\nThrows C<X::Cannot::Capture>.\n\n=head2 routine val\n\n    multi val(*@maybevals)\n    multi val(Slip:D \\maybevals)\n    multi val(List:D \\maybevals)\n    multi val(Pair:D \\ww-thing)\n    multi val(\\one-thing)\n    multi val(Str:D $MAYBEVAL, :$val-or-fail)\n\nGiven a C<Str> that may be parsable as a numeric value, it will\nattempt to construct the appropriate L<allomorph|/language/glossary#Allomorph>,\nreturning one of L<C<IntStr>|/type/IntStr>, L<C<NumStr>|/type/NumStr>, L<C<RatStr>|/type/RatStr>\nor L<C<ComplexStr>|/type/ComplexStr> or a plain C<Str> if a numeric value cannot\nbe parsed.\n\n    say val(\"42\").^name;    # OUTPUT: «IntStr␤»\n    say val(\"42e0\").^name;  # OUTPUT: «NumStr␤»\n    say val(\"42.0\").^name;  # OUTPUT: «RatStr␤»\n    say val(\"42+0i\").^name; # OUTPUT: «ComplexStr␤»\n\nYou can use the plus and minus sign, as well as the Unicode \"Minus Sign\" as\npart of the String\n\n    say val(\"−42\");         # OUTPUT: «−42␤»\n\nWhile characters belonging to the Unicode categories C<Nl> (number\nletters) and C<No> (other numbers) can be used as numeric literals\nin the language, they will not be converted to a number by C<val>,\nby design, and using C<val> on them will produce a failure. The\nsame will happen with synthetic numerics (such as 7̈ ). See\nL«unival|/routine/unival» if you need to convert such characters to\nL<C<Numeric>|/type/Numeric>.\n\n=head2 method Version\n\n    method Version(Str:D: --> Version:D)\n\nAvailable as of the 2020.01 release of the Rakudo compiler.\n\nCoerces the string to L<C<Version>|/type/Version>.\n\nThis could be used for L<type coercion in\nsignature|/language/signatures#Coercion_type>, as for example:\n\n    sub f(Version(Str) $want-version) { say $want-version.^name };\n    f \"1.2.3\";  # OUTPUT: «Version␤»\n\n=head2 method Date\n\n    method Date(Str:D:)\n\nAvailable as of the 2020.05 release of the Rakudo compiler.\n\nCoerces a C<Str> to a L«C«Date»|/type/Date» object, provided the string is\nproperly formatted. C«Date(Str)» also works.\n\nExamples:\n\n    say '2015-11-24'.Date.year;  # OUTPUT: «2015␤»\n    say Date('2015-11-24').year; # OUTPUT: «2015␤»\n\n=head2 method DateTime\n\n    method DateTime(Str:D:)\n\nAvailable as of the 2020.05 release of the Rakudo compiler.\n\nCoerces a C<Str> to a L«C«DateTime»|/type/DateTime» object, provided the\nstring is properly formatted. C«DateTime(Str)» also works.\n\nExamples:\n\n    say ('2012-02-29T12:34:56Z').DateTime.hour; # OUTPUT: «12␤»\n    say DateTime('2012-02-29T12:34:56Z').hour;  # OUTPUT: «12␤»\n\nSince Rakudo release 2022.07, it is also possible to just specify a\n\"YYYY-MM-DD\" string to indicate midnight on the given date.\n\n    say \"2023-03-04\".DateTime;  # OUTPUT: «2023-03-04T00:00:00Z␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/StrDistance.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class StrDistance\n\n=SUBTITLE Contains the result of a string transformation.\n\nC<StrDistance> objects are used to represent the return of the\nL<string transformation|/language/operators#tr///_in-place_transliteration> operator.\n\n    say (($ = \"fold\") ~~ tr/old/new/).^name;  # OUTPUT: «StrDistance␤»\n\nA C<StrDistance> object will stringify to the resulting string after the\ntransformation, and will numify to the distance between the two strings.\n\n=begin code\nmy $str = \"fold\";\nmy $str-dist = ($str ~~ tr/old/new/);\nsay ~$str-dist;  # OUTPUT: «fnew␤»\nsay +$str-dist;  # OUTPUT: «3␤»\n=end code\n\n=head1 Methods\n\n=head2 method before\n\nThis is actually a class attribute, and called as a method returns the string\nbefore the transformation:\n\n=for code :preamble<my $str = \"fold\"; my $str-dist = ($str ~~ tr/old/new/); >\nsay $str-dist.before; # OUTPUT: «fold␤»\n\n=head2 method after\n\nAlso a class attribute, returns the string after the transformation:\n\n=for code :preamble<my $str = \"fold\"; my $str-dist = ($str ~~ tr/old/new/); >\nsay $str-dist.after;  # OUTPUT: «fnew␤»\n\n=head2 method Bool\n\nReturns C<True> if C<before> is different from C<after>.\n\n=head2 method Numeric\n\nReturns the distance as a number.\n\n=head2 method Int\n\n    multi method Int(StrDistance:D:)\n\nReturns the distance between the string before and after the transformation.\n\n=head2 method Str\n\n    multi method Str(StrDistance:D: --> Str)\n\nReturns an C<after> string value.\n\n    =begin code :preamble<my $str = \"fold\">\n    my $str-dist = ($str ~~ tr/old/new/);\n    say $str-dist.Str; # OUTPUT: «fnew␤»\n    say ~$str-dist;    # OUTPUT: «fnew␤»\n    =end code\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Stringy.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"basic\")\n\n=TITLE role Stringy\n\n=SUBTITLE String or object that can act as a string\n\n    role Stringy { ... }\n\nCommon role for string types (such as Str).\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Sub.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Sub\n\n=SUBTITLE Subroutine\n\n    class Sub is Routine { }\n\nA type for subroutines and operators. Subs are created with the C<sub>\ndeclarator keyword followed by an optional\nL<identifier|/language/syntax#Identifiers>. This\nL<short tutorial explains how operators are declared|/language/optut>.\nFor details of a sub's parameter list, see L<C<Signature>|/type/Signature>.\n\nNote that subs that go by the same name as\nL<coercers|/language/typesystem#Coercion> will not take precedence over\nthem. Use the C<&>-sigil to call them.\n\n    sub Int(Str $s){'what?'};\n    say [Int, Int('42'),&Int('42')];\n    # OUTPUT: «[(Int) 42 what?]␤»\n\nX<|Syntax,my (Sub)>X<|Syntax,our (Sub)>\nSubs can be nested and scoped with C<my> and C<our>, whereby C<my> is the\ndefault. A sub declared with C<my> cannot be reached from any outer scope. An\nC<our> scoped sub will not redefine a sub of the same name in the outer scope.\nAny sub can be accessed via a closure from any outer scope. For instance, in\nthis example\n\n    sub can-be-seener( $whatever ) {\n      my sub can-be-seen ( $objection ) {\n        return $whatever but $objection;\n      }\n      return &can-be-seen\n    }\n\n    my $objectioner = can-be-seener( \"Really?\");\n    say $objectioner(42).Int; # OUTPUT: «42␤»\n\nC<$objectioner> will contain the C<can-be-seen> subroutine, even if it has been\ndeclared in another scope; calling it with C<42> will return C<\"Really?\"> with\nthe number 42 mixed in, as shown in the last sentence.\n\n=head1 Operators\n\nOperators are also C<Sub>s. Their definition includes\nL<the category they belong to|/language/operators#Operator_classification>\nand their\nL<code, precedence and associativity|/language/functions#Defining_operators>.\nThe syntax used in their definition is an example of\nL<extended identifiers|/language/syntax#Extended_identifiers>.\n\nX<|Syntax,trait_mod (declarator)>\n=head1 Traits\n\nA C<Trait> is a sub that is applied at compile time to various objects like\nclasses, routines or L<containers|/language/phasers#index-entry-will_trait>. It\nis declared with the C<trait_mod> declarator followed by a colon and a string\nliteral containing the name of the trait. A single positional parameter defines\nthe type of the object that the trait is applied to. A single named argument\ndefines the secondary name and may carry arguments when the trait is called.\nTraits are a special grammar category and are allowed to be placed after most\nlanguage object names or parameter lists.\n\n    say 'start';\n    multi trait_mod:<is>(Sub $s, :$foo){\n        say \"⟨is foo⟩ has been called with ⟨$foo⟩ on {$s.WHICH}\";\n    }\n    sub bar() is foo<oi‽> {\n        say 'bar has been called'\n    }\n    bar();\n    # OUTPUT: «⟨is foo⟩ has been called with ⟨oi‽⟩ on Sub|47563000␤start␤bar has been called␤»\n\nUse L<destructuring|/language/signatures#Destructuring_arguments> to call traits\nwith complex arguments.\n\n    multi trait_mod:<is>(Variable $a, :@foo [$firstpos, *@restpos, :$named, *%restnameds]) {\n        say [$firstpos, @restpos, $named, %restnameds]\n    }\n    my $x is foo[1,2,3,:named<a>, :2b, :3c] = 1\n    # OUTPUT: «[1 [2 3] a {b => 2, c => 3}]␤»\n\nDespite its funky syntax, a trait is just a normal C<Sub>. We can apply traits\nto it (or even themselves) and we can apply traits to objects at runtime.\n\n    multi trait_mod:<is> (Sub $s, :$foo) is foo {\n        say 'is foo called'\n    }\n    sub bar {}\n    &trait_mod:<is>(&bar, :foo);\n    # OUTPUT: «is foo called␤is foo called␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Submethod.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Submethod\n\n=SUBTITLE Member function that is not inherited by subclasses\n\n    class Submethod is Routine {}\n\nA Submethod is a method that is not inherited by child classes. They are\ntypically used for per-class initialization and tear-down tasks which\nare called explicitly per class in an inheritance tree, usually for\nenforcing a particular order. For example object construction with the\nC<BUILD> submethod happens from the least-derived to most-derived, so\nthat the most-derived (child) classes can depend on the parent already\nbeing initialized.\n\nSubmethods are of type C<Submethod>, and are declared with the\nC<submethod> declarator:\n\n    class Area {\n        has $.size;\n        submethod BUILD(:$x, :$y, :$z) {\n            $!size = $x * $y * $z;\n        }\n    }\n\nSince submethods are not inherited, an interesting use case is precisely\nmethods that are going to be called from the I<standard> submethods such as\nC<BUILD> or C<TWEAK>.\n\n=begin code\nclass Hero {\n    has @.inventory;\n    has Str $.name;\n    submethod BUILD( :$!name, :@!inventory ) {\n        @!inventory = self.clean-inventory( @!inventory );\n    }\n    submethod clean-inventory( @inventory ) {\n        @!inventory.unique.sort\n    }\n}\n\nmy Hero $þor .= new( name => \"Þor\",\n                     inventory => ( \"Mjölnir\", \"Megingjörð\", \"Mjölnir\" ) );\nsay $þor.inventory;\n# OUTPUT: «[Megingjörð Mjölnir]␤»\n=end code\n\nInvoking these methods make sense only in the specific context of the\nsubmethod it is invoked from.\n\n=head1 Methods\n\n=head2 method gist\n\n    multi method gist(Submethod:D:)\n\nReturns the name of the submethod.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Supplier/Preserving.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Supplier::Preserving\n\n=SUBTITLE Cached live Supply factory\n\n    class Supplier::Preserving is Supplier { }\n\nThis is a factory for live L<C<Supply>|/type/Supply>-type objects, and it\nprovides the mechanism for emitting new values onto the supplies, whereby\nvalues are kept when no consumer has tapped into the L<C<Supply>|/type/Supply>. Any tapping\nwill consume the already stored and future values.\n\nStarting a preserving L<C<Supply>|/type/Supply> and consuming its values after it is C<done>:\n\n    my $p = Supplier::Preserving.new;\n    start for ^3 {\n        $p.emit($_);\n        LAST {\n            say „done after { now - BEGIN now}s“;\n            $p.done;\n        }\n    }\n    sleep 2;\n    react {\n        whenever $p.Supply { $_.say; }\n        whenever Promise.in(2) { done }\n    }\n    say „also done after { now - BEGIN now }s“\n\nWill output:\n\n=for code :lang<output>\ndone after 0.0638467s\n0\n1\n2\nalso done after 4.0534119s\n\n=head1 Methods\n\n=head2 method new\n\n    method new()\n\nThe L<C<Supplier>|/type/Supplier> constructor.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Supplier.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Supplier\n\n=SUBTITLE Live Supply factory\n\n    class Supplier { }\n\nThis is a factory for I<live> L<C<Supply>|/type/Supply> objects, which\nprovides the mechanism for emitting new values onto the supplies:\n\n    my $supplier = Supplier.new;\n    my $supply_1 = $supplier.Supply;\n    $supply_1.tap(-> $v { say \"One $v\" });\n    my $supply_2 = $supplier.Supply;\n    $supply_2.tap(-> $v { say \"Two $v\" });\n    $supplier.emit(42);\n\nWill output:\n\n=for code :lang<text>\nOne 42\nTwo 42\n\nI<on demand> supplies are created by the factory methods of the L<C<Supply>|/type/Supply>\nclass or by the C<supply> keyword. A mixture of a live and on-demand L<C<Supply>|/type/Supply> can\nbe created with a L<C<Supplier::Preserving>|/type/Supplier::Preserving>.\n\n=head1 Methods\n\n=head2 method new\n\n    method new()\n\nThe C<Supplier> constructor.\n\n=head2 method Supply\n\n    method Supply(Supplier:D: --> Supply)\n\nThis creates a new L<C<Supply>|/type/Supply> object to which any values which are emitted\non this supplier are passed. This is the factory for all C<live> supplies.\n\n=head2 method emit\n\n    method emit(Supplier:D: Mu \\value)\n\nSends the given value to all of the taps on all of the supplies created by\nL<C<Supply>|/type/Supply> on this C<Supplier>.\n\n=head2 method done\n\n    method done(Supplier:D:)\n\nCalls the C<done> callback on all the taps that have one.\n\n    my $supplier = Supplier.new;\n    my $supply   = $supplier.Supply;\n    $supply.tap(-> $v { say $v }, done => { say \"no more answers\" });\n    $supplier.emit(42);\n    $supplier.done;\n\nWill output:\n\n=for code :lang<text>\n42\nno more answers\n\n=head2 method quit\n\n    multi method quit(Supplier:D: Exception $ex)\n    multi method quit(Supplier:D: Str() $message)\n\nCalls the C<quit> callback on all the taps that have one, passing the\nexception to them. If called with a L<C<Str>|/type/Str> the exception will be an\nL<C<X::AdHoc>|/type/X::AdHoc> with the supplied message.\n\nThis is meant for shutting down a supply with an error.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Supply.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Supply\n\n=SUBTITLE Asynchronous data stream with multiple subscribers\n\n=for code :skip-test<Mandatory function to implement>\n    class Supply does Awaitable {}\n\nA supply is a thread-safe, asynchronous data stream like a\nL<C<Channel>|/type/Channel>, but it can have multiple subscribers\n(I<taps>) that all get the same values flowing through the supply.\n\nIt is a thread-safe implementation of the\nL<Observer Pattern|https://en.wikipedia.org/wiki/Observer_pattern>,\nand central to supporting reactive programming in Raku.\n\nThere are two types of Supplies: C<live> and C<on demand>. A C<live>\nsupply is like a TV broadcast: those who tune in don't get previously emitted\nvalues. An C<on-demand> broadcast is like a video streaming service:\neveryone who starts streaming a movie (taps a C<Supply>),\nalways starts it from the beginning (gets all the values),\nregardless of how many people are watching it right now.\n\nThus, when tapping into a\nC<live> supply, the tap will only see values that are flowing through the\nsupply B<after> the tap has been created. Such supplies are normally infinite\nin nature, such as mouse movements. Closing such a tap does not stop mouse\nevents from occurring, it just means that the values will go by unseen. All\ntappers see the same flow of values.\n\nA tap on an C<on demand> supply will initiate the production of values, and\ntapping the supply again may result in a new set of values. For example,\nC<Supply.interval> produces a fresh timer with the appropriate interval each\ntime it is tapped. If the tap is closed, the timer simply stops emitting values\nto that tap. Note that no history is kept for C<on-demand> supplies, instead,\nthe C<supply> block is run for each tap of the supply.\n\nA C<live> C<Supply> is obtained from the L<C<Supplier>|/type/Supplier>\nfactory method C<Supply>. New values are emitted by calling C<emit> on\nthe L<C<Supplier>|/type/Supplier> object.\n\n    my $supplier = Supplier.new;\n    my $supply = $supplier.Supply;\n    $supply.tap(-> $v { say \"$v\" });\n    $supplier.emit(42); # Will cause the tap to output \"42\"\n\nThe L<live method|#method live> returns C<True> on live supplies. Factory\nmethods such as L<interval|#method interval>, L<from-list|#method from-list>\nwill return I<on demand> supplies.\n\nA live C<Supply> that keeps values until tapped the first time can be created\nwith L<C<Supplier::Preserving>|/type/Supplier::Preserving>.\n\nFurther examples can be found in the L<concurrency page|/language/concurrency#Supplies>.\n\n=head1 Methods that return Taps\n\n=head2 method tap\n\n=for code\nmethod tap(Supply:D: &emit = -> $ { },\n        :&done = -> {},\n        :&quit = -> $ex { $ex.throw },\n        :&tap = -> $ {} )\n\nCreates a new tap (a kind of subscription if you will), in addition to all\nexisting taps. The first positional argument is a piece of code that will be\ncalled when a new value becomes available through the C<emit> call.\n\nThe C<&done> callback can be called in a number of cases: if a supply block is being tapped, when a C<done> routine is reached;\nif a supply block is being tapped, it will be automatically triggered if the supply block reaches the end;\nif the C<done> method is called on the parent L<C<Supplier>|/type/Supplier>\n(in the case of a supply block, if there are multiple Suppliers referenced by C<whenever>, they must\nall have their C<done> method invoked for this to trigger the C<&done> callback of the tap as the\nblock will then reach its end).\n\nThe C<&quit> callback is called if the tap is on a supply block which exits with an error. It is also\ncalled if the C<quit> method is invoked on the parent L<C<Supplier>|/type/Supplier> (in the case of a supply block any\none L<C<Supplier>|/type/Supplier> quitting with an uncaught exception will call the C<&quit> callback as the block will\nexit with an error). The error is passed as a parameter to the callback.\n\nThe C<&tap> callback is called once the L<C<Tap>|/type/Tap> object is created,\nwhich is passed as a parameter to the callback. The callback is called ahead of\nC<emit>/C<done>/C<quit>, providing a reliable way to get the L<C<Tap>|/type/Tap> object. One\ncase where this is useful is when the C<Supply> begins emitting values\nsynchronously, since the call to C<.tap> won't return the L<C<Tap>|/type/Tap> object until\nit is done emitting, preventing it from being stopped if needed.\n\nMethod C<tap> returns an object of type L<C<Tap>|/type/Tap>, on which you can\ncall the C<close> method to cancel the subscription.\n\n    my $s = Supply.from-list(0 .. 5);\n    my $t = $s.tap(-> $v { say $v }, done => { say \"no more ticks\" });\n\nProduces:\n\n=for code :lang<text>\n0\n1\n2\n3\n4\n5\nno more ticks\n\n=head2 method act\n\n    method act(Supply:D: &actor, *%others)\n\nCreates a tap on the given supply with the given code.  Differently from\nC<tap>, the given code is guaranteed to be executed by only one thread at\na time.\n\n=head1 Utility methods\n\n=head2 method Capture\n\n    method Capture(Supply:D: --> Capture:D)\n\nEquivalent to calling L«C<.List.Capture>|/type/List#method_Capture»\non the invocant.\n\n=head2 method Channel\n\n    method Channel(Supply:D: --> Channel:D)\n\nReturns a L<C<Channel>|/type/Channel> object that will receive all future values\nfrom the supply, and will be C<close>d when the Supply is done, and quit (shut\ndown with error) when the supply is quit.\n\n=head2 method Promise\n\n    method Promise(Supply:D: --> Promise:D)\n\nReturns a L<C<Promise>|/type/Promise> that will be kept when the C<Supply> is\nC<done>. If the C<Supply> also emits any values, then the L<C<Promise>|/type/Promise> will be\nkept with the final value. Otherwise, it will be kept with L<C<Nil>|/type/Nil>. If the\nC<Supply> ends with a C<quit> instead of a C<done>, then the L<C<Promise>|/type/Promise> will\nbe broken with that exception.\n\n    my $supplier = Supplier.new;\n    my $s = $supplier.Supply;\n    my $p = $s.Promise;\n    $p.then(-> $v { say \"got $v.result()\" });\n    $supplier.emit('cha');         # not output yet\n    $supplier.done();              # got cha\n\nThe L<C<Promise>|/type/Promise> method is most useful when dealing with supplies that will tend\nto produce just one value, when only the final value is of interest, or when\nonly completion (successful or not) is relevant.\n\n=head2 method live\n\n    method live(Supply:D: --> Bool:D)\n\nReturns C<True> if the supply is \"live\", that is, values are emitted to taps\nas soon as they arrive. Always returns C<True> in the default C<Supply> (but\nfor example on the supply returned from C<Supply.from-list> it's C<False>).\n\n    say Supplier.new.Supply.live;    # OUTPUT: «True␤»\n\n=head2 method schedule-on\n\n    method schedule-on(Supply:D: Scheduler $scheduler)\n\nRuns the emit, done and quit callbacks on the specified scheduler.\n\nThis is useful for GUI toolkits that require certain actions to be run from\nthe GUI thread.\n\n=head1 Methods that wait until the supply is done\n\n=head2 method wait\n\n    method wait(Supply:D:)\n\nTaps the C<Supply> it is called on, and blocks execution until the either the supply\nis C<done> (in which case it evaluates to the final value that was emitted on the\nC<Supply>, or L<C<Nil>|/type/Nil> if not value was emitted) or C<quit> (in which case it will throw\nthe exception that was passed to C<quit>).\n\n   my $s = Supplier.new;\n   start {\n     sleep 1;\n     say \"One second: running.\";\n     sleep 1;\n     $s.emit(42);\n     $s.done;\n   }\n   $s.Supply.wait;\n   say \"Two seconds: done\";\n\n=head2 method list\n\n    multi method list(Supply:D:)\n\nTaps the C<Supply> it is called on, and returns a lazy list that will be reified\nas the C<Supply> emits values. The list will be terminated once the C<Supply> is\nC<done>. If the C<Supply> C<quit>s, then an exception will be thrown once that\npoint in the lazy list is reached.\n\n=head2 method Seq\n\n    method Seq(Supply:D:)\n\nReturns a L<C<Seq>|/type/Seq> with an iterator containing the values that the C<Supply>\ncontains.\n\n=head2 method grab\n\n    method grab(Supply:D: &when-done --> Supply:D)\n\nTaps the C<Supply> it is called on. When it is C<done>, calls C<&when-done> and\nthen emits the list of values that it returns on the result C<Supply>. If the\noriginal C<Supply> C<quit>s, then the exception is immediately conveyed on the\nreturn C<Supply>.\n\n    my $s = Supply.from-list(4, 10, 3, 2);\n    my $t = $s.grab(&sum);\n    $t.tap(&say);           # OUTPUT: «19␤»\n\n=head2 method reverse\n\n    method reverse(Supply:D: --> Supply:D)\n\nTaps the C<Supply> it is called on. Once that C<Supply> emits C<done>, all of the\nvalues it emitted will be emitted on the returned C<Supply> in reverse order. If\nthe original C<Supply> C<quit>s, then the exception is immediately conveyed on the\nreturn C<Supply>.\n\n    my $s = Supply.from-list(1, 2, 3);\n    my $t = $s.reverse;\n    $t.tap(&say);           # OUTPUT: «3␤2␤1␤»\n\n=head2 method sort\n\n    method sort(Supply:D: &custom-routine-to-use? --> Supply:D)\n\nTaps the C<Supply> it is called on. Once that C<Supply> emits C<done>, all of the\nvalues that it emitted will be sorted, and the results emitted on the returned\nC<Supply> in the sorted order. Optionally accepts a comparator L<C<Block>|/type/Block>.\nIf the original C<Supply> C<quit>s, then the exception is immediately conveyed on the\nreturn C<Supply>.\n\n    my $s = Supply.from-list(4, 10, 3, 2);\n    my $t = $s.sort();\n    $t.tap(&say);           # OUTPUT: «2␤3␤4␤10␤»\n\n=head2 method collate\n\n    method collate(Supply:D:)\n\nTaps the C<Supply> it is called on. Once that C<Supply> emits C<done>,\nall of the values that it emitted will be sorted taking into account\nUnicode grapheme characteristics. A new C<Supply> is returned with\nthe sorted values emitted. See L<Any.collate|/type/Any#method_collate>\nfor more details on the collated sort.\n\n    my $s = Supply.from-list(<ä a o ö>);\n    my $t = $s.collate();\n    $t.tap(&say);           # OUTPUT: «a␤ä␤o␤ö␤»\n\n=head2 method reduce\n\n    method reduce(Supply:D: &with --> Supply:D)\n\nCreates a \"reducing\" supply, which will emit a single value with the same\nsemantics as L<List.reduce|/type/List#routine_reduce>.\n\n    my $supply = Supply.from-list(1..5).reduce({$^a + $^b});\n    $supply.tap(-> $v { say \"$v\" }); # OUTPUT: «15␤»\n\n=head1 Methods that return another Supply\n\n=head2 method from-list\n\n    method from-list(Supply:U: +@values --> Supply:D)\n\nCreates an on-demand supply from the values passed to this method.\n\n    my $s = Supply.from-list(1, 2, 3);\n    $s.tap(&say);           # OUTPUT: «1␤2␤3␤»\n\n=head2 method share\n\n    method share(Supply:D: --> Supply:D)\n\nCreates a live supply from an on-demand supply, thus making it possible to\nshare the values of the on-demand supply on multiple taps, instead of each\ntap seeing its own copy of all values from the on-demand supply.\n\n    # this says in turn: \"first 1\" \"first 2\" \"second 2\" \"first 3\" \"second 3\"\n    my $s = Supply.interval(1).share;\n    $s.tap: { \"first $_\".say };\n    sleep 1.1;\n    $s.tap: { \"second $_\".say };\n    sleep 2\n\n=head2 method flat\n\n    method flat(Supply:D: --> Supply:D)\n\nCreates a supply on which all of the values seen in the given supply are\nflattened before being emitted again.\n\n=head2 method do\n\n    method do(Supply:D: &do --> Supply:D)\n\nCreates a supply to which all values seen in the given supply, are emitted\nagain.  The given code, executed for its side-effects only, is guaranteed\nto be only executed by one thread at a time.\n\n=head2 method on-close\n\n    method on-close(Supply:D: &on-close --> Supply:D)\n\nReturns a new C<Supply> which will run C<&on-close> whenever a L<C<Tap>|/type/Tap>\nof that C<Supply> is closed. This includes if further operations are chained\non to the C<Supply>. (for example, C<$supply.on-close(&on-close).map(*.uc)>).\nWhen using a C<react> or C<supply> block, using the L<CLOSE|/language/phasers#CLOSE>\nphaser is usually a better choice.\n\n    my $s = Supplier.new;\n    my $tap = $s.Supply.on-close({ say \"Tap closed\" }).tap(\n        -> $v { say \"the value is $v\" },\n        done    => { say \"Supply is done\" },\n        quit    => -> $ex { say \"Supply finished with error $ex\" },\n    );\n\n    $s.emit('Raku');\n    $tap.close;        # OUTPUT: «Tap closed␤»\n\n=head2 method interval\n\n    method interval(Supply:U: $interval, $delay = 0, :$scheduler = $*SCHEDULER --> Supply:D)\n\nCreates a supply that emits a value every C<$interval> seconds, starting\nC<$delay> seconds from the call. The emitted value is an integer, starting from\n0, and is incremented by one for each value emitted.\n\nImplementations may treat too-small and negative values as lowest resolution they support,\npossibly warning in such situations; e.g. treating C<0.0001> as C<0.001>.\nFor 6.d language version, the minimal value specified is C<0.001>.\n\n=head2 method grep\n\n    method grep(Supply:D: Mu $test --> Supply:D)\n\nCreates a new supply that only emits those values from the original supply\nthat smartmatch against C<$test>.\n\n    my $supplier = Supplier.new;\n    my $all      = $supplier.Supply;\n    my $ints     = $all.grep(Int);\n    $ints.tap(&say);\n    $supplier.emit($_) for 1, 'a string', 3.14159;   # prints only 1\n\n=head2 method map\n\n    method map(Supply:D: &mapper --> Supply:D)\n\nReturns a new supply that maps each value of the given supply through\nC<&mapper> and emits it to the new supply.\n\n    my $supplier = Supplier.new;\n    my $all      = $supplier.Supply;\n    my $double   = $all.map(-> $value { $value * 2 });\n    $double.tap(&say);\n    $supplier.emit(4);           # OUTPUT: «8»\n\n=head2 method batch\n\n    method batch(Supply:D: :$elems, :$seconds, :$emit-timed --> Supply:D)\n\nCreates a new supply that batches the values of the given supply by either\nthe number of elements in the batch (using C<:elems>) or a duration\n(using C<:seconds>) or both.  Any remaining values are emitted in\na final batch when the supply is done.\n\nWhen C<:emit-timed> is specified, a timer will run, emitting\nwhatever is in the batch every given number of C<:seconds>, if the\nbatch contains any values.\n\nB<Note>: Since Rakudo release 2020.12, the C<:seconds> parameter has\na millisecond granularity: for example a 1 millisecond duration could\nbe specified as C<:seconds(0.001)>. Before Rakudo release 2020.12,\nthe C<:seconds> parameter had a second granularity.\n\n=head2 method elems\n\n    method elems(Supply:D: $seconds? --> Supply:D)\n\nCreates a new supply in which changes to the number of values seen are\nemitted.  It optionally also takes an interval (in seconds) if you only want\nto be updated every so many seconds.\n\n=head2 method head\n\n    multi method head(Supply:D:)\n    multi method head(Supply:D: Callable:D $limit)\n    multi method head(Supply:D: \\limit)\n\nCreates a \"head\" supply with the same semantics as L<List.head|/type/List#method_head>.\n\n    my $s = Supply.from-list(4, 10, 3, 2);\n    my $hs = $s.head(2);\n    $hs.tap(&say);           # OUTPUT: «4␤10␤»\n\nSince release 2020.07, A L<C<WhateverCode>|/type/WhateverCode> can be used also, again with the same\nsemantics as C<List.head>\n\n    my $s = Supply.from-list(4, 10, 3, 2, 1);\n    my $hs = $s.head( * - 2);\n    $hs.tap(&say);           # OUTPUT: «4␤10␤3␤»\n\n=head2 method tail\n\n    multi method tail(Supply:D:)\n    multi method tail(Supply:D: Callable:D $limit)\n    multi method tail(Supply:D: \\limit)\n\nCreates a \"tail\" supply with the same semantics as L<List.tail|/type/List#method_tail>.\n\n    my $s = Supply.from-list(4, 10, 3, 2);\n    my $ts = $s.tail(2);\n    $ts.tap(&say);           # OUTPUT: «3␤2␤»\n\nYou can call C<.tail> with L<C<Whatever>|/type/Whatever> or C<Inf>; which will return a new\nsupply equivalent to the initial one. Calling it with a L<C<WhateverCode>|/type/WhateverCode> will\nbe equivalent to skipping until that number.\n\n    my $s = Supply.from-list(4, 10, 3, 2);\n    my $ts = $s.tail( * - 2 );\n    $ts.tap(&say);           # OUTPUT: «3␤2␤»\n\nThis feature is only available from the 2020.07 release of Raku.\n\n=head2 method first\n\n    method first(Supply:D: :$end, |c)\n\nThis method creates a supply of the first element, or the last element if\nthe optional named parameter C<:end> is truthy, from a supply created by\ncalling the C<grep> method on the invocant, with any remaining arguments\nas parameters.\nIf there is no remaining argument, this method is equivalent to calling\non the invocant, without parameter, the C<head> or the C<tail> method,\naccording to named parameter C<:end>.\n\n    my $rand = supply { emit (rand × 100).floor for ^∞ };\n    my $first-prime = $rand.first: &is-prime;\n    # output the first prime from the endless random number supply $rand,\n    # then the $first-prime supply reaches its end\n    $first-prime.tap: &say;\n\n=head2 method split\n\n    multi method split(Supply:D: \\delimiter)\n    multi method split(Supply:D: \\delimiter, \\limit)\n\nThis method creates a supply of the values returned by the C<Str.split>\nmethod called on the string collected from the invocant.\nSee L«C<Str.split>|/type/Str#routine_split» for details on the\nC<\\delimiter> argument as well as available extra named parameters.\nThe created supply can be limited with the C<\\limit> argument, see\nL«C<.head>|#method head».\n\n    my $words = Supply.from-list(<Hello World From Raku!>);\n    my $s = $words.split(/ <?upper> /, 2, :skip-empty);\n    $s.tap(&say); # OUTPUT: «Hello␤World␤»\n\n=head2 method rotate\n\n    method rotate(Supply:D: $rotate = 1)\n\nCreates a supply with elements rotated to the left when C<$rotate>\nis positive or to the right otherwise, in which case the invocant is\ntapped on before a new supply is returned.\n\n    my $supply = Supply.from-list(<a b c d e>).rotate(2);\n    $supply.tap(&say); # OUTPUT: «c␤d␤e␤a␤b␤»\n\nB<Note>: Available since Rakudo 2020.06.\n\n=head2 method rotor\n\n    method rotor(Supply:D: @cycle --> Supply:D)\n\nCreates a \"rotoring\" supply with the same semantics as L<List.rotor|/type/List#routine_rotor>.\n\n=head2 method delayed\n\n    method delayed(Supply:D: $seconds, :$scheduler = $*SCHEDULER --> Supply:D)\n\nCreates a new supply in which all values flowing through the given supply\nare emitted, but with the given delay in seconds.\n\n=head2 method throttle\n\n=for code :method\nmulti method throttle(Supply:D:\n      Int()  $elems,\n      Real() $seconds,\n      Real() $delay  = 0,\n      :$scheduler    = $*SCHEDULER,\n      :$control,\n      :$status,\n      :$bleed,\n      :$vent-at,\n    )\n\n=for code :method\nmulti method throttle(Supply:D:\n      Int()  $elems,\n      Callable:D $process,\n      Real() $delay = 0,\n      :$scheduler   = $*SCHEDULER,\n      :$control,\n      :$status,\n      :$bleed,\n      :$vent-at,\n    )\n\nArguments to C<.throttle> are defined as follows:\n\n=begin table\nArgument                  | Meaning\n========================================================================\n  $limit,                 | values / time or simultaneous processing\n  $seconds or $process    | time-unit / code to process simultaneously\n  $delay = 0,             | initial delay before starting, in seconds\n  :$control,              | supply to emit control messages on (optional)\n  :$status,               | supply to tap status messages from (optional)\n  :$bleed,                | supply to bleed messages to (optional)\n  :$vent-at,              | bleed when so many buffered (optional)\n  :$scheduler,            | scheduler to use, default $*SCHEDULER\n=end table\n\nThis method produces a C<Supply> from a given one, but makes sure the number of\nmessages passed through is limited.\n\nIt has two modes of operation: per time-unit or by maximum number of\nexecutions of a block of code: this is determined by the type of the second\npositional parameter.\n\nThe first positional parameter specifies the limit that should be applied.\n\nIf the second positional parameter is a L<C<Callable>|/type/Callable>, then the limit indicates\nthe maximum number of parallel processes executing the Callable, which is\ngiven the value that was received.  The emitted values in this case will be\nthe L<C<Promise>|/type/Promise>s that were obtained from C<start>ing the L<C<Callable>|/type/Callable>.\n\nIf the second positional parameter is a real number, it is interpreted as\nthe time-unit (in seconds).  If you specify B<.1> as the value, then it makes\nsure you don't exceed the limit for every tenth of a second.\n\nIf the limit is exceeded, then incoming messages are buffered until there\nis room to pass on / execute the Callable again.\n\nThe third positional parameter is optional: it indicates the number of\nseconds the throttle will wait before passing on any values.\n\nThe C<:control> named parameter optionally specifies a Supply that you can\nuse to control the throttle while it is in operation.  Messages that\ncan be sent, are strings in the form of \"key:value\".  Please see below\nfor the types of messages that you can send to control the throttle.\n\nThe C<:status> named parameter optionally specifies a Supply that will receive\nany status messages.  If specified, it will at least send one status message\nafter the original Supply is exhausted.  See L<status message|#status_message> below.\n\nThe C<:bleed> named parameter optionally specifies a Supply that will receive\nany values that were either explicitly bled (with the B<bleed> control\nmessage), or automatically bled (if there's a B<vent-at> active).\n\nThe C<:vent-at> named parameter indicates the number of values that may be\nbuffered before any additional value will be routed to the C<:bleed> Supply.\nDefaults to 0 if not specified (causing no automatic bleeding to happen).\nOnly makes sense if a C<:bleed> Supply has also been specified.\n\nThe C<:scheduler> named parameter indicates the scheduler to be used.  Defaults\nto C<$*SCHEDULER>.\n\n=head3 control messages\n\nThese messages can be sent to the C<:control> Supply.  A control message\nconsists of a string of the form \"key: value\", e.g. \"limit: 4\".\n\n=item limit\n\nChange the number of messages (as initially given in the first positional)\nto the value given.\n\n=item bleed\n\nRoute the given number of buffered messages to the C<:bleed> Supply.\n\n=item vent-at\n\nChange the maximum number of buffered values before automatic bleeding\ntakes place.  If the value is lower than before, will cause immediate\nrerouting of buffered values to match the new maximum.\n\n=item status\n\nSend a status message to the C<:status> Supply with the given id.\n\n=head3 status message\n\nThe status return message is a hash with the following keys:\n\n=item allowed\n\nThe current number of messages / callables that is still allowed to be\npassed / executed.\n\n=item bled\n\nThe number of messages routed to the C<:bleed> Supply.\n\n=item buffered\n\nThe number of messages currently buffered because of overflow.\n\n=item emitted\n\nThe number of messages emitted (passed through).\n\n=item id\n\nThe id of this status message (a monotonically increasing number).  Handy\nif you want to log status messages.\n\n=item limit\n\nThe current limit that is being applied.\n\n=item vent-at\n\nThe maximum number of messages that may be buffered before they're\nautomatically re-routed to the C<:bleed> Supply.\n\n=head3 Examples\n\nHave a simple piece of code announce when it starts running asynchronously,\nwait a random amount of time, then announce when it is done.  Do this 6 times,\nbut don't let more than 3 of them run simultaneously.\n\n  my $s = Supply.from-list(^6);  # set up supply\n  my $t = $s.throttle: 3,        # only allow 3 at a time\n  {                              # code block to run\n      say \"running $_\";          # announce we've started\n      sleep rand;                # wait some random time\n      say \"done $_\"              # announce we're done\n  }                              # don't need ; because } at end of line\n  $t.wait;                       # wait for the supply to be done\n\nand the result of one run will be:\n\n=for code :lang<text>\nrunning 0\nrunning 1\nrunning 2\ndone 2\nrunning 3\ndone 1\nrunning 4\ndone 4\nrunning 5\ndone 0\ndone 3\ndone 5\n\n=head2 method stable\n\n    method stable(Supply:D: $time, :$scheduler = $*SCHEDULER --> Supply:D)\n\nCreates a new supply that only passes on a value flowing through the given\nsupply if it wasn't superseded by another value in the given C<$time> (in\nseconds). Optionally uses another scheduler than the default scheduler,\nusing the C<:scheduler> parameter.\n\nTo clarify the above, if, during the timeout C<$time>, additional values\nare emitted to the L<C<Supplier>|/type/Supplier> all but the last one will be thrown away.\nEach time an additional value is emitted to the L<C<Supplier>|/type/Supplier>, during the\ntimeout, C<$time> is reset.\n\nThis method can be quite useful when handling UI input, where it is not desired\nto perform an operation until the user has stopped typing for a while rather\nthan on every keystroke.\n\n=begin code\nmy $supplier = Supplier.new;\nmy $supply1 = $supplier.Supply;\n$supply1.tap(-> $v { say \"Supply1 got: $v\" });\n$supplier.emit(42);\n\nmy Supply $supply2 = $supply1.stable(5);\n$supply2.tap(-> $v { say \"Supply2 got: $v\" });\nsleep(3);\n$supplier.emit(43);  # will not be seen by $supply2 but will reset $time\n$supplier.emit(44);\nsleep(10);\n# OUTPUT: «Supply1 got: 42␤Supply1 got: 43␤Supply1 got: 44␤Supply2 got: 44␤»\n=end code\n\nAs can be seen above, C<$supply1> received all values emitted to the L<C<Supplier>|/type/Supplier>\nwhile C<$supply2> only received one value. The 43 was thrown away because it\nwas followed by another 'last' value 44 which was retained and sent to C<$supply2>\nafter approximately eight seconds, this due to the fact that the timeout C<$time> was\nreset after three seconds.\n\n=head2 method produce\n\n    method produce(Supply:D: &with --> Supply:D)\n\nCreates a \"producing\" supply with the same semantics as L<List.produce|/type/List#routine_produce>.\n\n    my $supply = Supply.from-list(1..5).produce({$^a + $^b});\n    $supply.tap(-> $v { say \"$v\" }); # OUTPUT: «1␤3␤6␤10␤15␤»\n\n=head2 method lines\n\n    method lines(Supply:D: :$chomp = True --> Supply:D)\n\nCreates a supply that will emit the characters coming in line by line from a\nsupply that's usually created by some asynchronous I/O operation. The optional\nC<:chomp> parameter indicates whether to remove line separators: the default is\nC<True>.\n\n=head2 method words\n\n    method words(Supply:D: --> Supply:D)\n\nCreates a supply that will emit the characters coming in word for word from a\nsupply that's usually created by some asynchronous I/O operation.\n\n    my $s = Supply.from-list(\"Hello Word!\".comb);\n    my $ws = $s.words;\n    $ws.tap(&say);           # OUTPUT: «Hello␤Word!␤»\n\n=head2 method unique\n\n    method unique(Supply:D: :$as, :$with, :$expires --> Supply:D)\n\nCreates a supply that only provides unique values, as defined\nby the optional C<:as> and C<:with> parameters (same as with\nL<C<unique>|/type/independent-routines#routine_unique>).  The optional\nC<:expires> parameter how long to wait (in seconds) before \"resetting\"\nand not considering a value to have been seen, even if it's the same as\nan old value.\n\n=head2 method repeated\n\n    method repeated(Supply:D: :&as, :&with)\n\nCreates a supply that only provides repeated values, as defined\nby the optional C<:as> and C<:with> parameters (same as with\nL<C<unique>|/type/independent-routines#routine_unique>).\n\n    my $supply = Supply.from-list(<a A B b c b C>).repeated(:as(&lc));\n    $supply.tap(&say);           # OUTPUT: «A␤b␤b␤C␤»\n\nSee L<C<repeated>|/type/independent-routines#routine_repeated>\nfor more examples that use its sub form.\n\nB<Note>: Available since version 6.e (L<Rakudo|/language/glossary#Rakudo> 2020.01 and later).\n\n=head2 method squish\n\n    method squish(Supply:D: :$as, :$with --> Supply:D)\n\nCreates a supply that only provides unique values, as defined\nby the optional C<:as> and C<:with> parameters (same as with\nL<C<squish>|/type/independent-routines#routine_squish>).\n\n=head2 method max\n\n    method max(Supply:D: &custom-routine-to-use = &infix:<cmp> --> Supply:D)\n\nCreates a supply that only emits values from the given supply if they are\nlarger than any value seen before. In other words, from a continuously\nascending supply it will emit all the values. From a continuously descending\nsupply it will only emit the first value. The optional parameter specifies\nthe comparator, just as with L<Any.max|/type/Any#routine_max>.\n\n=head2 method min\n\n    method min(Supply:D: &custom-routine-to-use = &infix:<cmp> --> Supply:D)\n\nCreates a supply that only emits values from the given supply if they are\nsmaller than any value seen before.  In other words, from a continuously\ndescending supply it will emit all the values.  From a continuously ascending\nsupply it will only emit the first value.  The optional parameter specifies\nthe comparator, just as with L<Any.min|/type/Any#routine_min>.\n\n=head2 method minmax\n\n    method minmax(Supply:D: &custom-routine-to-use = &infix:<cmp> --> Supply:D)\n\nCreates a supply that emits a Range every time a new minimum or maximum\nvalues is seen from the given supply.  The optional parameter specifies\nthe comparator, just as with L<Any.minmax|/type/Any#routine_minmax>.\n\n=head2 method skip\n\n    method skip(Supply:D: Int(Cool) $number = 1 --> Supply:D)\n\nReturns a new C<Supply> which will emit all values from the given C<Supply>\nexcept for the first C<$number> values, which will be thrown away.\n\n=for code\nmy $supplier = Supplier.new;\nmy $supply = $supplier.Supply;\n$supply = $supply.skip(3);\n$supply.tap({ say $_ });\n$supplier.emit($_) for 1..10; # OUTPUT: «4␤5␤6␤7␤8␤9␤10␤»\n\n=head2 method start\n\n    method start(Supply:D: &startee --> Supply:D)\n\nCreates a supply of supplies. For each value in the original supply, the code\nobject is scheduled on another thread, and returns a supply either of a single\nvalue (if the code succeeds), or one that quits without a value (if the code\nfails).\n\nThis is useful for asynchronously starting work that you don't block on.\n\nUse C<migrate> to join the values into a single supply again.\n\n=head2 method migrate\n\n    method migrate(Supply:D: --> Supply:D)\n\nTakes a C<Supply> which itself has values that are of type C<Supply> as input. Each\ntime the outer C<Supply> emits a new C<Supply>, this will be tapped and its values\nemitted. Any previously tapped C<Supply> will be closed. This is useful for migrating\nbetween different data sources, and only paying attention to the latest one.\n\nFor example, imagine an application where the user can switch between different\nstocks. When they switch to a new one, a connection is established to a web socket\nto get the latest values, and any previous connection should be closed. Each stream\nof values coming over the web socket would be represented as a Supply, which\nthemselves are emitted into a Supply of latest data sources to watch.\nThe C<migrate> method could be used to flatten this supply of supplies into a single\nSupply of the current values that the user cares about.\n\nHere is a simple simulation of such a program:\n\n=begin code\nmy Supplier $stock-sources .= new;\n\nsub watch-stock($symbol) {\n    $stock-sources.emit: supply {\n        say \"Starting to watch $symbol\";\n        whenever Supply.interval(1) {\n            emit \"$symbol: 111.\" ~ 99.rand.Int;\n        }\n        CLOSE say \"Lost interest in $symbol\";\n    }\n}\n\n$stock-sources.Supply.migrate.tap: *.say;\n\nwatch-stock('GOOG');\nsleep 3;\nwatch-stock('AAPL');\nsleep 3;\n=end code\n\nWhich produces output like:\n\n=begin code :lang<text>\nStarting to watch GOOG\nGOOG: 111.67\nGOOG: 111.20\nGOOG: 111.37\nLost interest in GOOG\nStarting to watch AAPL\nAAPL: 111.55\nAAPL: 111.6\nAAPL: 111.6\n=end code\n\n=head1 Methods that combine supplies\n\n=head2 method merge\n\n    method merge(Supply @*supplies --> Supply:D)\n\nCreates a supply to which any value seen from the given supplies, is emitted.\nThe resulting supply is done only when all given supplies are done.  Can also\nbe called as a class method.\n\n=head2 method zip\n\n    method zip(**@s, :&with)\n\nCreates a supply that emits combined values as soon as there is a new value\nseen on B<all> of the supplies.  By default, L<C<List>|/type/List>s are\ncreated, but this can be changed by specifying your own combiner with the\nC<:with> parameter.  The resulting supply is done as soon as B<any> of the given\nsupplies are done.  Can also be called as a class method.\n\nThis can also be used as a class method; in case it's used as an object\nmethod the corresponding supply will be one of the supplies combined (with no\nspecial treatment).\n\n=head2 method zip-latest\n\n    method zip-latest(**@s, :&with, :$initial )\n\nCreates a supply that emits combined values as soon as there is a new value\nseen on B<any> of the supplies.  By default, L<C<List>|/type/List>s are\ncreated, but this can be changed by specifying your own combiner with the\nC<:with> parameter.  The optional :initial parameter can be used to indicate\nthe initial state of the combined values.  By default, all supplies have to\nhave at least one value emitted on them before the first combined values is\nemitted on the resulting supply.  The resulting supply is done as soon as\nB<any> of the given supplies are done.  Can also be called as a class method.\n\n=head1 I/O features exposed as supplies\n\n=head2 sub signal\n\n    sub signal(*@signals, :$scheduler = $*SCHEDULER)\n\nCreates a supply for the Signal enums (such as SIGINT) specified, and an\noptional C<:scheduler> parameter.  Any signals received, will be emitted on\nthe supply.  For example:\n\n    signal(SIGINT).tap( { say \"Thank you for your attention\"; exit 0 } );\n\nwould catch Control-C, thank you, and then exit.\n\nTo go from a signal number to a X<Signal|Reference,Signal>, you can do something like this:\n\n    signal(Signal(2)).tap( -> $sig { say \"Received signal: $sig\" } );\n\nThe list of supported signals can be found by checking C<Signal::.keys> (as\nyou would any enum). For more details on how enums work see\nL<enum|/language/typesystem#enum>.\n\nB<Note:> L<Rakudo|/language/glossary#Rakudo> versions up to 2018.05\nhad a bug due to which numeric values of signals were incorrect on\nsome systems. For example, C<Signal(10)> was returning C<SIGBUS> even\nif it was actually C<SIGUSR1> on a particular system. That being said,\nusing C<signal(SIGUSR1)> was working as expected on all Rakudo\nversions except 2018.04, 2018.04.1 and 2018.05, where the intended\nbehavior can be achieved by using C<signal(SIGBUS)> instead. These\nissues are resolved in Rakudo releases after 2018.05.\n\n=head2 method IO::Notification.watch-path\n\n=for code\nmethod watch-path($path --> Supply:D)\n\nCreates a supply to which the OS will emit values to indicate changes on the\nfilesystem for the given path.  Also has a shortcut with the C<watch> method\non an IO object, like this:\n\n=for code\nIO::Notification.watch-path(\".\").act( { say \"$^file changed\" } );\n\".\".IO.watch.act(                     { say \"$^file changed\" } );   # same\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Systemic.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"domain-specific\")\n\n=TITLE role Systemic\n\n=SUBTITLE Information related to the build system\n\nBuilt-in class for providing built system related information.  Usually accessed\nthrough dynamic variables mixing this role such as the\nL«C<$*KERNEL>|/language/variables#Dynamic_variables»,\nL«C<$*VM>|/language/variables#Dynamic_variables», or\nL«C<$*RAKU>|/language/variables#Dynamic_variables».\n\n\n=head1 Methods\n\n=head2 method auth\n\nInstance method returning the \"auth\" (as in \"author\" or \"authority\") of the\nobject. Returns \"unknown\" if the \"auth\" could not be established.\n\n=head2 method config\n\nInstance returning a hash with object configuration information. Subject to\nchange without notice, but can be helpful in environments where only one type of\nvirtual machine is in use, or to find about the configuration of any other\nobject that mixes in this role.\n\n=head2 method desc\n\nInstance method returning the \"desc\" (as in \"description\") of the VM object.\nReturns a L<C<Str>|/type/Str> type object if the \"desc\" could not be established.\n\n=head2 method name\n\nInstance method returning the name of the object.\n\n=head2 method signature\n\nInstance method returning the signature of the object. Returns a\nL<C<Blob>|/type/Blob> type object if the signature could not be established.\n\n=head2 method version\n\nInstance method returning the version of the object as a\nL<C<Version>|/type/Version> object. Returns a L<C<Version>|/type/Version> object \"unknown\" if the\nversion could not be established.\n\n=head2 method gist\n\n    method gist( Systemic:D: )\n\nInstance method returning the name and version of the object.\n\n    say $*RAKU.gist; # OUTPUT: «Raku (6.d)␤»\n\nC<$*RAKU> is an object of the L<C<Raku>|/type/Raku> type, which mixes in this role\nand thus implements this method.\n\n=head2 method Str\n\n    method Str\n\nInstance method returning the name of the object.\n\n    say $*RAKU.Str; # OUTPUT: «Raku␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Tap.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Tap\n\n=SUBTITLE Subscription to a Supply\n\n    class Tap {}\n\nA Tap is a subscription to a L<C<Supply>|/type/Supply>.\n\n    my $s = Supplier.new;\n    my $tap = $s.Supply.on-close({ say \"Tap closed\" }).tap(\n        -> $v { say \"the value is $v\" },\n        done    => { say \"Supply is done\" },\n        quit    => -> $ex { say \"Supply finished with error $ex\" },\n    );\n\n    # later\n    $tap.close;\n\n=head1 Methods\n\n=head2 method close\n\n    method close(Tap:D:)\n\nCloses the tap.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Telemetry/Instrument/Thread.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Telemetry::Instrument::Thread\n\n=SUBTITLE Instrument for collecting Thread data\n\n    class Telemetry::Instrument::Thread { }\n\nB<Note: > This class is a Rakudo-specific feature and not standard Raku.\n\nObjects of this class are generally not created by themselves, but rather\nthrough making a L<snap|/type/Telemetry>shot.\n\nThis class provides the following data points (in alphabetical order):\n\n=item tad\n\nThe number of threads that ended with an exception (B<t>hreads-B<a>borteB<d>).\n\n=item tcd\n\nThe number of threads that completed without any problem\n(B<t>hreads-B<c>ompleteB<d>).\n\n=item thid\n\nHighest OS thread ID seen (B<t>hread-B<h>ighest-B<id>).\n\n=item tjd\n\nThe number of threads that were joined (B<t>hreads-B<j>oineB<d>).\n\n=item tsd\n\nThe number of threads that were started (B<t>hreads-B<s>tarteB<d>).\n\n=item tyd\n\nThe number of times a thread was yielded (B<t>hreads-B<y>ieldeB<d>).\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Telemetry/Instrument/ThreadPool.rakudoc",
    "content": "\n=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Telemetry::Instrument::ThreadPool\n\n=SUBTITLE Instrument for collecting ThreadPoolScheduler data\n\n    class Telemetry::Instrument::ThreadPool { }\n\nB<Note:> This class is a Rakudo-specific feature and not standard Raku.\n\nObjects of this class are generally not created directly, but rather through\nmaking a L<snap|/type/Telemetry>shot. They provide the following attributes (in\nalphabetical order):\n\n=item atc\n\nThe number of tasks completed by affinity thread workers\n(B<a>ffinity-B<t>asks-B<c>ompleted).\n\n=item atq\n\nThe number of tasks queued for execution for affinity thread workers\n(B<a>ffinity-B<t>asks-B<q>ueued).\n\n=item aw\n\nThe number of affinity thread workers (B<a>ffinity-B<w>orkers).\n\n=item gtc\n\nThe number of tasks completed by general workers\n(B<g>eneral-B<t>asks-B<c>ompleted).\n\n=item gtq\n\nThe number of tasks queued for execution by general worker\n(B<g>eneral-B<t>asks-B<q>ueued).\n\n=item gw\n\nThe number of general workers (B<g>eneral-B<w>orkers).\n\n=item s\n\nThe number of supervisor threads running, usually C<0> or C<1> (B<s>upervisor).\n\n=item ttc\n\nThe number of tasks completed by timer workers (B<t>imer-B<t>asks-B<c>ompleted).\n\n=item ttq\n\nThe number of tasks queued for execution by timer workers\n(B<t>imer-B<t>asks-B<q>ueued).\n\n=item tw\n\nThe number of timer workers (B<t>imer-B<w>orkers).\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Telemetry/Instrument/Usage.rakudoc",
    "content": "\n=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Telemetry::Instrument::Usage\n\n=SUBTITLE Instrument for collecting getrusage data\n\n    class Telemetry::Instrument::Usage { }\n\nB<Note: > This class is a Rakudo-specific feature and not standard Raku.\n\nObjects of this class are generally not created by themselves, but rather\nthrough making a L<snap|/type/Telemetry>shot.\n\n=head2 Useful readings\n\nThis class provides the following generally usable readings (in alphabetical\norder):\n\n=item cpu\n\nThe total amount of CPU time (in microseconds), essentially the sum of\nC<cpu-user> and C<cpu-sys>.\n\n=item cpu-sys\n\nThe number of microseconds of CPU used by the system.\n\n=item cpu-user\n\nThe number of microseconds of CPU used by the user program.\n\n=item cpus\n\nThe number of CPU's active, essentially C<cpu> divided by C<wallclock>.\n\n=item max-rss\n\nThe maximum resident set size (in KiB).\n\n=item util%\n\nPercentage of CPU utilization, essentially 100 * C<cpus> / number of CPU cores.\n\n=item wallclock\n\nThe time the program has been executing (in microseconds).\n\n=head2 Less useful readings\n\nThe following readings may or may not contain sensible information, mostly\ndepending on hardware and OS being used.  Please check your local C<getrusage>\ndocumentation for their exact meaning:\n\n  =begin code :lang<text>\n  name        getrusage struct name\n  ====        =====================\n  max-rss     ru_maxrss\n  ix-rss      ru_ixress\n  id-rss      ru_idrss\n  is-rss      ru_isrss\n  minf        ru_minflt\n  majf        ru_majflt\n  nswp        ru_nswap\n  inb         ru_inblock\n  outb        ru_oublock\n  msnd        ru_msgsnd\n  mrcv        ru_msgrcv\n  nsig        ru_nsignals\n  volcsw      ru_nvcsw\n  invcsw      ru_nivcsw\n  =end code\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Telemetry/Period.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Telemetry::Period\n\n=SUBTITLE Performance data over a period\n\n    =begin code :preamble<class Telemetry { }>\n    class Telemetry::Period is Telemetry { }\n    =end code\n\nB<Note: > This class is a Rakudo-specific feature and not standard Raku.\n\n=begin code\n# basic usage\nuse Telemetry;\nmy $t0 = Telemetry.new;\n# execute some code\nmy $t1 = Telemetry.new;\nmy $period = $t1 - $t0;  # creates Telemetry::Period object\nsay \"Code took $period<wallclock> microseconds to execute\";\n=end code\n\nA C<Telemetry::Period> object contains the difference between two\nL<C<Telemetry>|/type/Telemetry> objects.  It is generally not created by calling\n.new, but it can be if needed.  For all practical purposes, it is the same as\nthe L<C<Telemetry>|/type/Telemetry> object, but the B<meaning> of the values is different (and\nthe values are generally much smaller, as they usually are the difference of\ntwo big values of the L<C<Telemetry>|/type/Telemetry> objects from which it was created).\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Telemetry/Sampler.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Telemetry::Sampler\n\n=SUBTITLE Telemetry instrument pod\n\n    =begin code :preamble<class Telemetry { }>\n    class Telemetry::Sampler { }\n    =end code\n\nB<Note: > This class is a Rakudo-specific feature and not standard Raku.\n\n=begin code\nuse Telemetry;\n$*SAMPLER.set-instruments(<Usage ThreadPool>); # default setting\n=end code\n\nOne usually does not create any C<Telemetry::Sampler> objects: when the\nL<C<Telemetry>|/type/Telemetry> module is loaded, a C<Telemetry::Sampler> object\nis automatically created in the C<$*SAMPLER> dynamic variable.\n\nAn object of the C<Telemetry::Sampler> class knows about which instruments\nto use when making a snapshot.\n\n=head2 method new\n\n=for code :preamble<use Telemetry>\nmethod new(Telemetry::Sampler: @instruments --> Telemetry::Sampler:D)\n\nThe C<new> method takes a list of instruments.  If no instruments are specified,\nthen it will look at the C<RAKUDO_TELEMETRY_INSTRUMENTS> environment variable\nto find specification of instruments.  If that is not available either, then\nL<C<Telemetry::Instrument::Usage>|/type/Telemetry::Instrument::Usage> and\nL<C<Telemetry::Instrument::ThreadPool>|/type/Telemetry::Instrument::ThreadPool> will be\nassumed.\n\nInstruments can be specified by either the type object of the instrument class\n(e.g. L<C<Telemetry::Instrument::Usage>|/type/Telemetry::Instrument::Usage>) or by a string, in which case it will\nbe automatically prefixed with \"Telemetry::Instrument::\", so \"Usage\" would be\nthe same as L<C<Telemetry::Instrument::Usage>|/type/Telemetry::Instrument::Usage>.\n\n=head2 method set-instruments\n\n=for code :preamble<use Telemetry>\nmethod set-instruments(Telemetry::Sampler:D @instruments --> Nil)\n\nAllows one to change the instruments on an existing C<Instrument::Sampler>\nobject.  Generally only used by calling it on the C<$*SAMPLER> dynamic variable.\nTakes the same parameters as L<new|/routine/new>, except that specifying B<no>\ninstruments will actually remove all of the instruments, effectively blocking\nany snap taking.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Telemetry.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Telemetry\n\n=SUBTITLE Collect performance state for analysis\n\n    class Telemetry { }\n\nB<Note: > This class is a Rakudo-specific feature and not standard Raku.\n\nOn creation, a C<Telemetry> object contains a snapshot of various aspects of\nthe current state of the virtual machine.  This is in itself useful, but\ngenerally one needs two snapshots for the difference (which is a\nL<C<Telemetry::Period>|/type/Telemetry::Period> object).\n\nThe Telemetry object is really a collection of snapshots taken by different\n\"instruments\".  By default, the\nL<C<Telemetry::Instrument::Usage>|/type/Telemetry::Instrument::Usage>\nand L<C<Telemetry::Instrument::ThreadPool>|/type/Telemetry::Instrument::ThreadPool>\ninstruments are activated.\n\nThe C<Telemetry> (and L<C<Telemetry::Period>|/type/Telemetry::Period>) objects\nalso do the role L<C<Associative>|/type/Associative>.  This means\nthat you can treat a Telemetry object as a read-only L<C<Hash>|/type/Hash>, with all of the\ndata values of the instruments as keys.\n\nYou can determine which instruments C<Telemetry> should use by setting the\nC<$*SAMPLER> dynamic variable, which is a\nL<C<Telemetry::Sampler>|/type/Telemetry::Sampler> object.\n\nCurrently, the following instruments are supported by the Rakudo core:\n\n=item Telemetry::Instrument::Usage\n\nProvides (in alphabetical order): C<cpu>, C<cpu-sys>, C<cpu-user>, C<cpus>,\nC<id-rss>, C<inb>, C<invcsw>, C<is-rss>, C<ix-rss>, C<majf>, C<max-rss>,\nC<minf>, C<mrcv>, C<msnd>, C<nsig>, C<nswp>, C<volcsw>, C<outb>, C<util%>\nand C<wallclock>.  For complete documentation of the meaning of these data\nvalues, see L<C<Telemetry::Instrument::Usage>|/type/Telemetry::Instrument::Usage>.\n\n=item Telemetry::Instrument::Thread\n\nProvides (in alphabetical order): C<tad>, C<tcd>, C<thid>, C<tjd>, C<tsd> and\nC<tys>.  For complete documentation of the meaning of these data values, see\nL<C<Telemetry::Instrument::Thread>|/type/Telemetry::Instrument::Thread>.\n\n=item Telemetry::Instrument::ThreadPool\n\nProvides (in alphabetical order): C<atc>, C<atq>, C<aw>, C<gtc>, C<gtq>, C<gw>,\nC<s>, C<ttc>, C<ttq> and C<tw>.  For complete documentation of the meaning of\nthese data values, see\nL<C<Telemetry::Instrument::ThreadPool>|/type/Telemetry::Instrument::ThreadPool>.\n\n=item Telemetry::Instrument::AdHoc\n\nDoes not provide any data by itself: one must indicate which variables are\nto be monitored, which will then become available as methods with the same name\non the instrument.\n\n=head2 routine T\n\n    sub T()\n\nShortcut for C<Telemetry.new>.  It is exported by default.  Since the\nC<Telemetry> class also provides an L<C<Associative>|/type/Associative> interface, one can easily\ninterpolate multiple values in a single statement:\n\n=begin code\nuse Telemetry;\nsay \"Used {T<max-rss cpu>} (KiB CPU) so far\";\n=end code\n\n=head2 routine snap\n\n    multi snap(--> Nil)\n    multi snap(Str:D $message --> Nil)\n    multi snap(Str $message = \"taking heap snapshot...\", :$heap!)\n    multi snap(@s --> Nil)\n\nThe C<snap> subroutine is shorthand for creating a new C<Telemetry> object and\npushing it to an array for later processing.  The subroutine is exported by default.\n\nFrom release 2017.11, one can give a custom array C<@s> to push to:\n\n=begin code\nuse Telemetry;\nmy @s;\nfor ^5 {\n    snap(@s);\n    # do some stuff\n    LAST snap(@s);\n}\n=end code\n\nIf no array is specified, it will use an internal array for convenience.\n\nFrom release 2019.07, C<snap> accepts a positional argument C<$message> of type L<C<Str>|/type/Str>, which will\nbecome the value of the C<message> attribute of the new C<Telemetry> object.\n\nAlso from release 2019.07, one can pass a named argument C<:heap>\nto instruct the compiler to write a heap snapshot to a file.\nFrom release 2021.12, C<snap> returns that filename.\nThe argument C<:heap> can be of type L<C<Bool>|/type/Bool>, L<C<Str>|/type/Str>, or L<C<IO::Path>|/type/IO::Path>. Their implications are as follows:\n\n=item L<C<IO::Path>|/type/IO::Path>, e.g. C«snap( heap => 'outputfile'.IO )»: The snapshot will be written to exactly this path.\nThe returned filename is always an absolute path.\n\n=item L<C<Str>|/type/Str>, e.g. C«snap(:heap<outputfile>)»: The snapshot will be written to this path I<if> no such file already exists.\nIf such a file already exists, the snapshot will instead be written to C<outputfile-$($*PID)-$($i).mvmheap>\n(where C<$i> starts at 1 and increases each time).\nThe returned filename is a relative or an absolute path depending on what form C<:heap> has.\n\n=item Boolean C<True>, e.g. C<snap(:heap)>: The snapshot will be written to the file C<heapsnapshot-$($*PID)-$($i).mvmheap>.\nThe returned filename is always a relative path.\n\nAdditionally, in each of these cases, two ordinary C<Telemetry> objects are pushed to the internal array:\nOne of them is created just before writing the snapshot and has C<$message> as its C<message> attribute.\nThe other is created just after writing the snapshot and has the filename as its C<message> attribute.\n\nFinally, there's also this option for C<:heap>:\n\n=item Boolean C<False>, e.g. C<snap(:!heap)>: No heap snapshot is taken, no file is written.\nInstead, C<snap()> will be called (or C<snap($message)>, if a custom C<$message> has been specified).\n\n=head2 routine snapper\n\n    sub snapper($sleep = 0.1, :$stop, :$reset --> Nil)\n\nThe C<snapper> routine starts a separate thread that will call C<snap>\nrepeatedly until the end of program.  It is exported by default.\n\nBy default, it will call C<snap> every B<0.1> second.  The only positional\nparameter is taken to be the delay between C<snap>s.\n\nPlease see the L<snapper module|#module_snapper> for externally starting a snapper without\nhaving to change the code.  Simply adding C<-Msnapper> as a command line\nparameter, will then start a snapper for you.\n\n=head2 routine periods\n\n    multi periods( --> Seq)\n    multi periods(@s --> Seq)\n\nThe C<periods> subroutine processes an array of C<Telemetry> objects and\ngenerates a L<C<Seq>|/type/Seq> of L<C<Telemetry::Period>|/type/Telemetry::Period> objects out of that.  It is exported\nby default.\n\n=begin code :preamble<my @t;use Telemetry;>\n.<cpu wallclock>.say for periods(@t);\n\n# OUTPUT:\n# ====================\n# (164 / 160)\n# (23 / 21)\n# (17 / 17)\n# (15 / 16)\n# (29 / 28)\n=end code\n\nIf no array is specified, it will use the internal array of C<snap> without\nparameters B<and> will reset that array upon completion (so that new C<snap>s\ncan be added again).\n\n=begin code\nuse Telemetry;\nfor ^5 {\n    snap;\n    LAST snap;\n}\nsay .<cpu wallclock>.join(\" / \") for periods;\n\n# OUTPUT:\n# ====================\n# 172 / 168\n# 24 / 21\n# 17 / 18\n# 17 / 16\n# 27 / 27\n=end code\n\nIf only one C<snap> was done, another C<snap> will be done to create at least\none L<C<Telemetry::Period>|/type/Telemetry::Period> object.\n\n=head2 routine report\n\n    multi report(:@columns, :$legend, :$header-repeat, :$csv, :@format)\n\nThe C<report> subroutine generates a report about an array of C<Telemetry>\nobjects.  It is exported by default.  These can have been created by regularly\ncalling C<snap>, or by having a L<snapper|/routine/snapper> running.  If no positional parameter\nis used, it will assume the internal array to which the parameterless C<snap>\npushes.\n\nBelow are the additional named parameters of C<report>.\n\n=item C<:columns>\n\nSpecify the names of the columns to be included in the report.  Names can\nbe specified with the column name (e.g. C<gw>).  If not specified, defaults to\nwhat is specified in the C<RAKUDO_REPORT_COLUMNS> environment variable.\nIf that is not set either, defaults to:\n\n    =begin code :lang<text>\n    wallclock util% max-rss gw gtc tw ttc aw atc\n    =end code\n\n=item C<:header-repeat>\n\nSpecifies after how many lines the header should be repeated in the report.\nIf not specified, defaults to what is specified in the\nC<RAKUDO_REPORT_HEADER_REPEAT> environment variable.  If that is not set either,\ndefaults to 32.\n\n=item C<:legend>\n\nSpecifies whether a legend should be added to the report.  If not specified,\ndefaults to what is specified in the C<RAKUDO_REPORT_LEGEND> environment variable.\nIf that is not set either, defaults to True.\n\nIf there are C<snap>s available in the internal array at the end of the\nprogram, then C<report> will be automatically generated and printed on C<STDERR>.\n\n=head2 module snapper\n\nStart a thread taking repeated system state snapshots.\n\nThis module contains no subroutines or methods or anything.  It is intended\nas a shortcut for starting the L<snapper|/routine/snapper> subroutine of the C<Telemetry> module,\nallowing taking snapshots of the execution of a program without needing to change\nthe program.  Simple loading the module with C<-Msnapper> will do all that is\nneeded to start the snapper, and have a report printed on STDERR upon completion\nof the program.\n\nThe C<RAKUDO_SNAPPER> environment variable can be set to indicate the time\nbetween snapshots.  If not specified, it will default to B<0.1> seconds.\n\nThe C<snapper> module assumes an orderly shutdown of the process.  Killing the\nprocess (for instance by pressing Control-c) will B<not> produce a report.\n\n=head2 module safe-snapper\n\nAvailable as of the 2021.09 release of the Rakudo compiler.\n\nThis module provides a safe alternative to the C<snapper> module: killing\na process by pressing Control-c B<will> produce a report.  It is able to\ndo so by installing a L<signal handler|/type/Supply#sub_signal>, which\nB<may> interfere with normal functioning of interactive programs.\n\nKilling a process in any other way, will B<not> produce a report.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Test.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"module\") :category(\"module\")\n\n=TITLE module Test\n\n=SUBTITLE Writing and running tests\n\nThis module provides a testing framework, and is used in the official suite that\ntests the specification. All its functions emit output conforming to the\nL<Test Anything Protocol|https://testanything.org>.\n\nAlso see L<Writing and running tests in Raku|/language/testing>.\n\n=head1 Methods\n\n=head2 sub plan\n\n    multi plan(Cool:D :skip-all($reason)!)\n    multi plan($number_of_tests)\n\nSpecify the count of tests -- usually written at the beginning of a\ntest file.\n\n=for code :preamble<use Test;>\nplan 15;   # expect to run 15 tests\n\nIn C<subtest>s, C<plan> is used to specify the count of tests within\nthe subtest.\n\nIf a C<plan> is used, it's not necessary to specify the end of testing with\nC<done-testing>.\n\nYou can also provide a C<:skip-all> named argument instead of a test count,\nto indicate that you want to skip all of the tests. Such a plan will\ncall L«C<exit>|/routine/exit», unless used inside of a C<subtest>.\n\n=for code :preamble<use Test;>\nplan :skip-all<These tests are only for Windows> unless $*DISTRO.is-win;\nplan 1;\nok dir 'C:/'; # this won't get run on non-Windows\n\nIf used in a C<subtest>, it will instead C<return> from that\nC<subtest>'s L«C<Callable>|/type/Callable». For that reason, to be able to\nuse C<:skip-all> inside a C<subtest>, you must use a C<sub> instead of a\nregular block:\n\n=begin code :preamble<use Test;>\nplan 2;\nsubtest \"Some Windows tests\" => sub { # <-- note the `sub`; can't use bare block\n    plan :skip-all<We aren't on Windows> unless $*DISTRO.is-win;\n    plan 1;\n    ok dir 'C:/'; # this won't get run on non-Windows\n}\nok 42; # this will run everywhere and isn't affected by skip-all inside subtest\n=end code\n\nNote that C<plan> with C<:skip-all> is to avoid performing any tests without\nmarking the test run as failed (i.e. the plan is to not run anything and that's\nall good). Use\nL«C<skip-rest>|#sub_skip-rest» to\nskip all further tests, once the run has started (i.e. planned to run some\ntests, maybe even ran some, but now we're skipping all the rest of them). Use\nL«C<bail-out>|#sub_bail-out» to fail\nthe test run without running any further tests (i.e. things are so bad, there's\nno point in running anything else; we've failed).\n\n=head2 sub done-testing\n\n    sub done-testing()\n\nSpecify that testing has finished.  Use this function when you don't\nhave a C<plan> with the number of tests to run. A C<plan> is not\nrequired when using C<done-testing>.\n\nIt's recommended that the C<done-testing> function be removed and replaced with\na C<plan> function when all tests are finalized. Use of C<plan> can help detect\ntest failures otherwise not reported because tests were accidentally skipped due\nto bugs in the tests or bugs in the compiler. For example:\n\n=for code :preamble<use Test;>\nsub do-stuff {@};\nuse Test;\nok .is-prime for do-stuff;\ndone-testing;\n# output:\n1..0\n\nThe above example is where a C<done-testing> fails. C<do-stuff()> returned\nnothing and tested nothing, even though it should've returned results to test.\nBut the test suite doesn't know how many tests were meant to be run, so it\npasses.\n\nAdding C<plan> gives a true picture of the test:\n\n=for code :preamble<use Test;>\nsub do-stuff {@};\nuse Test;\nplan 1;\nok .is-prime for do-stuff;\n# output:\n1..1\n# Looks like you planned 1 test, but ran 0\n\nNote that leaving the C<done-testing> in place will have no effect on the new test\nresults, but it should be removed for clarity.\n\nThe C<done-testing> function returns C<False> if any test has failed or\nless tests were run than planned, it returns C<True> otherwise.\n\n=head2 sub ok\n\n    multi ok(Mu $cond, $desc = '')\n\nThe C<ok> function marks a test as passed if the given C<$cond> evaluates to\nC<True>. It also accepts an optional description of the test as second\nargument.\n\n=for code :preamble<use Test;>\nmy $response; my $query; ...;\nok $response.success, 'HTTP response was successful';\n\nIn principle, you could use C<ok> for every kind of comparison test, by\nincluding the comparison in the expression passed to C<$cond>:\n\n=for code :preamble<use Test;>\nsub factorial($x) { ... };\nok factorial(6) == 720, 'Factorial - small integer';\n\nHowever, where possible it's better to use one of the specialized comparison\ntest functions below, because they can print more helpful diagnostics output in\ncase the comparison fails.\n\n=head2 sub nok\n\n    multi nok(Mu $cond, $desc = '')\n\nThe C<nok> function marks a test as passed if the given C<$cond> evaluates to\nC<False>. It also accepts an optional description of the test as second\nargument.\n\n=for code :preamble<use Test;>\nmy $response; my $query; ...;\nnok $query.error, 'Query completed without error';\n\n=head2 sub is\n\n    multi is(Mu $got, Mu:U $expected, $desc = '')\n    multi is(Mu $got, Mu:D $expected, $desc = '')\n\nMarks a test as passed if C<$got> and C<$expected> compare positively with the\nL«C<eq> operator|/routine/eq», unless C<$expected> is a type object, in which case\nL«C<===> operator|/routine/===» will be used instead; accepts an optional description of the\ntest as the last argument.\n\nB<NOTE:> the C<eq> operator stringifies its operands, which means C<is()> is not\na good function for testing more complex things, such as lists: C<is (1, (2,\n(3,))), [1, 2, 3]> passes the test, even though the operands are vastly\ndifferent. For those cases, use\nL«C<is-deeply> routine|#sub_is-deeply»\n\n=for code :preamble<use Test;>\nmy $pdf-document; sub factorial($x) { ... }; ...;\nis $pdf-document.author, \"Joe\", 'Retrieving the author field';\nis factorial(6),         720,   'Factorial - small integer';\nmy Int $a;\nis $a, Int, 'The variable $a is an unassigned Int';\n\nB<Note:> if I<only> whitespace differs between the values, C<is()> will output\nfailure message differently, to show the whitespace in each values. For example,\nin the output below, the second test shows the literal C<\\t> in the C<got:>\nline:\n\n=for code :preamble<use Test;>\nis \"foo\\tbar\", \"foo\\tbaz\";   # expected: 'foo     baz'␤#      got: 'foo   bar'\nis \"foo\\tbar\", \"foo    bar\"; # expected: \"foo    bar\"␤#      got: \"foo\\tbar\"\n\n=head2 sub isnt\n\n    multi isnt(Mu $got, Mu:U $expected, $desc = '')\n    multi isnt(Mu $got, Mu:D $expected, $desc = '')\n\nMarks a test as passed if C<$got> and C<$expected> are B<not> equal using\nthe same rules as C<is()>.  The function accepts an optional description\nof the test.\n\n=for code :preamble<use Test;>\nisnt pi, 3, 'The constant π is not equal to 3';\nmy Int $a = 23;\n$a = Nil;\nisnt $a, Nil, 'Nil should not survive being put in a container';\n\n=head2 sub is_approx\n\n    multi is_approx(Mu $got, Mu $expected, $desc = '')\n\nB<NOTE>: Removed with Rakudo release 2023.09, deprecated in older versions.\nUse C<is-approx> instead.\n\n=head2 sub is-approx\n\n    multi is-approx(Numeric $got, Numeric $expected, $desc = '')\n\n=for code :method\nmulti is-approx(Numeric $got, Numeric $expected, Numeric $abs-tol,\n                    $desc = '')\n\n=for code :method\nmulti is-approx(Numeric $got, Numeric $expected, $desc = '',\n                    Numeric :$rel-tol is required)\n\n=for code :method\nmulti is-approx(Numeric $got, Numeric $expected, $desc = '',\n                    Numeric :$abs-tol is required)\n\n=for code :method\nmulti is-approx(Numeric $got, Numeric $expected, $desc = '',\n                    Numeric :$rel-tol is required,\n                    Numeric :$abs-tol is required)\n\nMarks a test as passed if the C<$got> and C<$expected> numerical values\nare approximately equal to each other. The subroutine can be called in numerous\nways that let you test using relative tolerance (C<$rel-tol>) or\nabsolute tolerance (C<$abs-tol>) of different values.\n\nIf no tolerance is set, the function will base the tolerance on the I<absolute>\nvalue of C<$expected>: if it's smaller than C<1e-6>, use absolute tolerance of\nC<1e-5>; if it's larger, use relative tolerance of C<1e-6>.\n\n=begin code :preamble<use Test;>\nmy Numeric ($value, $expected, $abs-tol, $rel-tol) = ...\n\nis-approx $value, $expected;\nis-approx $value, $expected, 'test description';\n\nis-approx $value, $expected, $abs-tol;\nis-approx $value, $expected, $abs-tol, 'test description';\n\nis-approx $value, $expected, :$rel-tol;\nis-approx $value, $expected, :$rel-tol, 'test description';\n\nis-approx $value, $expected, :$abs-tol;\nis-approx $value, $expected, :$abs-tol, 'test description';\n\nis-approx $value, $expected, :$abs-tol, :$rel-tol;\nis-approx $value, $expected, :$abs-tol, :$rel-tol, 'test description';\n=end code\n\n=head3 Absolute tolerance\n\nWhen an absolute tolerance is set, it's used as the actual maximum value\nby which the first and the second parameters can differ. For example:\n\n=begin code :preamble<use Test;>\nis-approx 3, 4, 2; # success\nis-approx 3, 6, 2; # fail\n\nis-approx 300, 302, 2; # success\nis-approx 300, 400, 2; # fail\nis-approx 300, 600, 2; # fail\n=end code\n\nRegardless of values given, the difference between them cannot be more\nthan C<2>.\n\n=head3 Relative tolerance\n\nWhen a relative tolerance is set, the test checks the relative difference\nbetween values. Given the same tolerance, the larger the numbers given, the\nlarger the value they can differ by can be.\n\nFor example:\n\n=begin code :preamble<use Test;>\nis-approx 10, 10.5, :rel-tol<0.1>; # success\nis-approx 10, 11.5, :rel-tol<0.1>; # fail\n\nis-approx 100, 105, :rel-tol<0.1>; # success\nis-approx 100, 115, :rel-tol<0.1>; # fail\n=end code\n\nBoth versions use C<0.1> for relative tolerance, yet the first can differ\nby about C<1> while the second can differ by about C<10>. The function used\nto calculate the difference is:\n\n=begin code :lang<text>\n              |value - expected|\n⁣rel-diff = ────────────────────────\n           max(|value|, |expected|)\n=end code\n\nand the test will fail if C<rel-diff> is higher than C<$rel-tol>.\n\n=head3 Both absolute and relative tolerance specified\n\n=for code :preamble<use Test; my ($value, $expected);>\nis-approx $value, $expected, :rel-tol<.5>, :abs-tol<10>;\n\nWhen both absolute and relative tolerances are specified, each will be\ntested independently, and the C<is-approx> test will succeed only if both pass.\n\n=head2 sub is-approx-calculate\n\n=for code :method\nsub is-approx-calculate($got, $expected, $abs-tol where { !.defined or $_ >= 0 },\n                        $rel-tol where { !.defined or $_ >= 0 }, $desc)\n\nThis is the actual routine called by\nL<C<is-approx> when absolute and relative tolerance are specified|/type/Test#Both_absolute_and_relative_tolerance_specified>.\nThey are\ntested independently, and the test succeeds only if both pass.\n\n=head2 sub is-deeply\n\n    multi is-deeply(Seq:D $got, Seq:D $expected, $reason = '')\n    multi is-deeply(Seq:D $got, Mu $expected, $reason = '')\n    multi is-deeply(Mu $got, Seq:D $expected, $reason = '')\n    multi is-deeply(Mu $got, Mu $expected, $reason = '')\n\nMarks a test as passed if the first and second parameters are equivalent, using the\nsame semantics as the L<eqv operator|/routine/eqv>. This is the best way to\ncheck for equality of (deep) data structures. The function accepts an optional\ndescription of the test as the last argument.\n\n=begin code\nuse Test;\nplan 1;\n\nsub string-info(Str() $_) {\n    Map.new: (\n      length  =>  .chars,\n      char-counts => Bag.new-from-pairs: (\n          letters => +.comb(/<:letter>/),\n          digits  => +.comb(/<:digit>/),\n          other   => +.comb(/<.-:letter-:digit>/),\n    ))\n}\n\nis-deeply string-info('42 Butterflies ♥ Raku'), Map.new((\n    :21length,\n    char-counts => Bag.new-from-pairs: ( :15letters, :2digits, :4other, )\n)), 'string-info gives right info';\n=end code\n\nB<Note:> for L<historical reasons|https://github.com/rakudo/rakudo/commit/096bc17cd5>,\nL<C<Seq>|/type/Seq>C<:D> arguments to C<is-deeply> get converted to\nL<C<List>|/type/List>s by calling L<C<.cache>|/routine/cache> on them. If you\nwant to ensure strict L<C<Seq>|/type/Seq> comparisons, use\nL«C<cmp-ok $got, 'eqv', $expected, $desc>|/language/testing#By_arbitrary_comparison»\ninstead.\n\n\n=head2 sub cmp-ok\n\n    multi cmp-ok(Mu $got is raw, $op, Mu $expected is raw, $desc = '')\n\nCompares C<$got> and C<$expected> with the given C<$op> comparator and\npasses the test if the comparison yields a C<True> value. The description\nof the test is optional.\n\nThe C<$op> comparator can be either a L<C<Callable>|/type/Callable> or\na L<C<Str>|/type/Str> containing an infix operator, such as C<'=='>, a C<'~~'>, or a\nuser-defined infix.\n\n=for code :preamble<use Test;>\ncmp-ok 'my spelling is apperling', '~~', /perl/, \"bad speller\";\n\nMetaoperators cannot be given as a string; pass them as a\nL<C<Callable>|/type/Callable> instead:\n\n=for code :preamble<use Test;>\ncmp-ok <a b c>, &[!eqv], <b d e>, 'not equal';\n\nA L<C<Callable>|/type/Callable> C<$op> lets you use custom comparisons:\n\n=for code :preamble<use Test;>\nsub my-comp { $^a / $^b  < rand };\ncmp-ok 1, &my-comp, 2, 'the dice giveth and the dice taketh away'\ncmp-ok 2, -> $a, $b { $a.is-prime and $b.is-prime and $a < $b }, 7,\n    'we got primes, one larger than the other!';\n\n=head2 sub isa-ok\n\n    multi isa-ok(Mu $var, Mu $type, $desc = \"The object is-a '$type.raku()'\")\n\nMarks a test as passed if the given object C<$var> is, or inherits from, the\ngiven C<$type>.  For convenience, types may also be specified as a\nstring.  The function accepts an optional description of the test, which\ndefaults to a string that describes the object.\n\n=begin code :preamble<use Test;>\nclass Womble {}\nclass GreatUncleBulgaria is Womble {}\nmy $womble = GreatUncleBulgaria.new;\n\nisa-ok $womble, Womble, \"Great Uncle Bulgaria is a womble\";\nisa-ok $womble, 'Womble';     # equivalent\n=end code\n\nNote that, unlike C<isa>, C<isa-ok> also matches C<Roles>:\n\n=begin code :preamble<use Test;>\nsay 42.isa(Numeric); # OUTPUT: «False␤»\nisa-ok 42, Numeric;  # OUTPUT: «ok 1 - The object is-a 'Numeric'␤»\n=end code\n\n=head2 sub can-ok\n\n    multi can-ok(Mu $var, Str $meth, $desc = \"...\" )\n\nMarks a test as passed if the given C<$var> can run the method named\nC<$meth>.  The function accepts an optional description.  For\ninstance:\n\n=begin code :preamble<use Test;>\nclass Womble {\n    method collect-rubbish { ... }\n}\nmy $womble = Womble.new;\n\n# with automatically generated test description\ncan-ok $womble, 'collect-rubbish';\n#  => An object of type 'Womble' can do the method 'collect-rubbish'\n\n# with human-generated test description\ncan-ok $womble, 'collect-rubbish', \"Wombles can collect rubbish\";\n#  => Wombles can collect rubbish\n=end code\n\n=head2 sub does-ok\n\n    multi does-ok(Mu $var, Mu $type, $desc = \"...\")\n\nMarks a test as passed if the given C<$var> can do the given role C<$type>.\nThe function accepts an optional description of the test.\n\n=begin code :preamble<use Test;>\n# create a Womble who can invent\nrole Invent {\n    method brainstorm { say \"Aha!\" }\n}\nclass Womble {}\nclass Tobermory is Womble does Invent {}\n\n# ... and later in the tests\nuse Test;\n\nmy $tobermory = Tobermory.new;\n\n# with automatically generated test description\ndoes-ok $tobermory, Invent;\n#  => The object does role Type\n\ndoes-ok $tobermory, Invent, \"Tobermory can invent\";\n#  => Tobermory can invent\n=end code\n\n=head2 sub like\n\n    sub like(Str() $got, Regex:D $expected, $desc = \"text matches $expected.raku()\")\n\nUse it this way:\n\n=for code :preamble<use Test;>\nlike 'foo', /fo/, 'foo looks like fo';\n\nMarks a test as passed if the first parameter, when coerced to a string,\nmatches the regular expression specified as the second parameter.\nThe function accepts an optional description of the test with a default\nvalue printing the expected match.\n\n=head2 sub unlike\n\n    multi unlike(Str() $got, Regex:D $expected, $desc = \"text does not match $expected.raku()\")\n\nUsed this way:\n\n=for code :preamble<use Test;>\nunlike 'foo', /bar/, 'foo does not look like bar';\n\nMarks a test as passed if the first parameter, when coerced to a string,\ndoes B<not> match the regular expression specified as the second\nparameter.  The function accepts an optional description of the test,\nwhich defaults to printing the text that did not match.\n\n=head2 sub use-ok\n\n    multi use-ok(Str $code, $desc = \"$code module can be use-d ok\")\n\nMarks a test as passed if the given C<$module> loads correctly.\n\n=for code :preamble<use Test;>\nuse-ok 'Full::Qualified::ModuleName';\n\nSince C<$code> is being turned into an C<EVAL>, you can also pass arguments:\n\n=for code :preamble<use Test;>\nuse-ok 'Full::Qualified::ModuleName :my-argument';\n\n=head2 sub dies-ok\n\n    multi dies-ok(Callable $code, $reason = '')\n\nMarks a test as passed if the given C<$code> throws an L<C<Exception>|/type/Exception>.\n\nThe function accepts an optional description of the test.\n\n=begin code :preamble<use Test;>\nsub saruman(Bool :$ents-destroy-isengard) {\n    die \"Killed by Wormtongue\" if $ents-destroy-isengard;\n}\n\ndies-ok { saruman(ents-destroy-isengard => True) }, \"Saruman dies\";\n=end code\n\n=head2 sub lives-ok\n\n    multi lives-ok(Callable $code, $reason = '')\n\nMarks a test as passed if the given C<$code> B<does not> throw an\nexception.\n\nThe function accepts an optional description of the test.\n\n=begin code :preamble<use Test;>\nsub frodo(Bool :$destroys-ring) {\n    die \"Oops, that wasn't supposed to happen\" unless $destroys-ring;\n}\n\nlives-ok { frodo(destroys-ring => True) }, \"Frodo survives\";\n=end code\n\n=head2 sub eval-dies-ok\n\n    multi eval-dies-ok(Str $code, $reason = '')\n\nMarks a test as passed if the given C<$string> throws an\nL<C<Exception>|/type/Exception> when C<eval>ed as code.\n\nThe function accepts an optional description of the test.\n\n=begin code :preamble<use Test;>\neval-dies-ok q[my $joffrey = \"nasty\";\n               die \"bye bye Ned\" if $joffrey ~~ /nasty/],\n    \"Ned Stark dies\";\n=end code\n\n=head2 sub eval-lives-ok\n\n    multi eval-lives-ok(Str $code, $reason = '')\n\nMarks a test as passed if the given C<$string> B<does not> throw an\nexception when C<eval>ed as code.\n\nThe function accepts an optional description of the test.\n\n=begin code :preamble<use Test;>\neval-lives-ok q[my $daenerys-burns = False;\n                die \"Oops, Khaleesi now ashes\" if $daenerys-burns],\n    \"Dany is blood of the dragon\";\n=end code\n\n=head2 sub exits-ok\n\n    multi exits-ok($code, $exit, $reason)\n\nMarks a test as passed if the given C<$code> exits with the given C<$exit> code.\n\nThe routine accepts an optional description (C<$reason>) for the test.\n\n=begin code :preamble<use Test;>\nexits-ok({ say 3; exit 4}, 4, \"exited with the right code\") # passes\n=end code\n\n=head2 sub throws-like\n\n    sub throws-like($code, $ex_type, $reason?, *%matcher)\n\nMarks a test as passed if the given C<$code> throws the specific exception\nexpected exception type C<$ex_type>. The code C<$code> may be specified as\nsomething L<C<Callable>|/type/Callable> or as a string to be C<EVAL>ed. The exception is\nspecified as a type object.\n\nIf an exception was thrown, it will also try to match the matcher hash,\nwhere the key is the name of the method to be called on the exception, and\nthe value is the value it should have to pass. For example:\n\n=begin code :preamble<use Test;>\nsub frodo(Bool :$destroys-ring) {\n    fail \"Oops. Frodo dies\" unless $destroys-ring\n};\nthrows-like { frodo }, Exception, message => /dies/;\n=end code\n\nThe function accepts an optional description of the test as the third\npositional argument.\n\nThe routine makes L<C<Failure>|/type/Failure>s fatal. If you wish to avoid that,\nuse L«C<no fatal> pragma|/language/pragmas#fatal» and ensure\nthe tested code does not sink the possible L<C<Failure>|/type/Failure>s. If you\nwish to test that the code returns a L<C<Failure>|/type/Failure> instead of\nthrowing, use C<fails-like> routine instead.\n\n=begin code :preamble<use Test;>\nsub fails-not-throws { +\"a\" }\n# test passes, even though it's just a Failure and would not always throw:\nthrows-like { fails-not-throws }, Exception;\n\n# test detects nothing thrown, because our Failure wasn't sunk or made fatal:\nthrows-like { no fatal; my $ = fails-not-throws; Nil }, Exception;\n=end code\n\nPlease note that you can only use the string form (for C<EVAL>) if you are not\nreferencing any symbols in the surrounding scope. If you are, you should\nencapsulate your string with a block and an EVAL instead. For instance:\n\n=for code :preamble<use Test;>\nthrows-like { EVAL q[ fac(\"foo\") ] }, X::TypeCheck::Argument;\n\n=head2 sub fails-like\n\n    sub fails-like ( \\test where Callable:D|Str:D, $ex-type, $reason?, *%matcher)\n\nSame interface as C<throws-like>, except checks that the code returns a\nL<C<Failure>|/type/Failure> instead of throwing. If the code does throw or if the\nreturned L<C<Failure>|/type/Failure> has already been L<handled|/routine/handled>,\nthat will be considered as a failed test.\n\n=for code :preamble<use Test;>\nfails-like { +\"a\" }, X::Str::Numeric,\n    :message(/'Cannot convert string to number'/),\n    'converting non-numeric string to number fails';\n\n=head2 sub subtest\n\n    multi subtest(Pair $what)\n    multi subtest($desc, &subtests)\n    multi subtest(&subtests, $desc = '')\n\nThe C<subtest> function executes the given block, consisting of usually more\nthan one test, possibly including a C<plan> or C<done-testing>, and counts as\nI<one> test in C<plan>, C<todo>, or C<skip> counts. It will pass the\ntest only if B<all> tests in the block pass. The function accepts an\noptional description of the subtest.\n\n=begin code :preamble<use Test;>\nclass Womble {}\n\nclass GreatUncleBulgaria is Womble {\n    has $.location = \"Wimbledon Common\";\n    has $.spectacles = True;\n}\n\nsubtest {\n    my $womble = GreatUncleBulgaria.new;\n\n    isa-ok $womble,            Womble,             \"Correct type\";\n    is     $womble.location,   \"Wimbledon Common\", \"Correct location\";\n    ok     $womble.spectacles,                     \"Correct eyewear\";\n\n}, \"Check Great Uncle Bulgaria\";\n=end code\n\nYou can also place the description as the first positional argument, or use a\nL<C<Pair>|/type/Pair> with the description and the code in either order. This can be\nuseful for subtests with large bodies.\n\n=begin code :preamble<use Test;>\nsubtest 'A bunch of tests', {\n    plan 42;\n    ...\n    ...\n}\n\nsubtest {\n    plan 72;\n    ...\n    ...\n} => 'Another bunch of tests';\n\n\n=end code\n\n=head2 sub todo\n\n    multi todo($reason, $count = 1)\n\nSometimes tests just aren't ready to be run, for instance a feature might\nnot yet be implemented, in which case tests can be marked as C<todo>. Or it\ncould be the case that a given feature only works on a particular platform -\nin which case one would C<skip> the test on other platforms.\n\nMark C<$count> tests as TODO, giving a C<$reason> as to why.  By default\nonly one test will be marked TODO.\n\n=begin code :preamble<use Test;>\nsub my-custom-pi { 3 };\n\ntodo 'not yet precise enough';         # Mark the test as TODO.\nis my-custom-pi(), pi, 'my-custom-pi'; # Run the test, but don't report\n                                       # failure in test harness.\n=end code\n\nThe result from the test code above will be something like:\n\n=begin code :lang<TAP>\nnot ok 1 - my-custom-pi # TODO not yet precise enough\n# Failed test 'my-custom-pi'\n# at test-todo.rakutest line 7\n# expected: '3.14159265358979'\n#      got: '3'\n=end code\n\nNote that if you C<todo> a C<subtest>, all of the failing tests inside of it\nwill be automatically marked TODO as well and will I<not> count towards your\noriginal TODO count.\n\n=head2 sub skip\n\n    multi skip()\n    multi skip($reason, $count = 1)\n\nSkip C<$count> tests, giving a C<$reason> as to why.  By default only one\ntest will be skipped.  Use such functionality when a test (or tests) would\ndie if run.\n\n=begin code :preamble<use Test;>\nsub num-forward-slashes($arg) { ... } ;\n\nif $*KERNEL ~~ 'linux' {\n    is num-forward-slashes(\"/a/b\"),             2;\n    is num-forward-slashes(\"/a//b\".IO.cleanup), 2;\n}\nelse {\n    skip \"Can't use forward slashes on Windows\", 2;\n}\n=end code\n\nNote that if you mark a test as skipped, you must also prevent that\ntest from running.\n\n=head2 sub skip-rest\n\n    sub skip-rest($reason = '<unknown>')\n\nSkip the remaining tests.  If the remainder of the tests in the test file\nwould all fail due to some condition, use this function to skip them,\nproviding an optional C<$reason> as to why.\n\n=begin code :preamble<use Test;>\nmy $location; sub womble { ... }; ...;\nunless $location ~~ \"Wimbledon Common\" {\n    skip-rest \"We can't womble, the remaining tests will fail\";\n    exit;\n}\n\n# tests requiring functional wombling\nok womble();\n# ...\n=end code\n\nNote that C<skip-rest> requires a C<plan> to be set, otherwise the\nC<skip-rest> call will throw an error. Note that C<skip-rest> does\nnot exit the test run. Do it manually, or use conditionals to\navoid running any further tests.\n\nSee also L«C<plan :skip-all('...')>|#sub_plan»\nto avoid running any tests at all and\nL«C<bail-out>|#sub_bail-out» to abort\nthe test run and mark it as failed.\n\n=head2 sub bail-out\n\n    sub bail-out ($desc?)\n\nIf you already know the tests will fail, you can bail out of the test run\nusing C<bail-out()>:\n\n=begin code :preamble<use Test;>\nmy $has-db-connection;\n...\n$has-db-connection  or bail-out 'Must have database connection for testing';\n=end code\n\nThe function aborts the current test run, signaling failure to the harness.\nTakes an optional reason for bailing out. The subroutine will call\nC<exit()>, so if you need to do a clean-up, do it before calling C<bail-out()>.\n\nIf you want to abort the test run, but without marking it as failed, see\nL«C<skip-rest>|#sub_skip-rest»\nor L«C<plan :skip-all('...')>|#sub_plan»\n\n=head2 sub pass\n\n    multi pass($desc = '')\n\nThe C<pass> function marks a test as passed. C<flunk> marks a test as\nB<not> passed. Both functions accept an optional test description.\n\n=for code :preamble<use Test;>\npass \"Actually, this test has passed\";\nflunk \"But this one hasn't passed\";\n\nSince these subroutines do not provide indication of what value was received\nand what was expected, they should be used sparingly, such as when evaluating\na complex test condition.\n\n=head2 sub flunk\n\n    multi flunk($reason = '')\n\nThe opposite of C<pass>, makes a test fail with an optional message.\n\n=head2 sub diag\n\n    sub diag($message)\n\nDisplay diagnostic information in a TAP-compatible manner on the standard\nerror stream. This is usually used when a particular test has failed to\nprovide information that the test itself did not provide.  Or it can be used\nto provide visual markers on how the testing of a test-file is progressing\n(which can be important when doing stress testing).\n\n=for code :preamble<use Test;>\ndiag \"Yay!  The tests got to here!\";\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Thread.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Thread\n\n=SUBTITLE Concurrent execution of code (low-level)\n\n    class Thread {}\n\nA L<thread|https://en.wikipedia.org/wiki/Thread_%28computing%29> is a sequence\nof instructions that can (potentially) run in parallel to others. Class\nC<Thread> provides a bit of abstraction over threads provided by the\nunderlying virtual machines (which in turn might or might not be operating\nsystem threads).\n\nSince threads are fairly low-level, most applications should use other\nprimitives, like L«C<start>|/type/Promise#method_start», which also runs in\nparallel and returns a L«C<Promise>|/type/Promise».\n\n=begin code\nmy @threads = (^10).map: {\n    Thread.start(\n        name => \"Sleepsorter $_\",\n        sub {\n            my $rand = (^10).pick;\n            sleep $rand;\n            say $rand;\n        },\n    );\n}\n\n.finish for @threads;\n=end code\n\nThe current thread is available in the dynamic variable C<$*THREAD>.\n\n=head1 Methods\n\n=head2 method new\n\n    method new(:&code!, Bool :$app_lifetime = False, Str :$name = '<anon>' --> Thread:D)\n\nCreates and returns a new C<Thread>, without starting it yet. C<&code> is the\ncode that will be run in a separate thread.\n\nC<$name> is a user-specified string that identifies the thread.\n\nIf C<$app_lifetime> is set to C<True>, then the thread is killed when the main\nthread of the process terminates. If set to C<False>, the process will only\nterminate when the thread has finished.\n\n=head2 method start\n\n    method start(Thread:U: &code, Bool :$app_lifetime = False, Str :$name = '<anon>' --> Thread:D)\n\nCreates, runs and returns a new C<Thread>. Note that it can (and often does)\nreturn before the thread's code has finished running.\n\n=head2 method run\n\n    method run(Thread:D:)\n\nRuns the thread, and returns the invocant. It is an error to run a thread that\nhas already been started.\n\n=head2 method id\n\n    method id(Thread:D: --> Int:D)\n\nReturns a numeric, unique thread identifier.\n\n=head2 method finish\n\n    method finish(Thread:D:)\n\nWaits for the thread to finish. This is called L<join|#method_join> in other programming\nsystems.\n\n=head2 method join\n\n    method join(Thread:D:)\n\nWaits for the thread to finish.\n\n=head2 method yield\n\n    method yield(Thread:U:)\n\nTells the scheduler to prefer another thread for now.\n\n    Thread.yield;\n\n=head2 method app_lifetime\n\n    method app_lifetime(Thread:D: --> Bool:D)\n\nReturns C<False> unless the named parameter C<:app_lifetime> is specifically set\nto C<True> during object creation. If the method returns C<False> it means that\nthe process will only terminate when the thread has finished while C<True> means that\nthe thread will be killed when the main thread of the process terminates.\n\n    my $t1 = Thread.new(code => { for 1..5 -> $v { say $v }});\n    my $t2 = Thread.new(code => { for 1..5 -> $v { say $v }}, :app_lifetime);\n\n    say $t1.app_lifetime;                 # OUTPUT: «False␤»\n    say $t2.app_lifetime;                 # OUTPUT: «True␤»\n\n=head2 method name\n\n    method name(Thread:D: --> Str:D)\n\nReturns the user defined string, which can optionally be set during object\ncreation in order to identify the C<Thread>, or C<'<anon>'> if no such string\nwas specified.\n\n    my $t1 = Thread.new(code => { for 1..5 -> $v { say $v }});\n    my $t2 = Thread.new(code => { for 1..5 -> $v { say $v }}, name => 'my thread');\n\n    say $t1.name;                 # OUTPUT: «<anon>␤»\n    say $t2.name;                 # OUTPUT: «my thread␤»\n\n=head2 method Numeric\n\n    method Numeric(Thread:D: --> Int:D)\n\nReturns a numeric, unique thread identifier, i.e. the same as L<id|#method_id>.\n\n=head2 method Str\n\n    method Str(Thread:D: --> Str:D)\n\nReturns a string which contains the invocants L<thread id|#method_id> and\nL<name|#method_name>.\n\n    my $t = Thread.new(code => { for 1..5 -> $v { say $v }}, name => 'calc thread');\n    say $t.Str;                           # OUTPUT: «Thread<3>(calc thread)␤»\n\n=head2 method is-initial-thread\n\n    method is-initial-thread(--> Bool)\n\nReturns a Bool indicating whether the current thread (if called as a class\nmethod) or the Thread object on which it is called, is the initial thread\nthe program started on.\n\n    say Thread.is-initial-thread;    # True if this is the initial thread\n    say $*THREAD.is-initial-thread;  # True if $*THREAD is the initial thread\n\nPlease note there is no guarantee that this is actually the main thread from\nthe OS's point of view.  Also note that if you need this other than from a\npure introspection / debugging point of view, that there are probably better\nways to achieve what you're trying to achieve.\n\n=head1 Routines\n\n=head2 sub full-barrier\n\n    sub full-barrier()\n\nPerforms a full memory barrier, preventing re-ordering of reads/writes.\nRequired for implementing some lock-free data structures and algorithms.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/ThreadPoolScheduler.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class ThreadPoolScheduler\n\n=SUBTITLE Scheduler that distributes work among a pool of threads\n\n=begin code :skip-test<compile time error>\nclass ThreadPoolScheduler does Scheduler {}\n=end code\n\nThe C<ThreadPoolScheduler> has a range of number of threads that it maintains,\nand it distributes work among those threads. When the upper limit of threads\nisn't reached yet, and there is work pending, it spawns new threads to handle\nthe work.\n\n=head1 Methods\n\n=head2 new\n\n=for code\nmethod new(Int :$initial_threads = 0, Int :$max_threads = 8 * Kernel.cpu-cores)\n\nCreates a new C<ThreadPoolScheduler> object with the given range of threads to\nmaintain.\n\nThe default value for C<:initial_threads> is B<0>, so no threads will be\nstarted when a C<ThreadPoolScheduler> object is created by default.\n\nThe default value for C<:max_threads> is B<64>, unless there appear to be\nmore than 8 CPU cores available.  In that case the default will be 8 times\nthe number of CPU cores.\n\nSee also the L<RAKUDO_MAX_THREADS|/programs/03-environment-variables#Other>\nenvironment variable to set the default maximum number of threads.\n\nAs of release 2022.06 of the Rakudo compiler, it is also possible to specify\nC<Inf> or C<*> as a value for C<:max_threads>, indicating that the maximum\nnumber of threads allowed by the operating system, will be used.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/UInt.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE Subset UInt\n\n=SUBTITLE Unsigned integer (arbitrary-precision)\n\nThe C<UInt> is defined as a subset of L<C<Int>|/type/Int>:\n\n=for code\nmy subset UInt of Int where {not .defined or $_ >= 0};\n\nConsequently, it cannot be instantiated or subclassed; however, that shouldn't affect most normal uses.\n\nSome examples of its behavior and uses:\n\n  say UInt ~~ Int; # OUTPUT: «True␤»\n  my UInt $u = 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff; # 64-bit unsigned value\n  say $u.base(16); # OUTPUT: «FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF␤» (32 digits)\n  ++$u;\n  say $u.base(16); # OUTPUT: «100000000000000000000000000000000␤» (33 digits!)\n  my Int $i = $u;\n  say $i.base(16); # same as above\n  say $u.^name;    # OUTPUT: «Int␤» - UInt is a subset, so the type is still Int.\n  say $i.^name;    # OUTPUT: «Int␤»\n  # Difference in assignment\n  my UInt $a = 5;  # nothing wrong\n  my UInt $b = -5; # Exception about failed type check\n  my UInt $c = 0;\n  --$c;            # Exception again\n  CATCH { default { put .^name, ': ', .Str } };\n  # OUTPUT: «X::TypeCheck::Assignment: Type check failed in assignment to $b; expected UInt but got Int (-5)␤»\n\n  # Non-assignment operations are fine\n  my UInt $d = 0;\n  say $d - 3;      # OUTPUT: «-3␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Uni.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class Uni\n\n=SUBTITLE A string of Unicode codepoints\n\n    class Uni does Positional[uint32] does Stringy { }\n\nUnlike L<C<Str>|/type/Str>, which is made of Grapheme clusters, Uni is string\nstrictly made of Unicode codepoints. That is, base characters and combining\ncharacters are separate elements of a C<Uni> instance.\n\nC<Uni> presents itself with a list-like interface of integer Codepoints.\n\nTypical usage of C<Uni> is through one of its subclasses, L<C<NFC>|/type/NFC>, L<C<NFD>|/type/NFD>,\nL<C<NFKD>|/type/NFKD> and L<C<NFKC>|/type/NFKC>, which represent strings in one of the L<Unicode Normalization Forms|https://www.unicode.org/reports/tr15/> of the same name.\n\n=head1 Methods\n\n=head2 method new\n\n    method new(*@codes --> Uni:D)\n\nCreates a new C<Uni> instance from the given codepoint numbers.\n\n=head2 method list\n\n    method list(Uni:D:)\n\nReturns a L<C<Seq>|/type/Seq> of integer codepoints.\n\n=head2 method NFC\n\n    method NFC(Uni:D: --> NFC:D)\n\nReturns an L<C<NFC>|/type/NFC> (Normal Form Composed)-converted version of the invocant.\n\n=head2 method NFD\n\n    method NFD(Uni:D: --> NFD:D)\n\nReturns an L<C<NFD>|/type/NFD> (Normal Form Decomposed)-converted version of the invocant.\n\n=head2 method NFKC\n\n    method NFKC(Uni:D: --> NFKC:D)\n\nReturns an L<C<NFKC>|/type/NFKC> (Normal Form Compatibility Composed)-converted version of the invocant.\n\n=head2 method NFKD\n\n    method NFKD(Uni:D: --> NFKD:D)\n\nReturns an L<C<NFKD>|/type/NFKD> (Normal Form Compatibility Decomposed)-converted version of the invocant.\n\n=head2 method codes\n\n    method codes(Uni:D: --> Int:D)\n\nReturns the number of codepoints in the invocant.\n\n=head2 method elems\n\n    method elems(Uni:D: --> Int:D)\n\nReturns the number of codepoints in the invocant.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Unicode.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class Unicode\n\n=SUBTITLE Unicode related information\n\n    class Unicode { }\n\nBuilt-in class for providing Unicode related information.  Although it\ncan be instantiated, these methods currently mostly make sense when called\nas class methods.  In which case they represent the information of the\nsupported version of Unicode in the current runtime.\n\nAvailable as of release 2023.02 of the Rakudo compiler.  Available as an\nL<installable module|https://raku.land/zef:lizmat/Unicode> for earlier\nversions of the Rakudo compiler.\n\n=head1 Methods\n\n=head2 method version\n\n    method version(Unicode:)\n\nReturns a L«C<Version>|/type/Version» object representing the Unicode\nversion.\n\n    say Unicode.version; # OUTPUT: «v15.0␤»\n\n=head2 method NFG\n\n    method NFG(Unicode:)\n\nReturns a L«C<Bool>|/type/Bool» indicating whether complete\nL«C<Normalization Form Grapheme>|/language/glossary#NFG» support is\navailable.\n\n    # on MoarVM\n    say Unicode.NFG; # OUTPUT: «True␤»\n\n    # on JVM\n    say Unicode.NFG; # OUTPUT: «False␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/VM.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"domain-specific\")\n\n=TITLE class VM\n\n=SUBTITLE Raku Virtual Machine related information\n\n    class VM does Systemic { }\n\nBuilt-in class for providing information about the virtual machine in which\nRaku is running. Usually accessed through the\nL<$*VM|/language/variables#index-entry-%24*VM> dynamic variable.\n\n=head1 Methods\n\n\n=head2 method osname\n\n    multi method osname(VM:U:)\n    multi method osname(VM:D:)\n\nInstance / Class method returning the name of the Operating System, as known\nby the configuration of the VM object / currently running virtual machine.\n\n=head2 method precomp-ext\n\nInstance method returning a string of the extension that should be used for\nprecompiled files of the VM object.\n\n=head2 method precomp-target\n\nInstance method returning a string of the value of the compilation target\nthat should be used when precompiling source-files with the VM object.\n\n=head2 method prefix\n\nInstance method returning a string of the path in which the virtual machine\nof the VM object is installed.\n\n=head2 method request-garbage-collection\n\nAvailable as of the 2020.05 release of the Rakudo compiler.\n\nClass method that tells the virtual machine on which Raku is running, to\nperform a garbage collect run when possible.  Issues a warning if such a\nrequest is not supported by the virtual machine.\n\nProvides no guarantee that the process will actually use less memory after\na garbage collect.  In fact, calling this method repeatedly, may actually\ncause more memory to be used due to memory fragmentation.\n\nMainly intended as a debugging aid for module / core developers.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/ValueObjAt.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class ValueObjAt\n\n=SUBTITLE Unique identification for value types\n\n    class ValueObjAt is ObjAt { }\n\nA subclass of L<C<ObjAt>|/type/ObjAt> that should be used to indicate that a class\nproduces objects that are value types - in other words, that are immutable after\nthey have been initialized.\n\n    my %h = a => 42;    # mutable Hash\n    say %h.WHICH.raku;  # OUTPUT: «ObjAt.new(\"Hash|2972851925856\")␤»\n\n    my $date = Date.new(2025,7,20);  # immutable Date\n    say $date.WHICH.raku;            # OUTPUT: «ValueObjAt.new(\"Date|60876\")␤»\n\nIf you create a class that should be considered a value type, you should add\na C<WHICH> method to that class that returns a C<ValueObjAt> object, for\ninstance:\n\n    class YourClass {\n        has $.foo;  # note these are not mutable\n        has $.bar;\n\n        method WHICH() {\n            ValueObjAt.new(\"YourClass|$!foo|$!bar\");\n        }\n    }\n\nNote that it is customary to always start the identifying string with the\nname of the object, followed by a \"|\".  This to prevent confusion with other\nclasses that may generate similar string values: the name of the class should\nthen be enough of a differentiator to prevent collisions.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Variable.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Variable\n\n=SUBTITLE Object representation of a variable for use in traits\n\n    class Variable {}\n\nVariables have a wealth of compile-time information, but at runtime, accesses to\na variable usually act on the value stored inside it, not the variable itself.\nThe runtime class of a variable is L<C<Scalar>|/type/Scalar>.\n\nClass C<Variable> holds the compile-time information that traits can use to\nintrospect and manipulate variables.\n\n=head1 Traits\n\n=head2 X<trait is default|Traits,is default>\n\nSets the default value with which a variable is initialized, and to which it is\nreset when L<C<Nil>|/type/Nil> is assigned to it. Trait arguments are evaluated at\ncompile time. Closures won't do what you expect: they are stored as is and need\nto be called by hand.\n\n    my Int $x is default(42);\n    say $x;     # OUTPUT: «42␤»\n    $x = 5;\n    say $x;     # OUTPUT: «5␤»\n    # explicit reset:\n    $x = Nil;\n    say $x;     # OUTPUT: «42␤»\n\n\nThe trait C<is default> can be used also with subscripting things like arrays\nand hashes:\n\n=begin code\nmy @array is default( 'N/A' );\n@array[22].say;  # OUTPUT: N/A\n@array = Nil;\n@array.say;      # OUTPUT: [N/A]\n@array[4].say;   # OUTPUT: N/A\n\nmy %hash is default( 'no-value-here' );\n%hash<non-existent-key>.say; # OUTPUT: no-value-here\n%hash<foo> = 'bar';\n%hash<>.say;                 # OUTPUT: {foo => bar}\n%hash<wrong-key>.say;        # OUTPUT: no-value-here\n=end code\n\n\n=head2 trait is dynamic\n\n    multi trait_mod:<is>(Variable:D, :$dynamic)\n\nMarks a variable as dynamic, that is, accessible from inner dynamic scopes\nwithout being in an inner lexical scope.\n\n=begin code\nsub introspect() {\n    say $CALLER::x;\n}\n{\n    my $x is dynamic = 42;\n    introspect();  # OUTPUT: «42␤»\n}\n{\n    my $x = 41;    # not dynamic\n    introspect();  # dies with an exception of X::Caller::NotDynamic\n}\n=end code\n\nThe C<is dynamic> trait is a rather cumbersome way of creating and accessing\ndynamic variables.  A much easier way is to use the L<C<* twigil>|/language/variables#The_*_twigil>:\n\n=begin code\nsub introspect() {\n    say $*x;\n}\n{\n    my $*x = 42;\n    introspect();  # OUTPUT: «42␤»\n}\n{\n    my $x = 41;    # not dynamic\n    introspect();  # dies with an exception of X::Dynamic::NotFound\n}\n=end code\n\n=head2 trait of\n\n    multi trait_mod:<of>(Mu:U $target, Mu:U $type)\n\nSets the type constraint of a container bound to a variable.\n\n    my $i of Int = 42;\n    $i = \"forty plus two\";\n    CATCH { default { say .^name, ' ', .Str } }\n    # OUTPUT: «X::TypeCheck::Assignment Type check failed in assignment to $i; expected Int but got Str (\"forty plus two\")␤»\n\nYou can use any value defined in compile time as a type constraint, including\nconstants:\n\n    constant \\T = Int;\n    my $i of T = 42;\n\nwhich would be equivalent to the previous definition.\n\n=head1 Methods\n\n=head2 method name\n\n    method name(Variable:D: str)\n\nReturns the name of the variable, including the sigil.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Version.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Version\n\n=SUBTITLE Module version descriptor\n\n    class Version { }\n\nVersion objects identify version of software components (and potentially other\nentities). Raku uses them internally for versioning modules.\n\nX<|Syntax,v (version)>\n\nA version consists of several parts, which are visually represented by joining\nthem with a dot. A version part is usually an integer, a string like C<alpha>,\nor a L<C<Whatever>|/type/Whatever>-star C<*>. The latter is used to indicate that any version\npart is acceptable in another version that is compared to the current one.\n\n    say v1.0.1 ~~ v1.*;     # OUTPUT: «True␤»\n    say v1.0.1 ~~ v1.*.1;   # OUTPUT: «True␤»\n\nThe first part of version literals contains C<v> and a number; this might be\nfollowed by alphanumeric and L<C<Whatever>|/type/Whatever> parts and trailed by C<+>. Multiple\nparts are separate with a dot C<.>. A trailing C<+> indicates that higher\nversions are OK in comparisons:\n\n    say v1.2 ~~ v1.0;                 # OUTPUT: «False␤»\n    say v1.2 ~~ v1.0+;                # OUTPUT: «True␤»\n    say v0.and.anything.else ~~ v0+;  # OUTPUT: «True␤»\n\nIn comparisons, order matters, and every part is compared in turn.\n\n    say v1.2 cmp v2.1;      # OUTPUT: «Less␤»\n\nThe C<+> suffix is always taken into account in comparisons:\n\n    say v1.0.1+ <=> v1.0.1; # OUTPUT: «More␤»\n\nAnd C<*> (L<C<Whatever>|/type/Whatever>) is too, and considered always C<Less> than whatever digit\nis in the corresponding part, even if C<*> is trailed by C<+>:\n\n    say v1.* <=> v1.0;      # OUTPUT: «Less␤»\n    say v1.* <= v1.0;       # OUTPUT: «True␤»\n    say v1.*+ <= v1.0;      # OUTPUT: «True␤»\n\nPlease note that method calls, including pseudo methods like C<WHAT>, require\nversion literals either to be enclosed with parentheses or use some other method\nto separate them from the dot that denotes a method call, like in these\nexamples:\n\n    say (v0.and.some.*.stuff).parts;  # OUTPUT: «(0 and some * stuff)␤»\n    say v0.and.some.*.stuff .parts;   # OUTPUT: «(0 and some * stuff)␤»\n\n=head1 Methods\n\n=head2 method new\n\n    method new(Str:D $s)\n\nCreates a C<Version> from a string C<$s>.  The string is combed\nfor the numeric, alphabetic, and wildcard components of the version object.\nAny characters other than alphanumerics and asterisks are assumed\nto be equivalent to a dot.  A dot is also assumed between any adjacent\nnumeric and alphabetic characters.\n\n=head2 method parts\n\n    method parts(Version:D: --> List:D)\n\nReturns the list of parts that make up this C<Version> object\n\n    my $v1 = v1.0.1;\n    my $v2 = v1.0.1+;\n    say $v1.parts;                                    # OUTPUT: «(1 0 1)␤»\n    say $v2.parts;                                    # OUTPUT: «(1 0 1)␤»\n\nThe C<+> suffix is not considered a I<part> of the C<Version> object, and thus\nnot returned by this method, as shown above in the C<$v2> variable.\n\n=head2 method plus\n\n    method plus(Version:D: --> Bool:D)\n\nReturns C<True> if comparisons against this version allow larger versions too.\n\n    my $v1 = v1.0.1;\n    my $v2 = v1.0.1+;\n    say $v1.plus;                                     # OUTPUT: «False␤»\n    say $v2.plus;                                     # OUTPUT: «True␤»\n\n=head2 method Str\n\n    method Str(Version:D: --> Str:D)\n\nReturns a string representation of the invocant.\n\n    my $v1 = v1.0.1;\n    my $v2 = Version.new('1.0.1');\n    say $v1.Str;                                      # OUTPUT: «1.0.1␤»\n    say $v2.Str;                                      # OUTPUT: «1.0.1␤»\n\n=head2 method gist\n\n    method gist(Version:D: --> Str:D)\n\nReturns a string representation of the invocant, just like\nL<C<Str>|#method_Str>, prepended with a lowercase C<v>.\n\n    my $v1 = v1.0.1;\n    my $v2 = Version.new('1.0.1');\n    say $v1.gist;                                      # OUTPUT: «v1.0.1␤»\n    say $v2.gist;                                      # OUTPUT: «v1.0.1␤»\n\n=head2 method Capture\n\n    method Capture()\n\nThrows L<C<X::Cannot::Capture>|/type/X::Cannot::Capture>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/Whatever.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class Whatever\n\n=SUBTITLE Placeholder for the value of an unspecified argument\n\n    class Whatever { }\n\nX<|Syntax,* literal> X<|Syntax,Whatever literal>\nC<Whatever> is a class whose objects don't have any explicit meaning; it\ngets its semantics from other routines that accept C<Whatever>-objects\nas markers to do something special. Using the C<*> literal as an operand\ncreates a C<Whatever> object.\n\nX<|Syntax,Whatever-priming>\nMuch of C<*>'s charm comes from I<Whatever-priming>. When C<*> is used\nin term position, that is, as an operand, in combination with most\noperators, the compiler will transform the expression into a closure of\ntype L<C<WhateverCode>|/type/WhateverCode>, which is actually a\nL<C<Block>|/type/Block> that can be used wherever L<C<Callable>|/type/Callable>s are\naccepted.\n\n    my $c = * + 2;          # same as   -> $x { $x + 2 };\n    say $c(4);              # OUTPUT: «6␤»\n\nMultiple C<*> in one expression generate closures with as many\narguments:\n\n    my $c = * + *;          # same as   -> $x, $y { $x + $y }\n\nUsing C<*> in complex expressions will also generate closures:\n\n    my $c = 4 * * + 5;      # same as   -> $x { 4 * $x + 5 }\n\nCalling a method on C<*> also creates a closure:\n\n=for code\n<a b c>.map: *.uc;      # same as    <a b c>.map: -> $char { $char.uc }\n\nAs mentioned before, not all operators and syntactic constructs prime\nC<*> (or C<Whatever>-stars) to L<C<WhateverCode>|/type/WhateverCode>. In the following cases,\nC<*> will remain a C<Whatever> object.\n\n=begin table\n\n    Exception           Example     What it does\n    =========           =======     ============\n    comma               1, *, 2     generates a List with a * element\n    range operators     1 .. *      Range from 1 to Inf\n    series operator     1 ... *     infinite lazy Seq\n    assignment          $x = *      assign * to $x\n    binding             $x := *     bind * to $x\n    list repetition     1 xx *      generates an infinite list\n\n=end table\n\nThe range operators are handled specially. They do not prime with\nC<Whatever>-stars, but they do prime with L<C<WhateverCode>|/type/WhateverCode>\n\n    say (1..*).^name;       # OUTPUT: «Range␤»\n    say ((1..*-1)).^name;   # OUTPUT: «WhateverCode␤»\n\nThis allows all these constructs to work:\n\n=for code\n.say for 1..*;          # infinite loop\n\nand\n\n    my @a = 1..4;\n    say @a[0..*];           # OUTPUT: «(1 2 3 4)␤»\n    say @a[0..*-2];         # OUTPUT: «(1 2 3)␤»\n\nBecause I<Whatever-priming> is a purely syntactic compiler transform,\nyou will get no runtime priming of stored C<Whatever>-stars into\nL<C<WhateverCode>|/type/WhateverCode>s.\n\n=for code\nmy $x = *;\n$x + 2;   # Not a closure, dies because it can't coerce $x to Numeric\nCATCH { default { put .^name, ': ', .Str } };\n# OUTPUT: «X::Multi::NoMatch: Cannot resolve caller Numeric(Whatever: );\n# none of these signatures match:␤\n# (Mu:U \\v: *%_)»\n\nThe use cases for stored C<Whatever>-stars involve those prime-exception\ncases mentioned above. For example, if you want an infinite series by\ndefault.\n\n=for code :preamble<sub potential-upper-limit {}; sub known-lower-limit {};>\nmy $max    = potential-upper-limit() // *;\nmy $series = known-lower-limit() ... $max;\n\nA stored C<*> will also result in the generation of a L<C<WhateverCode>|/type/WhateverCode> in\nthe specific case of smartmatch. Note that this is not actually the\nstored C<*> which is being primed, but rather the C<*> on the left-hand\nside.\n\n=for code :preamble<sub find-constraint {};>\nmy $constraint           = find-constraint() // *;\nmy $maybe-always-matcher = * ~~ $constraint;\n\nIf this hypothetical C<find-constraint> were to have found no\nconstraint, C<$maybe-always-matcher> would evaluate to C<True> for\nanything.\n\n=for code :preamble<my $maybe-always-matcher>\n$maybe-always-matcher(555);      # True\n$maybe-always-matcher(Any);      # True\n\nL<C<HyperWhatever>|/type/HyperWhatever>'s functionality is similar to\nC<Whatever>, except it refers to multiple values, instead of a single\none.\n\n=head1 Methods\n\n=head2 method ACCEPTS\n\n    multi method ACCEPTS(Whatever:D: Mu $other)\n    multi method ACCEPTS(Whatever:U: Mu $other)\n\nIf the invocant is L«an instance|/language/classtut#A_word_on_types»,\nalways returns C<True>. If the invocant is a type object, performs a typecheck.\n\n    say 42 ~~ (*);       # OUTPUT: «True␤»\n    say 42 ~~ Whatever;  # OUTPUT: «False␤»\n\n=head2 method Capture\n\n    method Capture()\n\nThrows C<X::Cannot::Capture>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/WhateverCode.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class WhateverCode\n\n=SUBTITLE Code object constructed by Whatever-priming\n\n    class WhateverCode is Code { }\n\nC<WhateverCode> objects are the result of L<C<Whatever>|/type/Whatever>-priming.\nSee the L<C<Whatever>|/type/Whatever> documentation for details.\n\nWhen you wish to control how a method or function interprets any I<Whatever\nstar>, you may use multi dispatch with L<C<Whatever>|/type/Whatever> and C<WhateverCode>\nparameters to do so, as in the following example:\n\n    class Cycle {\n          has $.pos;\n          has @.vals;\n    }\n\n    multi get-val(Cycle $c, Int $idx) {\n          $c.vals[$idx % $c.vals.elems]\n    }\n\n    # Define what to do with a stand-alone * as the second argument\n    multi get-val(Cycle $c, Whatever $idx) {\n        get-val($c, $c.pos);\n    }\n\n    # Define what to do with a * WhateverCode in an expression\n    multi get-val(Cycle $c, WhateverCode $idx) {\n        get-val($c, $idx($c.pos));\n    }\n\n    my Cycle $c .= new(:pos(2), :vals(0..^10));\n\n    say get-val($c, 3);   # OUTPUT: «3␤»\n    say get-val($c, *);   # OUTPUT: «2␤»\n    say get-val($c, *-1); # OUTPUT: «1␤»\n\nThe C<WhateverCode> C<does> the L<C<Callable>|/type/Callable> role, so it should be\npossible to introspect the type of L<C<Callable>|/type/Callable> it contains; for instance,\ncontinuing the previous example, we can add a multi that handles a\nC<WhateverCode> with two arguments via checking the signature:\n\n=begin code :skip-test<compile time error>\n# Define what to do with two * in an expression\nmulti get-val(Cycle $c, WhateverCode $idx where { .arity == 2 }) {\n    get-val($c, $idx($c.pos, $c.vals.elems));\n}\n\nsay get-val($c, * + * div 2); # 2 + 10/2 = 7\n=end code\n\nNote, though, that subexpressions may impose their own I<Whatever star>\nrules:\n\n=for code :skip-test<compile time error>\nmy @a = (0, 1, 2);\nsay get-val($c, @a[*-1]) # 2, because the star belongs to the Array class\n\nThis can make the ownership of I<Whatever stars> become confusing rather\nquickly, so be careful not to overdo it.\n\nYou may instead type-constrain using L<C<Callable>|/type/Callable> type in order to\naccept any L<C<Callable>|/type/Callable>, including C<WhateverCode>:\n\n    sub run-with-rand (Callable $code) { $code(rand) };\n    run-with-rand *.say;           # OUTPUT: «0.773672071688484␤»\n    run-with-rand {.say};          # OUTPUT: «0.38673179353983␤»\n    run-with-rand sub { $^v.say }; # OUTPUT: «0.0589543603685792␤»\n\nType-constraining with C<&>-sigiled parameter works equally well and is shorter\nto type:\n\n    sub run-with-rand (&code) { code time };\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/AdHoc.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::AdHoc\n\n=SUBTITLE Error with a custom message\n\n=for code\nclass X::AdHoc is Exception { }\n\nWhen die() is called on an argument which is not an\nL<C<Exception>|/type/Exception>, the argument is wrapped in an\nexception of type C<X::AdHoc>, which is then thrown.\n\nThe benefit of C<X::AdHoc> over returning non-L<C<Exception>|/type/Exception>\nobjects is that it gives access to all the methods from class\nL<C<Exception>|/type/Exception>, like C<backtrace> and C<rethrow>.\n\nYou can obtain the original object with the C<payload> method.\n\n    try {\n        die [404, 'File not found']; # throw non-exception object\n    }\n    print \"Got HTTP code \",\n        $!.payload[0],          # 404\n        \" and backtrace \",\n        $!.backtrace.Str;\n\nNote that young code will often be prototyped using C<X::AdHoc> and then later\nbe revised to use more specific subtypes of L<C<Exception>|/type/Exception>. As such it is usually\nbest not to explicitly rely on receiving an C<X::AdHoc> – in many cases using\nthe string returned by the C<.message> method, which all L<C<Exception>|/type/Exception>s must\nhave, is preferable. Please note that we need to explicitly call C<.Str> to\nstringify the backtrace correctly.\n\n=head1 Methods\n\n=head2 method payload\n\nReturns the original object which was passed to C<die>.\n\n=head2 method Numeric\n\n    method Numeric()\n\nConverts the payload to L<C<Numeric>|/type/Numeric> and returns it\n\n=head2 method from-slurpy\n\n    method from-slurpy (|cap)\n\nX<|Reference,SlurpySentry>\nCreates a new exception from a capture and returns it. The capture will have the\nC<SlurpySentry> role mixed in, so that the C<.message> method behaves in a\ndifferent when printing the message.\n\n=for code\ntry {\n    X::AdHoc.from-slurpy( 3, False, \"Not here\" ).throw\n};\nprint $!.payload.^name; # OUTPUT: «Capture+{X::AdHoc::SlurpySentry}»\nprint $!.message;       # OUTPUT: «3FalseNot here»\n\nThe C<SlurpySentry> role joins the elements of the payload, instead of directly\nconverting them to a string.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Anon/Augment.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Anon::Augment\n\n=SUBTITLE Compilation error due to augmenting an anonymous package\n\n    class X::Anon::Augment does X::Comp { }\n\nCompile time error thrown when trying to augment an anonymous package.\n\nFor example\n\n=for code :skip-test<compile time error>\nuse MONKEY-TYPING;\naugment class { }\n\nDies with\n\n=for code :lang<text>\nCannot augment anonymous class\n\n=head1 Methods\n\n=head2 method package-kind\n\n    method package-kind returns Str:D\n\nReturns the kind of package (module, class, grammar, ...) that the code\ntried to augment.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Anon/Multi.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Anon::Multi\n\n=SUBTITLE Compilation error due to declaring an anonymous multi\n\n    class X::Anon::Multi does X::Comp { }\n\nCompile time error thrown when an anonymous multi is being declared.\n\nFor example\n\n=for code :skip-test<compile time error>\nmulti method () { }\n\ndies with\n\n=for code :lang<text>\nCannot put multi on anonymous method\n\n=head1 Methods\n\n=head2 method multiness\n\n    method multiness(--> Str:D)\n\nReturns a string describing the multiness that the original code used, for\nexample C<\"multi\"> or C<\"proto\">.\n\n=head2 method routine-type\n\n    method routine-type(--> Str:D)\n\nReturns a string describing the type of routine that was declared, for example\nC<\"sub\"> or C<\"method\">.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Assignment/RO.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Assignment::RO\n\n=SUBTITLE Exception thrown when trying to assign to something read-only\n\n    class X::Assignment::RO is Exception {}\n\nCode like\n\n    sub f() { 42 };\n    f() = 'new value';  # throws an X::Assignment::RO\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Assignment::RO: Cannot modify an immutable Any␤»\n\nthrows an exception of type C<X::Assignment::RO>.\n\n=head1 Methods\n\n=head2 method typename\n\n    method typename(X::Assignment::RO:D: --> Str)\n\nReturns the type name of the value on the left-hand side\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Attribute/NoPackage.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Attribute::NoPackage\n\n=SUBTITLE Compilation error due to declaring an attribute outside of a package\n\n    class X::Attribute::NoPackage does X::Comp { }\n\nCompile time error thrown when an attribute is declared where it does\nnot make sense (for example in the mainline).\n\nFor example\n\n=for code\nhas $.x;\n\nDies with\n\n=for code :lang<text>\nYou cannot declare attribute '$.x' here; maybe you'd like a class or a role?\n\n=head1 Methods\n\n=head2 method name\n\n    method name(--> Str:D)\n\nReturns the name of the attribute\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Attribute/Package.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Attribute::Package\n\n=SUBTITLE Compilation error due to declaring an attribute in an ineligible package\n\n    class X::Attribute::Package does X::Comp { }\n\nCompile time error, thrown when the compiler encounters an attribute\ndeclaration inside a package that does not support attributes.\n\nFor example\n\n=for code :skip-test<compile time error>\nmodule A { has $.x }\n\ndies with\n\n=for code :lang<text>\nA module cannot have attributes, but you tried to declare '$.x'\n\n=head1 Methods\n\n=head2 method name\n\n    method name(--> Str:D)\n\nReturns the name of the attribute that triggered this error.\n\n=head2 method package-kind\n\n    method package-kind(--> Str:D)\n\nReturns the kind of package (package, module) that doesn't support attributes.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Attribute/Required.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Attribute::Required\n\n=SUBTITLE Compilation error due to not declaring an attribute with the C<is required> trait\n\n    class X::Attribute::NoPackage does X::MOP { }\n\nCompile time error thrown when a required attribute is not assigned when\ncreating an object.\n\nFor example\n\n=for code\nmy class Uses-required {\n    has $.req is required\n};\nmy $object = Uses-required.new()\n\nDies with\n\n=for code :lang<text>\nOUTPUT: «(exit code 1) The attribute '$!req' is required, but you did not provide a value for it.␤»\n\n=head1 Methods\n\n=head2 method name\n\n    method name(--> Str:D)\n\nReturns the name of the attribute.\n\n=head2 method why\n\n    method why(--> Str:D)\n\nReturns the reason why that attribute is required, and it will be included in\nthe message if provided. That reason is taken directly from the C<is required>\ntrait.\n\n=for code :skip-test<compile time error>\nmy class Uses-required {\n    has $.req is required(\"because yes\")\n};\nmy $object = Uses-required.new();                                  │\n# OUTPUT:\n# «(exit code 1) The attribute '$!req' is required because because yes,␤\n# but you did not provide a value for it.␤»\n\n\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Attribute/Undeclared.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Attribute::Undeclared\n\n=SUBTITLE Compilation error due to an undeclared attribute\n\n    class X::Attribute::Undeclared is X::Undeclared { }\n\nThrown when code refers to an attribute that has not been declared.\n\nFor example the code\n\n=for code :skip-test<compile time error>\nclass A { method m { $!notthere } }\n\nProduces the error\n\n=for code :lang<text>\nAttribute $!notthere not declared in class A\n\n=head1 Methods\n\n=head2 method package-kind\n\nReturns the kind of package the attribute was used in (for example C<class>,\nC<grammar>)\n\n=head2 method package-name\n\nReturns the name of the package in which the offensive attribute reference\nwas performed.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Augment/NoSuchType.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Augment::NoSuchType\n\n=SUBTITLE Compilation error due to augmenting a non-existing type\n\n    class X::Augment::NoSuchType does X::Comp { }\n\nThrown when trying to augment a type which doesn't exist.\n\nFor example\n\n=for code :skip-test<compile time error>\nuse MONKEY-TYPING;\naugment class NoSuch { }\n\ndies with\n\n=for code :lang<text>\nYou tried to augment class NoSuch, but it does not exist\n\n=head1 Methods\n\n=head2 method package-kind\n\n    method package-kind(--> Str:D)\n\nReturns the kind of package (class, grammar) that is being tried to augment\n\n=head2 method package\n\nReturns the name that was tried to augment, but which doesn't exist.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Bind/NativeType.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Bind::NativeType\n\n=SUBTITLE Compilation error due to binding to a natively typed variable\n\n    class X::Bind::NativeType does X::Comp { }\n\nCompile-time error thrown when trying to bind to a natively typed variable.\n\nSince native variables explicitly don't have the concept of a container at\nruntime, it does not make sense to support both binding and assignment;\nRaku supports only assignment (which makes more sense, because native\ntypes are value types).\n\nFor example the code\n\n=for code :skip-test<compile time error>\nmy int $x := 3;\n\ndies with\n\n=for code :lang<text>\nCannot bind to natively typed variable '$x'; use assignment instead\n\nand can be fixed by writing it as\n\n    my int $x = 3;\n\n=head1 Methods\n\n=head2 method name\n\n    method name(--> Str:D)\n\nReturns the name of the variable.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Bind/Slice.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Bind::Slice\n\n=SUBTITLE Error due to binding to a slice\n\n    class X::Bind::Slice is Exception {}\n\nWhen you try to bind to an array or hash slice:\n\n    my @a; @a[0, 1] := [42];\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Bind::Slice: Cannot bind to Array slice␤»\n\nand\n\n    my %h; %h<a b> := {};\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Bind::Slice: Cannot bind to Hash slice␤»\n\nyou get an exception of type C<::Bind::Slice>.\n\n=head1 Methods\n\n=head2 method type\n\n    method type(X::Bind::Slice:D:)\n\nreturns the type object of the thing that you tried to slice-bind, for example\nL<C<Array>|/type/Array>, L<C<List>|/type/List> or L<C<Hash>|/type/Hash>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Bind.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Bind\n\n=SUBTITLE Error due to binding to something that is not a variable or container\n\n    class X::Bind is Exception {}\n\nIf you write code like this:\n\n=begin code :skip-test<compile time error>\nfloor(1.1) := 42;\n=end code\n\nit dies with an C<X::Bind> exception:\n\n=begin code :lang<text>\nCannot use bind operator with this left-hand side\n=end code\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Caller/NotDynamic.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Caller::NotDynamic\n\n=SUBTITLE Error while trying to access a non dynamic variable through CALLER\n\n    class X::Caller::NotDynamic is Exception { }\n\nThrown when trying to access a non dynamic variable through CALLER\n\nA typical error message is\n\n=for code :lang<text>\nCannot access '$x' through CALLER, because it is not declared as dynamic\n\n=head1 Methods\n\n=head2 method symbol\n\nReturns the name of the symbol that was passed to CALLER.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Cannot/Empty.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Cannot::Empty\n\n=SUBTITLE Error due to inappropriate usage of an empty collection\n\n    class X::Cannot::Empty is Exception { }\n\nError, typically wrapped in a L<C<Failure>|/type/Failure>, when inappropriately\nusing an empty collection.\n\nFor example, the following stack implementation fails when trying to pop a value\nfrom an empty stack. Sink context causes the returned L<C<Failure>|/type/Failure> to throw.\n\n=begin code\nclass Stack {\n    my class Node {\n        has $.value;\n        has Node $.next;\n    }\n    has Node $!next;\n\n    method push($value) {\n        $!next .= new(:$value, :$!next);\n        self;\n    }\n\n    method pop() {\n        fail X::Cannot::Empty.new(:action<pop>, :what(self.^name))\n         unless $!next;\n\n        my $value = $!next.value;\n        $!next .= next;\n        $value;\n    }\n}\n\nmy $stack = Stack.new.push(42);\nsay $stack.pop; # OUTPUT: «42␤»\ntry $stack.pop;\nsay $!.message; # OUTPUT: «Cannot pop from an empty Stack␤»\n=end code\n\n=head1 Methods\n\n=head2 method action\n\n    method action()\n\nVerbal description of the inappropriate action.\n\n=head2 method what\n\n    method what()\n\nReturns the type that was the target of the action.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Cannot/Lazy.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Cannot::Lazy\n\n=SUBTITLE Error due to inappropriate usage of a lazy list\n\n    class X::Cannot::Lazy is Exception { }\n\nError thrown (or wrapped in a L<C<Failure>|/type/Failure>) when inappropriately using a\nlist that C<.is-lazy>. Such a list can be infinite which would make it\nimpossible to iterate over all values.\n\n=head1 Methods\n\n=head2 method action\n\n    method action()\n\nVerbal description of the inappropriate action.\n\n=head2 method what\n\n    method what()\n\nReturns the type that was the target of the action, if it was not the\nlazy list itself.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Channel/ReceiveOnClosed.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Channel::ReceiveOnClosed\n\n=SUBTITLE Error due to calling receive on a closed channel\n\n    class X::Channel::ReceiveOnClosed {}\n\nThis exception is thrown when a calling C<receive> on a L<C<Channel>|/type/Channel> that has been closed:\n\n    my $s = Channel.new;\n    $s.close;\n    $s.receive;     # Cannot receive a message on a closed channel\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Channel::ReceiveOnClosed: Cannot receive a message on a closed channel␤»\n\n=head1 Methods\n\n=head2 method channel\n\n    method Channel(X::Channel::ReceiveOnClosed:D: --> Channel:D)\n\nReturns the Channel object on which the C<receive> method was called.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Channel/SendOnClosed.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Channel::SendOnClosed\n\n=SUBTITLE Error due to calling send on a closed channel\n\n    class X::Channel::SendOnClosed {}\n\nThis exception is thrown when a calling C<send> on a L<C<Channel>|/type/Channel> that has been closed:\n\n    my $s = Channel.new;\n    $s.close;\n    $s.send(42);\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Channel::SendOnClosed: Cannot send a message on a closed channel␤»\n\n=head1 Methods\n\n=head2 method channel\n\n    method Channel(X::Channel::SendOnClosed:D: --> Channel:D)\n\nReturns the Channel object on which the C<send> method was called.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Comp.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"exception\")\n\n=TITLE role X::Comp\n\n=SUBTITLE Common role for compile-time errors\n\n    role X::Comp is Exception { }\n\nCommon role for compile-time errors.\n\nNote that since the backtrace of a compile time error generally shows\nroutines from the compiler, not from user-space programs, the L<C<Backtrace>|/type/Backtrace>\nreturned from the L<backtrace|/routine/backtrace> method is not very informative. Instead\nthe exception carries its own C<filename>, C<line> and C<column> attributes\nand public accessors.\n\nIf an error occurs while creating an object (like a class or routine) at\ncompile time, generally the exception associated with it does not hold a\nreference to the object (for example a class would not be fully composed, and\nthus not usable). In those cases the name of the would-be-created object\nis included in the error message instead.\n\n=head1 Methods\n\n=head2 method filename\n\nThe filename in which the compilation error occurred\n\n=head2 method line\n\nThe line number in which the compilation error occurred.\n\n=head2 method column\n\nThe column number of location where the compilation error occurred.\n(Rakudo does not implement that yet).\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Composition/NotComposable.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Composition::NotComposable\n\n=SUBTITLE Compilation error due to composing an ineligible type\n\n    class X::Composition::NotComposable is Exception { }\n\nThrown when trying to compose a type into a target type, but the composer type\ncannot be used for composition (roles and enums are generally OK).\n\nFor example\n\n=for code :skip-test<compile time error>\nclass B { }\nclass C does B { }\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\n␤B is not composable, so C cannot compose it\n\nbecause C<does> is reserved for role composition, and C<B> is not a role,\nnor something that knows how to turn into a role.\n\nThe fix is to either make C<B> a role, or use inheritance\n(C<class C is B { }>) instead.\n\n=head1 Methods\n\n=head2 method target-name\n\n    method target-name(--> Str:D)\n\nReturns the name of the type that should be composed, but failed.\n\n=head2 method composer\n\n    method composer(--> Mu)\n\nReturns the type that should be composed into the target, but which isn't a\nrole.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Constructor/Positional.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Constructor::Positional\n\n=SUBTITLE Error due to passing positional arguments to a default constructor\n\n    class X::Constructor::Positional is Exception { }\n\nThrown from L<Mu.new|/type/Mu#method_new> when positional arguments are passed to it.\n\nFor example\n\n    class A { };\n    A.new(2, 3);\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Constructor::Positional: Default constructor for 'A' only takes named arguments␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Control.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE role X::Control\n\n=SUBTITLE Role for control exceptions\n\n    role X::Control is Exception { }\n\nThis role turns an exception into a\nL<control exception|/language/exceptions#Control_exceptions>, such as\nL<C<CX::Next>|/type/CX::Next> or L<C<CX::Take>|/type/CX::Take>. It has got no code other than the definition.\n\nSince Rakudo 2019.03, C<throw>ing an object that mixes in this role\nC<X::Control> can raise a control exception which is caught by the L<CONTROL\nphaser|/language/phasers#CONTROL> instead of L<CATCH|/language/phasers#CATCH>.\nThis allows to define custom control exceptions.\n\nFor example, the custom C<CX::Vaya> control exception we define below:\n\n=begin code\nclass CX::Vaya does X::Control {\n    has $.message\n}\n\nsub ea {\n    CONTROL {\n        default {\n            say \"Controlled { .^name }: { .message }\"\n        }\n    }\n    CX::Vaya.new( message => \"I messed up!\" ).throw;\n\n}\nea;\n# OUTPUT: «Controlled CX::Vaya: I messed up!␤»\n=end code\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/ControlFlow/Return.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::ControlFlow::Return\n\n=SUBTITLE Error due to calling return outside a routine\n\n    class X::ControlFlow::Return is X::ControlFlow { }\n\nThrown when a C<return> is called from outside a routine.\n\n    return;\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::ControlFlow::Return: Attempt to return outside of any Routine␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/ControlFlow.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::ControlFlow\n\n=SUBTITLE Error due to calling a loop control command in an ineligible scope\n\n    class X::ControlFlow is Exception { }\n\nThrown when a control flow construct (such as C<next> or C<redo>) is called\noutside the dynamic scope of an enclosing construct that is supposed to catch\nthem.\n\nFor example\n\n    last;\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::ControlFlow: last without loop construct␤»\n\n=head1 Methods\n\n=head2 method illegal\n\n    method illegal returns Str:D\n\nReturns the name of the control flow command that was called.\n\n=head2 method enclosing\n\n    method enclosing returns Str:D\n\nReturns the name of the missing enclosing construct.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/DateTime/TimezoneClash.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::DateTime::TimezoneClash\n\n=SUBTITLE Error due to using both timezone offset and :timezone\n\n=for code :skip-test<compile time error>\nclass X::DateTime::TimezoneClash does X::Temporal is Exception { }\n\nThis exception is thrown when code tries to create a L<C<DateTime>|/type/DateTime> object\nspecifying both a timezone offset and the named argument C<:timezone>.\n\n=for code\nsay DateTime.new('2015-12-24T12:23:00+0200');                   # works\nsay DateTime.new('2015-12-24T12:23:00', timezone => 7200);      # works\nsay DateTime.new('2015-12-24T12:23:00+0200', timezone => 7200); # exception\n\n=head1 Methods\n\n=head2 method message\n\n    method message()\n\nReturns 'DateTime.new(Str): :timezone argument not allowed with a timestamp\noffset'\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Declaration/Scope/Multi.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Declaration::Scope::Multi\n\n=SUBTITLE Compilation error due to declaring a multi with an ineligible scope\n\n    class X::Declaration::Scope::Multi is X::Declaration::Scope { }\n\nThrown when a multi is declared with an incompatible scope.\n\nFor example C<our multi foo() { }> dies with\n\n=for code :lang<text>\n===SORRY!===\nCannot use 'our' with individual multi candidates. Please declare an our-scoped proto instead\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Declaration/Scope.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Declaration::Scope\n\n=SUBTITLE Compilation error due to a declaration with an ineligible scope\n\n=for code\nclass X::Declaration::Scope does X::Comp { }\n\nCompile time error thrown when a declaration does not harmonize with the\ndeclared scope.\n\nFor example\n\n=for code :skip-test<compile time error>\nhas sub f() { }\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nCannot use 'has' with sub declaration\n\n=head1 Methods\n\n=head2 method scope\n\n    method scope(--> Str:D)\n\nReturns a string representation of the scope, usually the same keyword that is\nused for the declaration (C<\"my\">, C<\"our\">, C<\"has\">, ...);\n\n=head2 method declaration\n\n    method declaration(--> Str:D)\n\nDescribes the symbol that has been declared in a wrong scope.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Does/TypeObject.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Does::TypeObject\n\n=SUBTITLE Error due to mixing into a type object\n\n    class X::Does::TypeObject is Exception {}\n\nWhen you try to add one or more roles to a type object with C<does> after it\nhas been composed, an error of type C<X::Does::TypeObject> is thrown:\n\n=for code\nMu does Numeric;    # Cannot use 'does' operator with a type object.\n\nThe correct way to apply roles to a type is at declaration time:\n\n=for code :skip-test<compile time error>\nclass GrassmannNumber does Numeric { ... };\nrole AlgebraDebugger does IO { ... };\ngrammar IntegralParser does AlgebraParser { ... };\n\nRoles may only be runtime-mixed into defined object instances:\n\n=for code :skip-test<compile time error>\nGrassmannNumber.new does AlgebraDebugger;\n\n(This restriction may be worked around by using\nL<augment or supersede|/language/variables#The_augment_declarator>, or\nwith dark Metamodel magics, but this will likely result in a\nsignificant performance penalty.)\n\n=head1 Methods\n\n=head2 method type\n\n    method type(X::Does::TypeObject:D: --> Mu:U)\n\nReturns the type object into which the code tried to mix in a role.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Dynamic/NotFound.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Dynamic::NotFound\n\n=SUBTITLE Runtime error thrown when a dynamic variable does not exist\n\n    class X::Dynamic::NotFound is Exception {}\n\nThis exception is raised when a dynamic variable that has not been declared\nis used.\n\n=for code\n$*dynamic-not-found = 33;\n# OUTPUT: «Dynamic variable $*dynamic-not-found not found␤»\n\n=head1 Methods\n\n=head2 method name\n\n    method name(--> Str:D)\n\nReturns the name of the variable that has not been found.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Eval/NoSuchLang.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Eval::NoSuchLang\n\n=SUBTITLE Error due to specifying an unknown language for EVAL\n\n    class X::Eval::NoSuchLang is Exception { }\n\nError thrown when C<EVAL($str, :$lang)> specifies a language that the\ncompiler does not know how to handle.\n\nFor example\n\n    EVAL 'boo', lang => \"bar\";\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Eval::NoSuchLang: No compiler available for language 'bar'␤»\n\n\n=head1 Methods\n\n=head2 method lang\n\n    method lang()\n\nReturns the language that L<EVAL|/routine/EVAL> did not know how to handle.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Export/NameClash.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Export::NameClash\n\n=SUBTITLE Compilation error due to exporting the same symbol twice\n\n    class X::Export::NameClash does X::Comp { }\n\nCompile time error thrown when a symbol is exported twice.\n\nFor example\n\n=for code :skip-test<compile time error>\nsub f() is export { };\n{\n    sub f() is export { }\n}\n\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nA symbol '&f' has already been exported\n\n=head1 Methods\n\n=head2 method symbol\n\nReturns the symbol that is exported twice.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/IO/BinaryMode.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::IO::BinaryMode\n\n=SUBTITLE Error while invoking methods on a handle in binary mode.\n\n=for code :skip-test<compile time error>\nclass X::IO::BinaryMode does X::IO is Exception { }\n\nThrown from certain L<C<IO::Handle>|/type/IO::Handle> methods if the handle is L<in binary mode|/type/IO/Handle#method_encoding>.\n\nA typical error message is\n\n=for code :lang<text>\nCannot do 'comb' on a handle in binary mode.\n\n=head1 Methods\n\n=head2 method trying\n\nReturns a string describing the failed operation; in this example, C<comb>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/IO/Chdir.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::IO::Chdir\n\n=SUBTITLE Error while trying to change the working directory\n\n=for code :skip-test<compile time error>\nclass X::IO::Chdir does X::IO is Exception { }\n\nError class when a L<chdir|/routine/chdir> call failed.\n\nFor example\n\n=for code\nchdir '/home/other'\n\nthrows\n\n=for code :lang<text>\nFailed to change the working directory to '/home/other': permission denied\n\n=head1 Methods\n\n=head2 method path\n\nReturns the path that was passed to the failed C<chdir> call.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/IO/Chmod.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::IO::Chmod\n\n=SUBTITLE Error while trying to change file permissions\n\n=for code :skip-test<compile time error>\nclass X::IO::Chmod does X::IO is Exception { }\n\nError class for failed C<chmod> calls.\n\nA typical error message is\n\n=for code :lang<text>\nFailed to set the mode of '/home/other' to '0o777': Permission denied\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/IO/Chown.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::IO::Chown\n\n=SUBTITLE Error while trying to change file ownership\n\n=for code :skip-test<compile time error>\nclass X::IO::Chown does X::IO is Exception { }\n\nError class for failed C<chown> calls.\n\nA typical error message is\n\n=for code :lang<text>\nFailed to change owner of '/home/other' to :137/666: Permission denied\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/IO/Copy.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::IO::Copy\n\n=SUBTITLE Error while trying to copy a file\n\n=for code :skip-test<compile time error>\nclass X::IO::Copy does X::IO is Exception { }\n\nError class for failed file copy operations. A typical error message is\n\n=for code :lang<text>\nFailed to copy 'source' to 'destination': permission denied\n\n=head1 Methods\n\n=head2 method from\n\nReturns the source of the failed copy operation\n\n=head2 method to\n\nReturns the destination of the failed copy operation\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/IO/Cwd.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::IO::Cwd\n\n=SUBTITLE Error while trying to determine the current working directory\n\n=for code :skip-test<compile time error>\nclass X::IO::Cwd does X::IO is Exception { }\n\nError class when the runtime fails to determine the current directory.\n\nA typical error message is\n\n=for code :lang<text>\nFailed to get the working directory: permission denied\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/IO/Dir.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::IO::Dir\n\n=SUBTITLE Error while trying to get a directory's contents\n\n=for code :skip-test<compile time error>\nclass X::IO::Dir does X::IO is Exception { }\n\nError class that is thrown when a L<dir|/routine/dir> call fails.\n\nA typical error message is\n\n=for code :lang<text>\nFailed to get the directory contents of '/tmp/': No such file or directory\n\n=head1 Methods\n\n=head2 method path\n\nReturns the path that L<dir|/routine/dir> failed to read.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/IO/DoesNotExist.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::IO::DoesNotExist\n\n=SUBTITLE Error while doing file tests on a non existing path\n\n=for code :skip-test<compile time error>\nclass X::IO::DoesNotExist does X::IO is Exception { }\n\nThrown when doing file test operations on a non existing path.\n\nA typical error message is\n\n=for code :lang<text>\nFailed to find 'euler-5.raku' while trying to do '.f'\n\n=head1 Methods\n\n=head2 method path\n\nReturns the path that was passed to the failed call.\n\n=head2 method trying\n\nReturns a string describing the failed operation.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/IO/Flush.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::IO::Flush\n\n=SUBTITLE Error while trying to flush IO handles\n\n=for code :skip-test<compile time error>\nclass X::IO::Flush does X::IO is Exception { }\n\nError class for failures during handle flushes.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/IO/Link.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::IO::Link\n\n=SUBTITLE Error while trying to create a link\n\n=for code :skip-test<compile time error>\nclass X::IO::Link does X::IO is Exception { }\n\nError class for failed L<link|/routine/link> operation.\n\nA typical error message is\n\n=for code :lang<text>\nFailed to create link called 'my-link' on target 'does-not exist': Failed to link file\n\n=head1 Methods\n\n=head2 method target\n\nReturns the name of the link target, i.e. the existing file.\n\n=head2 method name\n\nReturns the name of the link that could not be created.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/IO/Lock.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::IO::Lock\n\n=SUBTITLE Error while trying to lock handles\n\n=for code :skip-test<compile time error>\nclass X::IO::Flush does X::IO is Exception { }\n\nError class for failures while locking handles. Typical errors include:\n\"Cannot create a non-shared lock on a read-only filehandle\" and\n\"Cannot create a shared lock on a write-only filehandle\".\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/IO/Mkdir.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::IO::Mkdir\n\n=SUBTITLE Error while trying to create a directory\n\n=for code :skip-test<compile time error>\nclass X::IO::Mkdir does X::IO is Exception { }\n\nError class for failed L<mkdir|/routine/mkdir> operations.\n\nA typical error message is\n\n=for code :lang<text>\nFailed to create directory 'destination' with mode '0o755': File exists\n\n=head1 Methods\n\n=head2 method path\n\nReturns the path that the L<mkdir|/routine/mkdir> operation failed to create.\n\n=head2 method mode\n\nReturns the permissions mask of the failed L<mkdir|/routine/mkdir> operation as an L<C<Int>|/type/Int>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/IO/Move.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::IO::Move\n\n=SUBTITLE Error while trying to move a file\n\n=for code :skip-test<compile time error>\nclass X::IO::Move does X::IO is Exception { }\n\nError class for a failed file move operation. A typical\nerror message is\n\n=for code :lang<text>\nFailed to move '/tmp/alpha.raku' to 'test.raku': :createonly specified and destination exists\n\n=head1 Methods\n\n=head2 method from\n\nReturns the source of the failed L<move|/routine/move> operation\n\n=head2 method to\n\nReturns the destination of the failed L<move|/routine/move> operation\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/IO/Rename.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::IO::Rename\n\n=SUBTITLE Error while trying to rename a file or directory\n\n=for code :skip-test<compile time error>\nclass X::IO::Rename does X::IO is Exception { }\n\nError class for failed file or directory rename operations. A typical\nerror message is\n\n=for code :lang<text>\nFailed to rename 'source' to 'destination': is a directory\n\n=head1 Methods\n\n=head2 method from\n\nReturns the source of the failed rename operation\n\n=head2 method to\n\nReturns the destination of the failed rename operation\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/IO/Rmdir.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::IO::Rmdir\n\n=SUBTITLE Error while trying to remove a directory\n\n=for code :skip-test<compile time error>\nmy class X::IO::Rmdir does X::IO is Exception { }\n\nError class for failed L<rmdir|/routine/rmdir> operations.\n\nA typical error message is\n\n=for code :lang<text>\nFailed to remove the directory 'lib': Directory not empty\n\n=head1 Methods\n\n=head2 method path\n\nReturns the path L<rmdir|/routine/rmdir> failed to remove\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/IO/Symlink.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::IO::Symlink\n\n=SUBTITLE Error while trying to create a symbolic link\n\n=for code :skip-test<compile time error>\nclass X::IO::Symlink does X::IO is Exception { }\n\nError class for failed L<symlink|/routine/symlink> creation.\n\nA typical error message is\n\n=for code :lang<text>\nFailed to create symlink called 'euler' on target '/home/myhome/euler-1.raku': Failed to symlink file: file already exist\n\n=head1 Methods\n\n=head2 method name\n\nReturns the path that L<symlink|/routine/symlink> failed to create.\n\n=head2 method target\n\nReturns the path that L<symlink|/routine/symlink> failed to create a link to.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/IO/Unlink.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::IO::Unlink\n\n=SUBTITLE Error while trying to remove a file\n\n=for code :skip-test<compile time error>\nclass X::IO::Unlink does X::IO is Exception { }\n\nError class for failed L<unlink|/routine/unlink> operation.\n\nA typical error message is\n\n=for code :lang<text>\nFailed to remove the file 'secret': Permission defined\n\n=head1 Methods\n\n=head2 method path\n\nReturns the path that L<unlink|/routine/unlink> failed to delete.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/IO.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"exception\")\n\n=TITLE role X::IO\n\n=SUBTITLE IO related error\n\n    role X::IO does X::OS {}\n\nCommon role for IO related errors.\n\nThis role does not provide any additional methods.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Inheritance/NotComposed.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Inheritance::NotComposed\n\n=SUBTITLE Error due to inheriting from a type that's not composed yet\n\n    class X::Inheritance::NotComposed is Exception {}\n\nWhen you try to inherit from a class that hasn't been\nL<composed|/language/mop#Composition_time_and_static_reasoning>, an\nexception of type X::Inheritance::NotComposed is thrown.\n\nUsually this happens because it's not yet fully parsed, or that is stubbed:\n\nFor example\n\n=for code :skip-test<compile time error>\nclass A { ... };    # literal ... for stubbing\nclass B is A { };\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\n'B' cannot inherit from 'A' because 'A' isn't composed yet (maybe it is stubbed)\n\nThe second common way to trigger this error is by trying to inherit from a\nclass from within the class body.\n\nFor example\n\n=for code :skip-test<compile time error>\nclass Outer {\n    class Inner is Outer {\n    }\n}\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\n'Outer::Inner' cannot inherit from 'Outer' because 'Outer' isn't composed yet (maybe it is stubbed)\n\n=head1 Methods\n\n=head2 method child-name\n\n    method child-name(X::Inheritance::NotComposed:D: --> Str:D)\n\nReturns the name of the type that tries to inherit.\n\n=head2 method parent-name\n\n    method parent-name(X::Inheritance::NotComposed:D: --> Str:D)\n\nReturns the name of the parent type that the type tries to inherit from\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Inheritance/Unsupported.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Inheritance::Unsupported\n\n=SUBTITLE Compilation error due to inheriting from an ineligible type\n\n    class X::Inheritance::Unsupported does X::Comp { }\n\nCompile time error thrown when trying to inherit from a type that does\nnot support inheritance (like a package or an enum).\n\nFor example\n\n=for code :skip-test<compile time error>\nenum E <Ex Ey>;\nclass B is E { };\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nE does not support inheritance, so B cannot inherit from it\n\n=head1 Methods\n\n=head2 method child-typename\n\nThe name of the type that tries to inherit.\n\n=head2 method parent\n\nThe type object that the child tried to inherit from.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Method/InvalidQualifier.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Method::InvalidQualifier\n\n=SUBTITLE Error due to calling a qualified method from an ineligible class\n\n    class X::Method::InvalidQualifier is Exception { }\n\nThrown when a method is call in the form C<$invocant.TheClass::method> if\nC<$invocant> does not conform to C<TheClass>.\n\nFor example\n\n    1.Str::split(/a/);\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Method::InvalidQualifier: Cannot dispatch to method split on Str because it is not inherited or done by Int␤»\n\n=head1 Methods\n\n=head2 method method\n\n    method method(--> Str:D)\n\nReturns the name of the (unqualified) method.\n\n=head2 method invocant\n\nReturns the invocant of the failed, qualified method call\n\n=head2 method qualifier-type\n\nReturns the type by which the method call was qualified.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Method/NotFound.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Method::NotFound\n\n=SUBTITLE Error due to calling a method that isn't there\n\n    class X::Method::NotFound is Exception {}\n\nThrown when the user tries to call a method that isn't there.\n\nFor example\n\n=for code\n1.no-such\n\nthrows\n\n=for code :lang<text>\nNo such method 'no-such' for invocant of type 'Int'\n\n=head1 Methods\n\n=head2 method method\n\n    method method(--> Str:D)\n\nReturns the method name that was invoked.\n\n=head2 method typename\n\n    method typename(--> Str:D)\n\nReturns the name of the invocant type.\n\n=head2 method private\n\n    method private(--> Bool:D)\n\nReturns C<True> for private methods, and C<False> for public methods.\n\n=head2 method addendum\n\n    method addendum(--> Str:D)\n\nReturns additional explanations or hints.\n\nI<Note>: C<addendum> was introduced in Rakudo 2019.03.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Method/Private/Permission.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Method::Private::Permission\n\n=SUBTITLE Compilation error due to calling a private method without permission\n\n    class X::Method::Private::Permission does X::Comp { }\n\nCompile time error thrown when the code contains a call to a private method\nthat isn't defined in the current class, and when no appropriate trusts\nrelation is defined that permits the private method call.\n\nFor example\n\n=for code :skip-test<compile time error>\n1!Int::foo\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nCannot call private method 'foo' on package Int because it does not trust GLOBAL\n\n=head1 Methods\n\n=head2 method method\n\n    method method(--> Str:D)\n\nThe name of the private method\n\n=head2 method source-package\n\n    method source-package(--> Mu:D)\n\nReturns the type object that (supposedly) contains the private method.\n\n=head2 method calling-package\n\n    method calling-package(--> Mu:D)\n\nReturns the package in which the calling code is, and which the source package\ndoes not trust.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Method/Private/Unqualified.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Method::Private::Unqualified\n\n=SUBTITLE Compilation error due to an unqualified private method call\n\n    class X::Method::Private::Unqualified does X::Comp { }\n\nCompile time error thrown when a private method call on anything but C<self>\nis not fully qualified.\n\nFor example\n\n=for code\n1!priv\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nPrivate method call to priv must be fully qualified with the package containing the method\n\n=head1 Methods\n\n=head2 method method\n\n    method method(--> Str:D)\n\nReturns the name of the private method that triggered the error.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Mixin/NotComposable.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Mixin::NotComposable\n\n=SUBTITLE Error due to using an ineligible type as a mixin\n\n    class X::Mixin::NotComposable is Exception { }\n\nThrown when a mixin with infix C<does> or C<but> is done with a composer that\ncannot be used for mixin.\n\nFor example\n\n    class B { };\n    1 but B;\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Mixin::NotComposable: Cannot mix in non-composable type B into object of type Int␤»\n\nThe compile-time equivalent of this error is L<C<X::Composition::NotComposable>|/type/X::Composition::NotComposable>.\n\n=head1 Methods\n\n=head2 method target\n\n    method target()\n\nReturns the target of the failed mixin operation.\n\n=head2 method rolish\n\n    method rolish()\n\nReturns the thing that could not act as a role for mixing it in\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/NYI.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::NYI\n\n=SUBTITLE Error due to use of an unimplemented feature\n\n    class X::NYI is Exception { }\n\nError class for unimplemented features. I<NYI> stands for I<Not Yet\nImplemented>.\n\nIf a Raku compiler is not yet feature complete, it may throw an C<X::NYI>\nexception when a program uses a feature that it can detect but has\nnot yet implemented.\n\nA full-featured Raku compiler must not throw such exceptions, but\nmust still provide the C<X::NYI> class for compatibility.\n\nA typical error message is\n\n=for code :lang<text>\nHyperWhatever is not yet implemented. Sorry.\n\n=head1 Methods\n\n=head2 method new\n\n    method new( :$feature, :$did-you-mean, :$workaround)\n\nThis is the default constructor for C<X:NYI> which can take three parameters with obvious meanings.\n\n=begin code\nclass Nothing {\n    method ventured( $sub, **@args) {\n        X::NYI.new( feature => &?ROUTINE.name,\n                    did-you-mean => \"gained\",\n                    workaround => \"Implement it yourself\" ).throw;\n    }\n}\n\nmy $nothing = Nothing.new;\n$nothing.ventured(\"Nothing\", \"Gained\");\n=end code\n\nIn this case, we are throwing an exception that indicates that the C<ventured> routine has not been implemented; we use the generic C<&?ROUTINE.name> to not tie the exception to the method name in case it is changed later on. This code effectively throws this exception\n\n=begin code\n# OUTPUT:\n# ventured not yet implemented. Sorry.\n# Did you mean: gained?\n# Workaround: Implement it yourself\n#   in method ventured at NYI.raku line 6\n#   in block <unit> at NYI.raku line 14\n=end code\n\nUsing the exception properties, it composes the message that we see there.\n\n=head2 method feature\n\nReturns a L<C<Str>|/type/Str> describing the missing feature.\n\n=head2 method did-you-mean\n\nReturns a L<C<Str>|/type/Str> indicating the optional feature that is already implemented.\n\n=head2 method workaround\n\nIt helpfully shows a possible workaround for the missing feature, if it's been declared.\n\n=head2 method message\n\nReturns the message including the above properties.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/NoDispatcher.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::NoDispatcher\n\n=SUBTITLE Error due to calling a dispatch command in an ineligible scope\n\n    class X::NoDispatcher is Exception { }\n\nWhen a redispatcher like C<nextsame> is called without being in the\ndynamic scope of a call where a redispatch is possible, an X::NoDispatcher is\nthrown.\n\nFor example\n\n    nextsame; # In the mainline\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::NoDispatcher: nextsame is not in the dynamic scope of a dispatcher␤»\n\n=head1 Methods\n\n=head2 method redispatcher\n\n    method redispatcher(--> Str:D)\n\nReturns the name of the redispatcher function that did not succeed.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Numeric/CannotConvert.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Numeric::CannotConvert\n\n=SUBTITLE Error while trying to coerce a number to another type\n\n    class X::Numeric::CannotConvert is Exception { }\n\nOccurs when an attempt to coerce an L<C<Inf>|/type/Num#Inf> or\na L<C<NaN>|/type/Num#NaN> to a L<C<Numeric>|/type/Numeric> type.\n\n\nFor example\n\n    say Inf.Int;\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Numeric::CannotConvert: Cannot convert Inf to Int␤»\n\nMost other conversion errors throw L<C<X::Numeric::Real>|/type/X::Numeric::Real>.\n\n=head1 Methods\n\n=head2 method source\n\n    method source()\n\nReturns the value that failed to coerce.\n\n=head2 method target\n\n    method target()\n\nReturns the type to which the coercion was attempted.\n\n=head2 method reason\n\n    method reason(--> Str:D)\n\nReturns the reason that the conversion failed.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Numeric/DivideByZero.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Numeric::DivideByZero\n\n=SUBTITLE Error while trying to divide by zero\n\n    class X::Numeric::DivideByZero is Exception { }\n\nOccurs when attempting to divide by zero.\n\nFor example:\n\n    say 1 / 0;\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Numeric::DivideByZero: Attempt to divide by zero when coercing Rational to Str␤»\n\nNote that the error is only thrown when you attempt to do something with the result. A simple\n\n    1/0; # no Error\n\nwill only generate a silent Failure. It's the C<say> in the first example that triggers the exception.\n\n=head1 Methods\n\n=head2 method using\n\n    method using()\n\nIf present, returns the name of the operator used, e.g. C<infix:<%%>>.\n\n=head2 method details\n\n    method details()\n\nIf present, contains some details on the operation that caused the failure.\n\n=head2 method numerator\n\n    method numerator()\n\nIf present, returns the numerator of the operation.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Numeric/Real.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Numeric::Real\n\n=SUBTITLE Error while trying to coerce a number to a Real type\n\n    class X::Numeric::Real is Exception { }\n\nOccurs when an attempt to coerce a L<C<Numeric>|/type/Numeric> to a\nL<C<Real>|/type/Real>, L<C<Num>|/type/Num>, L<C<Int>|/type/Int> or\nL<C<Rat>|/type/Rat> fails (due to a number with a nonzero imaginary part, for instance).\n\nFor example\n\n    say (1+2i).Int;\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Numeric::Real: Can not convert 1+2i to Int: imaginary part not zero␤»\n\n=head1 Methods\n\n=head2 method source\n\n    method source(--> Numeric:D)\n\nReturns the number that failed to coerce to L<C<Real>|/type/Real>.\n\n=head2 method target\n\n    method target()\n\nReturns the type to which the coercion was attempted.\n\n=head2 method reason\n\n    method reason(--> Str:D)\n\nReturns the reason that the conversion failed.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/OS.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"exception\")\n\n=TITLE role X::OS\n\n=SUBTITLE Error reported by the operating system\n\n    role X::OS { has $.os-error }\n\nCommon role for all exceptions that are triggered by some error\nreported by the operating system (failed IO, system calls,\nfork, memory allocation).\n\n=head1 Methods\n\n=head2 method os-error\n\n    method os-error(--> Str:D)\n\nReturns the error as reported by the operating system.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Obsolete.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Obsolete\n\n=SUBTITLE Compilation error due to use of obsolete syntax\n\n    class X::Obsolete does X::Comp { }\n\nSyntax error thrown when the user is attempting to use constructs from\nother languages.\n\nFor example\n\n=for code :skip-test<compile time error>\nm/abc/i\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nUnsupported use of /i; in Raku please use :i\n\n=head1 Methods\n\n=head2 method old\n\n    method old(--> Str:D)\n\nReturns a textual description of the obsolete syntax construct\n\n=head2 method replacement\n\n    method replacement(--> Str:D)\n\nDescribes what to use instead of the obsolete syntax.\n\n=head2 method when\n\n    method when(--> Str:D)\n\nReturns a string describing the state of the language (usually\nC<\" in Raku\">).\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/OutOfRange.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::OutOfRange\n\n=SUBTITLE Error due to indexing outside of an allowed range\n\n    class X::OutOfRange is Exception { }\n\nGeneral error when something (for example an array index) is out of an allowed\nrange.\n\nFor example\n\n    say 42[2];\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::OutOfRange: Index out of range. Is: 2, should be in 0..0␤»\n\nsince scalars generally act as a one-element list.\n\n=head1 Methods\n\n=head2 method what\n\n    method what(--> Str:D)\n\nVerbal description of the thing that was out of range (e.g. C<\"array index\">,\nC<\"month\">).\n\n=head2 method got\n\n    method got()\n\nReturns the object that was considered out of range (often an integer)\n\n=head2 method range\n\n    method range(--> Range:D)\n\nReturns a L<C<Range>|/type/Range> object describing the permissible range for the object\nreturned from C<.got>.\n\n=head2 method comment\n\n    method comment(--> Str)\n\nReturns an additional comment that is included in the error message.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Package/Stubbed.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Package::Stubbed\n\n=SUBTITLE Compilation error due to a stubbed package that is never defined\n\n    class X::Package::Stubbed does X::Comp { }\n\nThrown at C<CHECK> time when there are packages stubbed but not later defined.\n\nFor example\n\n=for code :skip-test<compile time error>\nclass A { ... }     # literal ...\nclass B { ... }     # literal ...\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nThe following packages were stubbed but not defined:\n    A\n    B\n\n=head1 Methods\n\n=head2 method packages\n\n    method packages(--> Positional:D)\n\nReturns a list of packages that were stubbed but not defined.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Parameter/Default.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Parameter::Default\n\n=SUBTITLE Compilation error due to an unallowed default value in a signature\n\n    class X::Parameter::Default does X::Comp { }\n\nCompile-time error thrown when a parameter in a signature has default value,\nbut isn't allowed to have one. That is the case with slurpy parameters\n(because a slurpy always binds successfully, even to zero arguments)\nand with mandatory parameters.\n\nExample:\n\n=for code :skip-test<compile time error>\nsub f($x! = 3) { }\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nCannot put default on required parameter $x\n\nAnd\n\n=for code :skip-test<compile time error>\nsub f(*@ = 3) { }\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nCannot put default on anonymous slurpy parameter\n\n=head1 Methods\n\n=head2 method how\n\nReturns a string describing how the parameter is qualified that makes\nit disallow default values, for example C<\"slurpy\"> or C<\"mandatory\">.\n\n=head2 method parameter\n\nReturns the parameter name\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Parameter/MultipleTypeConstraints.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Parameter::MultipleTypeConstraints\n\n=SUBTITLE Compilation error due to a parameter with multiple type constraints\n\n    class X::Parameter::MultipleTypeConstraints does X::Comp { }\n\nCompile time error thrown when a parameter has multiple type constraints.\nThis is not allowed in Raku.0.\n\nExample:\n\n=for code :skip-test<compile time error>\nsub f(Cool Real $x) { }\n\ndies with\n\n=for code :lang<text>\nParameter $x may only have one prefix type constraint\n\n=head1 Methods\n\n=head2 method parameter\n\nReturns the name of the offensive parameter.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Parameter/Placeholder.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Parameter::Placeholder\n\n=SUBTITLE Compilation error due to an unallowed placeholder in a signature\n\n    class X::Parameter::Placeholder does X::Comp { }\n\nThrown when a placeholder parameter is used inside a signature where\na normal parameter is expected. The reason is often that a named parameter\nC<:$param> was misspelled as C<$:param>.\n\nFor example\n\n=for code :skip-test<compile time error>\nsub f($:param) { }\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nIn signature parameter, placeholder variables like $:param are illegal\nyou probably meant a named parameter: ':$param'\n\n=head1 Methods\n\n=head2 method parameter\n\nThe text of the offensive parameter declaration (C<$:param> in the example\nabove).\n\n=head2 method right\n\nSuggestion on how to write the parameter declaration instead (C<:$param> in\nthe example above).\n\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Parameter/Twigil.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Parameter::Twigil\n\n=SUBTITLE Compilation error due to an unallowed twigil in a signature\n\n    class X::Parameter::Twigil does X::Comp { }\n\nThrown when a parameter in a signature has a twigil that it may not have.\nOnly C<!>, C<.> and C<*> as twigils are allowed.\n\nExample:\n\n=for code :skip-test<compile time error>\nsub f($=foo) { }\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nIn signature parameter $=foo, it is illegal to use the = twigil\n\n=head1 Methods\n\n=head2 method parameter\n\nThe name of the offensive parameter (C<$=foo> in the example above)\n\n=head2 method twigil\n\nThe illegally used twigil.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Parameter/WrongOrder.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Parameter::WrongOrder\n\n=SUBTITLE Compilation error due to passing parameters in the wrong order\n\n    class X::Parameter::WrongOrder does X::Comp { }\n\nCompile time error that is thrown when parameters in a signature in the wrong\norder (for example if an optional parameter comes before a mandatory\nparameter).\n\nFor example\n\n=for code :skip-test<compile time error>\nsub f($a?, $b) { }\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nCannot put required parameter $b after optional parameters\n\n=head1 Methods\n\n=head2 method misplaced\n\nReturns the kind of misplaced parameter (for example C<\"mandatory\">,\nC<\"positional\">).\n\n=head2 method parameter\n\nReturns the name of the (first) misplaced parameter\n\n=head2 method after\n\nReturns a string describing other parameters after which the current parameter\nwas illegally placed (for example C<\"variadic\">, C<\"positional\"> or\nC<\"optional\">).\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Phaser/Multiple.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Phaser::Multiple\n\n=SUBTITLE Compilation error due to multiple phasers of the same type\n\n    class X::Phaser::Multiple does X::Comp { }\n\nThrown when multiple phasers of the same type occur in a block, but only one\nis allowed (for example C<CATCH> or C<CONTROL>).\n\nFor example\n\n=for code :skip-test<compile time error>\nCATCH { }; CATCH { }\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nOnly one CATCH block is allowed\n\n=head1 Methods\n\n=head2 method block\n\nReturns the name of the phaser that occurred more than once.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Phaser/PrePost.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Phaser::PrePost\n\n=SUBTITLE Error due to a false return value of a PRE/POST phaser\n\n=for code\nclass X::Phaser::PrePost is Exception { }\n\nThrown when the condition inside a C<PRE> or C<POST> phaser evaluate to a\nfalse value.\n\nFor example\n\n    sub f($x) { PRE { $x ~~ Int } };\n    f \"foo\";\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: X::Phaser::PrePost: Precondition '{ $x ~~ Int }' failed«␤»\n\n=head1 Methods\n\n=head2 method phaser\n\n    method phaser(--> Str:D)\n\nReturns the name of the failed phaser, C<\"PRE\"> or C<\"POST\">.\n\n=head2 method condition\n\n    method condition(--> Str:D)\n\nReturns the part of the source code that describes the phaser condition.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Placeholder/Block.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Placeholder::Block\n\n=SUBTITLE Compilation error due to a placeholder in an ineligible block\n\n    class X::Placeholder::Block does X::Comp {}\n\nThrown when a placeholder variable is used in a block that does not allow a\nsignature.\n\nFor example\n\n=for code :skip-test<compile time error>\nclass A { $^foo }\n\ndies with\n\n=for code :lang<text>\nPlaceholder variable $^foo may not be used here because the surrounding block takes no signature\n\n=head1 Methods\n\n=head2 method placeholder\n\nReturns the name of the (first) illegally used placeholder.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Placeholder/Mainline.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Placeholder::Mainline\n\n=SUBTITLE Compilation error due to a placeholder in the mainline\n\n    class X::Placeholder::Mainline is X::Placeholder::Block { }\n\nThrown when a placeholder variable is used in the mainline, i.e. outside of\nany explicit block.\n\nFor example\n\n=for code :skip-test<compile time error>\n$^x;\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nCannot use placeholder parameter $^x outside of a sub or block\n\nNote that this error can also occur when you think something is a block,\nbut it really is a L«postcircumfix:<{ }>|/routine/{ }», for example\n\n=for code :skip-test<compile time error>\nmy %h;\nsay %h{ $^x };\n#     ^^^^^^^  not a block, so $^x is part of the mainline\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Pod.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"exception\")\n\n=TITLE role X::Pod\n\n=SUBTITLE Pod related error\n\n    role X::Pod { }\n\nCommon role for Pod related errors.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Proc/Async/AlreadyStarted.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Proc::Async::AlreadyStarted\n\n=SUBTITLE Error due to calling start on an already started Proc::Async object\n\n    class X::Proc::Async::AlreadyStarted is Exception {}\n\nWhen you call C<start> twice on the same L<C<Proc::Async>|/type/Proc::Async>\nobject, the second invocation will die with an\nC<X::Proc::Async::AlreadyStarted> exception.\n\n    my $proc = Proc::Async.new(\"echo\");\n    $proc.start;\n    $proc.start;\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Proc::Async::AlreadyStarted: Process has already been started␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Proc/Async/BindOrUse.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Proc::Async::BindOrUse\n\n=SUBTITLE Error due to trying to bind a handle that is also used\n\n=for code :preamble<role X::Proc::Async {}>\nclass X::Proc::Async::BindOrUse does X::Proc::Async {}\n\nIn general, it occurs when there's some mistake in the direction the stream\nflows, for instance:\n\n=for code\nmy $p = Proc::Async.new(\"ls\", :w);\nmy $h = \"ls.out\".IO.open(:w);\n$p.bind-stdin($h);\n# Fails with OUTPUT: «Cannot both bind stdin to a handle and also use :w␤»\n\nIn this case, C<stdin> is already bound and cannot be used again; one of them\nshould flow C<:out> and the other one C<:w> to work correctly.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Proc/Async/CharsOrBytes.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Proc::Async::CharsOrBytes\n\n=SUBTITLE Error due to tapping the same Proc::Async stream for both text and binary reading\n\n    class X::Proc::Async::CharsOrBytes is Exception {}\n\nA L<C<Proc::Async>|/type/Proc::Async> object allows subscription to the output or error stream\neither for bytes (L<C<Blob>|/type/Blob>) or for text data (L<C<Str>|/type/Str>), but\nnot for both. If you do try both, it throws an exception of type\nC<X::Proc::Async::CharsOrBytes>.\n\n    my $proc = Proc::Async.new('echo');\n    $proc.stdout.tap(&print);\n    $proc.stdout(:bin).tap(&print);\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Proc::Async::CharsOrBytes: Can only tap one of chars or bytes supply for stdout␤»\n\n=head1 Methods\n\n=head2 method handle\n\n    method handle(X::Proc::Async::CharsOrBytes:D: --> Str:D)\n\nReturns the name of the handle that was accessed both for text and for binary\ndata, C<stdout> or C<stderr>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Proc/Async/MustBeStarted.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Proc::Async::MustBeStarted\n\n=SUBTITLE Error due to interacting with a Proc::Async stream before spawning its process\n\n    class X::Proc::Async::MustBeStarted is Exception {}\n\nSeveral methods from L<C<Proc::Async>|/type/Proc::Async> expect that the external program has been\nspawned (by calling C<.start> on it), including C<say>, C<write>, C<print> and\nC<close-stdin>. If one of those methods is called before C<.start> was called,\nthey throw an exception of type C<X::Proc::Async::MustBeStarted>.\n\n    Proc::Async.new('echo', :w).say(42);\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Proc::Async::MustBeStarted: Process must be started first before calling 'say'␤»\n\n=head1 Methods\n\n=head2 method method\n\n    method method(X::Proc::Async::MustBeStarted:D --> Str:D)\n\nReturns the name of the method that was illegally called before starting the\nexternal program.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Proc/Async/OpenForWriting.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Proc::Async::OpenForWriting\n\n=SUBTITLE Error due to writing to a read-only Proc::Async object\n\n    class X::Proc::Async::OpenForWriting is Exception {}\n\nWhen a L<C<Proc::Async>|/type/Proc::Async> object is opened only for reading from the external\nprogram (no C<:w> passed to open), and a write operation such as C<write>,\nC<print> and C<say> is performed, an exception of type\nC<X::Proc::Async::OpenForWriting> is thrown:\n\n    my $proc = Proc::Async.new(\"echo\");\n    $proc.start;\n    $proc.say(42);\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Proc::Async::OpenForWriting: Process must be opened for writing with :w to call 'say'␤»\n\nTo fix that you can use writable commands with :w flag:\n\n    my $prog = Proc::Async.new(:w, 'cat');\n    $prog.stdout.tap( -> $str {\n        print $str;\n    });\n    my $promise = $prog.start;\n    await $prog.say('foo');\n    $prog.close-stdin;\n    await $promise;\n\n=head1 Methods\n\n=head2 method method\n\n    method method(X::Proc::Async::OpenForWriting:D:)\n\nReturns the method name that was called and which caused the exception.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Proc/Async/TapBeforeSpawn.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Proc::Async::TapBeforeSpawn\n\n=SUBTITLE Error due to tapping a Proc::Async stream after spawning its process\n\n    class X::Proc::Async::TapBeforeSpawn is Exception {}\n\nIf the C<stdout> or C<stderr> methods of L<C<Proc::Async>|/type/Proc::Async> are\ncalled after the program has been C<start>ed, an exception of type\nC<X::Proc::Async::TapBeforeSpawn> is thrown.\n\n    my $proc = Proc::Async.new(\"echo\", \"foo\");\n    $proc.start;\n    $proc.stdout.tap(&print);\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Proc::Async::TapBeforeSpawn: To avoid data races, you must tap stdout before running the process␤»\n\nThe right way is the reverse order\n\n    my $proc = Proc::Async.new(\"echo\", \"foo\");\n    $proc.stdout.tap(&print);\n    await $proc.start;\n\n=head1 Methods\n\n=head2 method handle\n\n    method handle(X::Proc::Async::TapBeforeSpawn:D: --> Str:D)\n\nReturns the name of the handle (C<stdout> or C<stderr>) that was accessed after the\nprogram started.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Proc/Async.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"exception\")\n\n=TITLE role X::Proc::Async\n\n=SUBTITLE Exception thrown by Proc::Async\n\n    role X::Proc::Async is Exception { ... }\n\nAll exceptions thrown by L<C<Proc::Async>|/type/Proc::Async> do this common role.\n\n=head1 Methods\n\n=head2 method proc\n\n    method proc(X::Proc::Async:D --> Proc::Async)\n\nReturns the object that threw the exception.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Proc/Unsuccessful.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Proc::Unsuccessful\n\n=SUBTITLE Exception thrown if a Proc object is sunk after the process it ran exited unsuccessfully\n\n    class X::Proc::Unsuccessful is Exception {}\n\n=head1 Methods\n\n=head2 method proc\n\n    method proc(X::Proc::Unsuccessful:D --> Proc)\n\nReturns the object that threw the exception.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Promise/CauseOnlyValidOnBroken.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Promise::CauseOnlyValidOnBroken\n\n=SUBTITLE Error due to asking why an unbroken promise has been broken.\n\n    class X::Promise::CauseOnlyValidOnBroken is Exception { }\n\nThis exception is thrown when code expects a Promise to be broken,\nand asks why it has been broken, but the Promise has in fact,\nnot yet been broken.\n\n=head1 Methods\n\n=head2 method promise\n\n    method promise()\n\nReturns the Promise that was asked about.\n\n=head2 method status\n\n    method status()\n\nReturns the status the Promise had at that time.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Promise/Vowed.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Promise::Vowed\n\n=SUBTITLE Error due to directly trying to keep/break a vowed promise.\n\n    class X::Promise::Vowed is Exception { }\n\nThis exception is thrown when code tries to keep/break an already vowed\npromise without going through the corresponding C<Vow> object.\n\n=head1 Methods\n\n=head2 method promise\n\n    method promise()\n\nReturns the vowed Promise.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Redeclaration.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Redeclaration\n\n=SUBTITLE Compilation error due to declaring an already declared symbol\n\n    class X::Redeclaration does X::Comp { }\n\nThrown when a symbol (variable, routine, type, parameter, ...) is redeclared.\nNote that redeclarations are generally fine in an inner scope, but if the\nredeclaration appears in the same scope as the original declaration,\nit usually indicates an error and is treated as one.\n\nExamples\n\n=for code\nmy $x; my $x;\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nRedeclaration of symbol $x\n\nIt works with routines too:\n\n=for code :skip-test<compile time error>\nsub f() { }\nsub f() { }\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nRedeclaration of routine f\n\nBut those are fine\n\n=for code\nmy $x;\nsub f() {\n    my $x;          # not a redeclaration,\n                    # because it's in an inner scope\n    sub f() { };    # same\n}\n\n\n=head1 Methods\n\n=head2 method symbol\n\nReturns the name of the symbol that was redeclared.\n\n=head2 method what\n\nReturns the kind of symbol that was redeclared. Usually C<symbol>, but can\nalso be C<routine>, C<type> etc.\n\n=head2 method postfix\n\nReturns a string that is attached to the end of the error message. It\nusually explains the particular problem in more detail, or suggests\nway to fix the problem.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Role/Initialization.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Role::Initialization\n\n=SUBTITLE Error due to passing an initialization value to an ineligible role\n\n    class X::Role::Initialization is Exception { }\n\nThrown when the C<SomeRole($init)> syntax is used, but SomeRole does not have\nexactly one public attribute.\n\nFor example:\n\n=begin code :skip-test<X::Role::Initialization>\nrole R { }; \"D2\" but R(2)\nCATCH { default { put .^name, ': ', .Str } }\n# OUTPUT: «X::Role::Initialization: Can only supply an initialization value for a role if it has a single public attribute, but this is not the case for 'R'␤»\n=end code\n\n=head1 Methods\n\n=head2 method role\n\n    method role()\n\nReturns the role that caused the error.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Scheduler/CueInNaNSeconds.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Scheduler::CueInNaNSeconds\n\n=SUBTITLE Error caused by passing NaN to Scheduler.cue as :at, :in, or :every\n\n    class X::Scheduler::CueInNaNSeconds is Exception { }\n\nWhen calling C<ThreadPoolScheduler.cue> or C<CurrentThreadScheduler.cue> with\nC<:at>, C<:in>, or C<:every> as C<NaN>, this exception gets thrown. For\nexample, the following code:\n\n=for code\nmy Cancellation $c = $*SCHEDULER.cue({\n    say 'This will never output :(';\n}, at => NaN);\n\nThrows with:\n\n=for code :lang<text>\nCannot pass NaN as a number of seconds to Scheduler.cue\n\nThis class only exists in releases 2019.05 and later.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Seq/Consumed.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Seq::Consumed\n\n=SUBTITLE Error due to trying to reuse a consumed sequence\n\n    class X::Seq::Consumed is Exception { }\n\nThis exception is thrown when a piece of code tries to reuse\na L<C<Seq>|/type/Seq> which has already been iterated.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Sequence/Deduction.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Sequence::Deduction\n\n=SUBTITLE Error due to constructing a sequence from ineligible input\n\n    class X::Sequence::Deduction is Exception { }\n\nException type thrown when the C<...> sequence operator is being called\nwithout an explicit closure, and the sequence cannot be deduced.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Signature/NameClash.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Signature::NameClash\n\n=SUBTITLE Compilation error due to two named parameters with the same name\n\n    my class X::Signature::NameClash does X::Comp { }\n\nCompile time error thrown when two named parameters have the same name,\npotentially through aliases.\n\nFor example\n\n=for code :skip-test<compile time error>\nsub f(:$a, :a(:@b)) { }\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nName a used for more than one named parameter\n\n=head1 Methods\n\n=head2 method name\n\n    method name(--> Str:D)\n\nReturns the name that was used for more than one parameter.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Signature/Placeholder.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Signature::Placeholder\n\n=SUBTITLE Compilation error due to placeholders in a block with a signature\n\n=for code\nclass X::Signature::Placeholder does X::Comp { }\n\nCompile time error thrown when a block has both an explicit signature\nand placeholder parameters.\n\nFor example\n\n=for code :skip-test<compile time error>\nsub f() { $^x }\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nPlaceholder variable '$^x' cannot override existing signature\n\n=head1 Methods\n\n=head2 method placeholder\n\n    method placeholder(--> Str:D)\n\nReturns the name of a placeholder that was used in a block that already\nhad a signature.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Str/Match/x.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Str::Match::x\n\n=SUBTITLE Invalid argument type for :x argument to Str matching methods\n\n    class X::Str::Match::x is Exception { }\n\nError thrown (or wrapped in a L<C<Failure>|/type/Failure>) if an invalid type is passed to the\nC<:x> argument of C<Str.match> or C<Str.subst>. Only L<C<Numeric>|/type/Numeric> and\nL<C<Range>|/type/Range> types are allowed.\n\nFor example\n\n    say \"foobar\".match(\"o\",:x<hello>);\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Str::Match::x: in Str.match, got invalid value of type Str for :x, must be Int or Range␤»\n\n=head1 Methods\n\n=head2 method source\n\n    method got(--> Str:D)\n\nReturns the type of the invalid argument.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Str/Numeric.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Str::Numeric\n\n=SUBTITLE Error while trying to coerce a string to a number\n\n    class X::Str::Numeric is Exception { }\n\nError thrown (or wrapped in a L<C<Failure>|/type/Failure>) when a conversion from string to\na number fails.\n\nFor example\n\n    say +\"42 answers\";\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::Str::Numeric: Cannot convert string to number: trailing characters after number in '42⏏ answers' (indicated by ⏏)␤»\n\n=head1 Methods\n\n=head2 method source\n\n    method source(--> Str:D)\n\nReturns the string that was attempted to convert to a number\n\n=head2 method pos\n\n    method pos(--> Int:D)\n\nGives the position into the string where the parsing failed.\n\n=head2 method reason\n\n    method reason(--> Int:D)\n\nVerbal description of the reason why the conversion failed.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/StubCode.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::StubCode\n\n=SUBTITLE Runtime error due to execution of stub code\n\n    class X::StubCode is Exception { }\n\nThrown when a piece of stub code (created via C<!!!> or C<...>) is executed.\n\n=head1 Methods\n\n=head2 method message\n\nReturns the custom message provided to C<!!!>, or a reasonable default if none\nwas provided.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/Augment/WithoutMonkeyTyping.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::Augment::WithoutMonkeyTyping\n\n=SUBTITLE Compilation error due to augmenting a type without the C<MONKEY-TYPING> pragma\n\n    class X::Syntax::Augment::WithoutMonkeyTyping does X::Syntax { }\n\nCompile time error thrown when C<augment> is used without C<use MONKEY-TYPING>.\n\nSince C<augment> is considered a rather unsafe and impolite action, you have\nto pre-declare your intent with the C<use MONKEY-TYPING;> pragma.\n\nIf you don't do that, like here\n\n=for code :skip-test<compile time error>\naugment class Int { };\n\nyou get the error\n\n=for code :lang<text>\n===SORRY!===\naugment not allowed without 'use MONKEY-TYPING'\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/Comment/Embedded.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::Comment::Embedded\n\n=SUBTITLE Compilation error due to a malformed inline comment\n\n    class X::Syntax::Comment::Embedded does X::Syntax { }\n\nSyntax error thrown when C<#`> is encountered and it is not followed by\nan opening curly brace.\n\nFor example\n\n=for code :skip-test<invalid>\n#`\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nOpening bracket is required for #` comment\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/Confused.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::Confused\n\n=SUBTITLE Compilation error due to unrecognized syntax\n\n=for code\nclass X::Syntax::Confused does X::Syntax { }\n\nThe most general syntax error, if no more specific error message can be given.\n\nFor example\n\n=for code :skip-test<compile time error>\n1∞\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nConfused\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/InfixInTermPosition.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::InfixInTermPosition\n\n=SUBTITLE Compilation error due to an infix in term position\n\n    class X::Syntax::InfixInTermPosition does X::Syntax { }\n\nSyntax error thrown when the parser expects a term, but finds an infix\noperator instead.\n\nFor example\n\n=for code :skip-test<compile time error>\n1, => 2;\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nPreceding context expects a term, but found infix => instead\n\n=head1 Methods\n\n=head2 method infix\n\n    method infix(--> Str:D)\n\nReturns the symbol of the infix that was found in term position.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/Malformed.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::Malformed\n\n=SUBTITLE Compilation error due to a malformed construct (usually a declarator)\n\n    class X::Syntax::Malformed does X::Syntax {}\n\nThe Raku compiler throws errors of type C<X::Syntax::Malformed> when it\nknows what kind of declaration it is parsing, and encounters a syntax error,\nbut can't give a more specific error message.\n\n=for code :skip-test<compile time error>\nmy Int a;   # throws an X::Syntax::Malformed\n\nproduces\n\n=for code :lang<text>\n===SORRY!===\nMalformed my\nat -e:1\n------> my Int ⏏a\n\n\n=head1 Methods\n\n=head2 method what\n\n    method what(X::Syntax::Malformed:D: --> Str)\n\nReturns a description of the thing that was being parsed.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/Missing.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::Missing\n\n=SUBTITLE Compilation error due to a missing piece of syntax\n\n    class X::Syntax::Missing does X::Syntax { }\n\nSyntax error thrown when the previous piece of syntax requires the\nexistence of another piece of syntax, and that second piece is missing.\n\nFor example\n\n=for code :skip-test<compile time error>\nfor 1, 2, 3;\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nMissing block\n\nbecause a C<for> that is not a statement modifier must be followed by a block.\n\n=head1 Methods\n\n=head2 method what\n\n    method what(--> Str:D)\n\nReturns a string description of the missing syntax element.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/NegatedPair.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::NegatedPair\n\n=SUBTITLE Compilation error due to passing an argument to a negated colonpair\n\n    class X::Syntax::NegatedPair does X::Syntax { }\n\nThrown if a colonpair illegally has a value, for example C<:!a(1)>.\nThis is an error because the C<!> negation implies that the value is C<False>.\n\nA typical error message from this class is I<Argument not allowed on\nnegated pair with key 'a'>.\n\n=head1 Methods\n\n=head2 method key\n\nReturns the key of the pair that caused the error.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/NoSelf.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::NoSelf\n\n=SUBTITLE Compilation error due to implicitly using a C<self> that is not there\n\n    class X::Syntax::NoSelf does X::Syntax { }\n\nCompile time error thrown when C<$.foo> style calls are used where no invocant\nis available.\n\nFor example the code\n\n=for code :skip-test<compile time error>\n$.meth;\n\nin the program body throws the error\n\n=for code :lang<text>\n===SORRY!===\nVariable $.meth used where no 'self' is available\n\nbecause C<$.meth> is short for C<$(self.meth)>, and there is no C<self>\navailable in mainline.\n\n=head1 Methods\n\n=head2 method variable\n\nReturns the variable/method call that caused the error.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/Number/RadixOutOfRange.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::Number::RadixOutOfRange\n\n=SUBTITLE Compilation error due to an unallowed radix in a number literal\n\n    class X::Syntax::Number::RadixOutOfRange does X::Syntax { }\n\nSyntax error that is thrown when the radix of a radix number is\nnot allowed, like C«:1<1>» or C«:42<ouch>».\n\n=head1 Methods\n\n=head2 method radix\n\n    method radix(--> Int:D)\n\nThe offensive radix.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/P5.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::P5\n\n=SUBTITLE Compilation error due to use of Perl-only syntax\n\n    class X::Syntax::P5 does X::Syntax { }\n\nSyntax error thrown when some piece of code is clearly Perl, not Raku.\n\nFor example\n\n=for code :skip-test<compile time error>\nfor my $a (1, 2) { };\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nThis appears to be Perl code\n\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/Perl5Var.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::Perl5Var\n\n=SUBTITLE Compilation error due to use of Perl-only default variables\n\n    class X::Syntax::Perl5Var does X::Syntax { }\n\nSyntax error thrown when some piece of code tries to use one of the old Perl\nvariables (and it does not error for some other reason).\n\n=for code :skip-test<Throws an exception>\nsay $];\n\ndies with\n\n=for code :lang<text>\nUnsupported use of $] variable; in Raku please use $*RAKU.version or $*RAKU.compiler.version\n\nFor every unsupported variable (which include most C<$^'letter'> constructs,\nas well as others like C<$\">, the error message will mention that the\nvariable is unsupported and the equivalent commands you could use.\n\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/Regex/Adverb.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::Regex::Adverb\n\n=SUBTITLE Compilation error due to an unrecognized regex adverb\n\n    class X::Syntax::Regex::Adverb does X::Syntax { }\n\nSyntax error thrown when an unrecognized or illegal regex adverb is\nencountered.\n\nFor example\n\n=for code :skip-test<compile time error>\nrx:g/a/\n\ndies with\n\n=begin code :lang<text>\n===SORRY!===\nAdverb g not allowed on rx\n=end code\n\nbecause C<:g> belongs to a match operation, not a regex itself.\n\n=head1 Methods\n\n=head2 method adverb\n\n    method adverb(--> Str:D)\n\nReturns the illegally used adverb\n\n=head2 method construct\n\n    method construct(--> Str:D)\n\nReturns the name of the construct that adverb was used on (C<m>, C<ms>,\nC<rx>, C<s>, C<ss>).\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/Regex/SolitaryQuantifier.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::Regex::SolitaryQuantifier\n\n=SUBTITLE Compilation error due to a regex quantifier without preceding atom\n\n    class X::Syntax::Regex::SolitaryQuantifier does X::Syntax { }\n\nSyntax error when a stand alone quantifier (without a preceding atom\nto quantify) is encountered in a regular expression.\n\nFor example\n\n=for code :skip-test<compile time error>\n/ * /;\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nQuantifier quantifies nothing\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/Reserved.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::Reserved\n\n=SUBTITLE Compilation error due to use of syntax reserved for future use\n\n    class X::Syntax::Reserved does X::Syntax { }\n\nSyntax error thrown when a syntax is used which is reserved for future\nexpansion.\n\nFor example\n\n=for code :skip-test<compile time error>\nmy @a();\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nThe () shape syntax in array declarations is reserved\n\n=head1 Methods\n\n=head2 method reserved\n\n    method reserved(--> Str:D)\n\nReturns a text description of the reserved syntax.\n\n=head2 method instead\n\n    method instead(--> Str)\n\nDescribes what to use instead of the reserved syntax (if anything).\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/Self/WithoutObject.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::Self::WithoutObject\n\n=SUBTITLE Compilation error due to invoking C<self> in an ineligible scope\n\n    class X::Syntax::Self::WithoutObject does X::Syntax { }\n\nSyntax error thrown when C<self> is referenced in a place where no\ninvocant is available.\n\nFor example\n\n=for code :skip-test<compile time error>\nself;\n\noutside a class or role declaration dies with\n\n=for code :lang<text>\n===SORRY!===\n'self' used where no object is available\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/Signature/InvocantMarker.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::Signature::InvocantMarker\n\n=SUBTITLE Compilation error due to a misplaced invocant marker in a signature\n\n    class X::Syntax::Signature::InvocantMarker does X::Syntax { }\n\nSyntax error when the invocant in a signature is anywhere else than after the\nfirst parameter.\n\nFor example\n\n=for code :skip-test<compile time error>\n:($a, $b: $c);\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nCan only use : as invocant marker in a signature after the first parameter\n\nSee also: L<C<Signature>|/type/Signature>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/Term/MissingInitializer.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::Term::MissingInitializer\n\n=SUBTITLE Compilation error due to declaring a term without initialization\n\n    class X::Syntax::Term::MissingInitializer does X::Syntax { }\n\nSyntax error when a term (a backslash variable) is declared without\ninitialization assignment.\n\nFor example\n\n=for code :skip-test<compile time error>\nmy \\foo;\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nTerm definition requires an initializer\n\nValid code would be\n\n=for code\nmy \\foo = 42;\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/UnlessElse.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::UnlessElse\n\n=SUBTITLE Compilation error due to an C<unless> clause followed by C<else>\n\n    class X::Syntax::UnlessElse does X::Syntax { }\n\nSyntax error thrown when an C<unless> clause is followed by an C<else> clause.\n\nFor example\n\n=for code :skip-test<compile time error>\nunless 1 { } else { };\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\n\"unless\" does not take \"else\", please rewrite using \"if\"\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/Variable/Match.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::Variable::Match\n\n=SUBTITLE Compilation error due to declaring a match variable\n\n    class X::Syntax::Variable::Match does X::Syntax { }\n\nSyntax error thrown when a match variable like C«$<thing>» was declared.\n\nFor example\n\n=for code :skip-test<compile time error>\nmy $<thing>;\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nCannot declare a match variable\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/Variable/Numeric.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::Variable::Numeric\n\n=SUBTITLE Compilation error due to declaring a numeric symbol\n\n    class X::Syntax::Variable::Numeric does X::Syntax { }\n\nSyntax error thrown when trying to declare numeric symbols.\n\nFor example\n\n=for code :skip-test<compile time error>\nmy @101;\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nCannot declare a numeric variable\n\n=head1 Methods\n\n=head2 method what\n\n    method what returns Str:D\n\nReturns a verbal description of the kind of symbol that was declared (variable,\nparameter, attribute).\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax/Variable/Twigil.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Syntax::Variable::Twigil\n\n=SUBTITLE Compilation error due to an unallowed twigil in a declaration\n\n    class X::Syntax::Variable::Twigil does X::Syntax { }\n\nSyntax error thrown when a variable with a twigil is used in an incompatible\ndeclaration.\n\nFor example\n\n=for code :skip-test<compile time error>\nmy $!foo;\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nCannot use ! twigil on my variable\n\n=head1 Methods\n\n=head2 method twigil\n\n    method twigil(--> Str:D)\n\nReturns the twigil that was illegally used\n\n=head2 method scope\n\n    method scope(--> Str:D)\n\nReturns the scope that did not harmonize with the twigil.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Syntax.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"exception\")\n\n=TITLE role X::Syntax\n\n=SUBTITLE Syntax error thrown by the compiler\n\n    role X::Syntax does X::Comp { }\n\nCommon role for syntax errors thrown by the compiler.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Temporal/InvalidFormat.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Temporal::InvalidFormat\n\n=SUBTITLE Error due to using an invalid format when creating a DateTime or Date\n\n=for code :skip-test<compile time error>\nclass X::Temporal::InvalidFormat does X::Temporal is Exception { }\n\nThis exception is thrown when code tries to create a L<C<DateTime>|/type/DateTime> or L<C<Date>|/type/Date> object\nusing an invalid format.\n\n=begin code :ok-test<dd>\nmy $dt = Date.new(\"12/25/2015\");\nCATCH { default { put .^name, ': ', .Str } };\n# OUTPUT: «X::Temporal::InvalidFormat: Invalid Date string '12/25/2015'; use yyyy-mm-dd instead␤»\n=end code\n\n=head1 Methods\n\n=head2 method invalid-str\n\nReturns the invalid format string (C<12/25/2015> in the example above)\n\n=head2 method target\n\nReturns the target type (L<C<Date>|/type/Date> in the example above)\n\n=head2 method format\n\nReturns valid format strings for the target type in question, (C<yyyy-mm-dd> in the example above)\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Temporal.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"role\") :category(\"exception\")\n\n=TITLE role X::Temporal\n\n=SUBTITLE Error related to DateTime or Date\n\n    role X::Temporal is Exception { }\n\nA common exception type for all errors related to L<C<DateTime>|/type/DateTime> or L<C<Date>|/type/Date>.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/TypeCheck/Assignment.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::TypeCheck::Assignment\n\n=SUBTITLE Error due to a failed type check during assignment\n\n    class X::TypeCheck::Assignment is X::TypeCheck { }\n\nError class thrown when the type check of an assignment fails.\n\nFor example, this will die\n\n    my Int $x = \"foo\";\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::TypeCheck::Assignment: Type check failed in assignment to $x; expected Int but got Str (\"foo\")␤»\n\nthough compilers are allowed to detect obvious cases like this example\nand complain at compile time with a different error.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/TypeCheck/Binding.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::TypeCheck::Binding\n\n=SUBTITLE Error due to a failed type check during binding\n\n    class X::TypeCheck::Binding is X::TypeCheck { }\n\nThrown when the type check of a binding operation fails.\n\nFor example:\n\n    my Int $x := \"foo\";\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::TypeCheck::Binding: Type check failed in binding; expected Int but got Str (\"foo\")␤»\n\nNote that the compiler is free to detect obvious errors at compile time,\nand complain with a different error at compile time.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/TypeCheck/Return.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::TypeCheck::Return\n\n=SUBTITLE Error due to a failed typecheck during C<return>\n\n    class X::TypeCheck::Return is X::TypeCheck { }\n\nThrown when a return type check fails.\n\nFor example\n\n    sub f(--> Int) { \"foo\" }\n    f();\n    CATCH { default { put .^name, ': ', .Str } };\n    # OUTPUT: «X::TypeCheck::Return: Type check failed for return value; expected Int but got Str (\"foo\")␤»\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/TypeCheck/Splice.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::TypeCheck::Splice\n\n=SUBTITLE Compilation error due to a macro trying to splice a non-AST value\n\n    class X::TypeCheck::Splice is X::TypeCheck does X::Comp { }\n\nCompile time error thrown when a L<C<Macro>|/type/Macro> or an unquote/hole in a C<quasi>\nquote does not return an L<C<AST>|/type/AST>.\n\nFor example\n\n=for code :skip-test<compile time error>\nuse experimental :macros;\nmacro quasi-ast { quasi { {{{'not AST'}}} };};\nsay quasi-ast;\n\ndies with\n\n=for code :lang<text>\n===SORRY!===\nType check failed in macro application; expected AST but got Str(\"not AST\")\n\nThis is because you are purposefully creating something that does not evaluate to an abstract syntax tree. To fix, instead write\n\n=for code\nuse experimental :macros;\nmacro an-ast {\n    quasi { 'yes AST' }\n}\nsay an-ast;              # OUTPUT: «yes AST␤»\n\n=head1 Methods\n\n=head2 method action\n\n    method action(--> Str:D)\n\nReturns a verbal description of the action that triggered the error,\nC<\"macro application\"> or C<\"unquote evaluation\">.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/TypeCheck.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::TypeCheck\n\n=SUBTITLE Error due to a failed type check\n\n    class X::TypeCheck is Exception { }\n\nError class thrown when a type check fails.\n\n=head1 Methods\n\n=head2 method operation\n\n    method operation(--> Str:D)\n\nReturns a string description of the operation that failed, for example\nC<\"assignment\">, C<\"binding\">, C<\"return\">.\n\n=head2 method got\n\n    method got()\n\nReturns the object that failed to type check\n\n=head2 method expected\n\n    method expected()\n\nReturns the type object against which the check failed.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/X/Undeclared.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"exception\")\n\n=TITLE class X::Undeclared\n\n=SUBTITLE Compilation error due to an undeclared symbol\n\n    class X::Undeclared does X::Comp {}\n\nThrown when the compiler encounters a symbol that has not been declared,\nbut needs to be.\n\nExample\n\n=for code :skip-test<compile time error>\n$x;\n\nresults in\n\n=for code :lang<text>\n===SORRY!===\nVariable $x is not declared\n\n=head1 Methods\n\n=head2 method symbol\n\nReturns the name of the undeclared symbol\n\n=head2 method what\n\nReturns the kind of symbol that was not declared (for example variable,\ntype, routine).\n\nSince The symbol wasn't declared, the compiler sometimes has to guess\n(or rather disambiguate) what kind of symbol it encounter that wasn't\ndeclared. For example if you write\n\n=for code :skip-test<compile time error>\nsay a;\n\nThen the disambiguation defaults to reporting a missing subroutine, even\nthough declaring a C<constant a = 'a'> would also make the error go away.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/atomicint.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"basic\")\n\n=TITLE class atomicint\n\n=SUBTITLE Integer (native storage at the platform's atomic operation size)\n\n    class atomicint is Int is repr('P6int') { }\n\nAn C<atomicint> is a native integer sized such that CPU-provided atomic\noperations can be performed upon it. On a 32-bit CPU it will typically\nbe 32 bits in size, and on an a 64-bit CPU it will typically be 64 bits\nin size. It exists to allow writing portable code that uses atomic\noperations.\n\nB<Note:> Rakudo releases before 2017.08 had no support for C<atomicint>s.\n\n    # Would typically only work on a 64-bit machine and VM build.\n    my int64 $active = 0;\n    $active⚛++;\n\n    # Would typically only work on a 32-bit machine and VM build.\n    my int32 $active = 0;\n    $active⚛++;\n\n    # Will work portably, though can only portably assume range of 32 bits.\n    my atomicint $active = 0;\n    $active⚛++;\n\nThe use of the C<atomicint> type does not automatically provide atomicity; it\nmust be used in conjunction with the atomic operations.\n\n    # Correct (will always output 80000)\n    my atomicint $total = 0;\n    await start { for ^20000 { $total⚛++ } } xx 4;\n    say $total;\n\n    # *** WRONG *** due to lack of use of the atomicint type.\n    # Either works correctly or dies, depending on platform.\n    my int $total = 0;\n    await start { for ^20000 { $total⚛++ } } xx 4;\n    say $total;\n\n    # *** WRONG *** due to lack of use of the atomic increment operator.\n    my atomicint $total = 0;\n    await start { for ^20000 { $total++ } } xx 4;\n    say $total;\n\n=head1 Routines\n\n=head2 sub atomic-assign\n\n    multi atomic-assign(atomicint $ is rw, int $value)\n    multi atomic-assign(atomicint $ is rw, Int() $value)\n\nPerforms an atomic assignment to a native integer, which may be in a lexical,\nattribute, or native array element. If C<$value> cannot unbox to a 64-bit\nnative integer due to being too large, an exception will be thrown. If the\nsize of C<atomicint> is only 32 bits, then an out of range C<$value> will be\nsilently truncated. The C<atomic-assign> routine ensures that any required\nbarriers are performed such that the changed value will be \"published\" to\nother threads.\n\n=head2 sub atomic-fetch\n\n    multi atomic-fetch(atomicint $ is rw)\n\nPerforms an atomic read of a native integer, which may live in a lexical,\nattribute, or native array element. Using this routine instead of simply\nusing the variable ensures that the latest update to the variable from other\nthreads will be seen, both by doing any required hardware barriers and also\npreventing the compiler from lifting reads. For example:\n\n    my atomicint $i = 0;\n    start { atomic-assign($i, 1) }\n    while atomic-fetch($i) == 0 { }\n\nIs certain to terminate, while in:\n\n    my atomicint $i = 0;\n    start { atomic-assign($i, 1) }\n    while $i == 0 { }\n\nIt would be legal for a compiler to observe that C<$i> is not updated in the\nloop, and so lift the read out of the loop, thus causing the program to never\nterminate.\n\n=head2 sub atomic-fetch-inc\n\n    multi atomic-fetch-inc(atomicint $ is rw)\n\nPerforms an atomic increment on a native integer. This will be performed using\nhardware-provided atomic operations. Since the operation is atomic, it is safe\nto use without acquiring a lock. Returns the value as seen before incrementing\nit. Overflow will wrap around silently.\n\n=head2 sub atomic-fetch-dec\n\n    multi atomic-fetch-dec(atomicint $ is rw)\n\nPerforms an atomic decrement on a native integer. This will be performed using\nhardware-provided atomic operations. Since the operation is atomic, it is safe\nto use without acquiring a lock. Returns the value as seen before decrementing\nit. Overflow will wrap around silently.\n\n=head2 sub atomic-fetch-add\n\n    multi atomic-fetch-add(atomicint $ is rw, int $value)\n    multi atomic-fetch-add(atomicint $ is rw, Int() $value)\n\nPerforms an atomic addition on a native integer. This will be performed using\nhardware-provided atomic operations. Since the operation is atomic, it is safe\nto use without acquiring a lock. Returns the value as seen before the addition\nwas performed. Overflow will wrap around silently. If C<$value> is too big to\nunbox to a 64-bit integer, an exception will be thrown. If C<$value> otherwise\noverflows C<atomicint> then it will be silently truncated before the addition\nis performed.\n\n=head2 sub atomic-fetch-sub\n\n    multi atomic-fetch-sub(atomicint $ is rw, int $value)\n    multi atomic-fetch-sub(atomicint $ is rw, Int() $value)\n\nPerforms an atomic subtraction on a native integer. This will be performed\nusing hardware-provided atomic operations. Since the operation is atomic, it is\nsafe to use without acquiring a lock. Returns the value as seen before the\nsubtraction was performed. Underflow will wrap around silently. If C<$value> is\ntoo big to unbox to a 64-bit integer, an exception will be thrown. If C<$value>\notherwise overflows C<atomicint> then it will be silently truncated before the\nsubtraction is performed.\n\n=head2 sub atomic-inc-fetch\n\n    multi atomic-inc-fetch(atomicint $ is rw)\n\nPerforms an atomic increment on a native integer. This will be performed using\nhardware-provided atomic operations. Since the operation is atomic, it is safe\nto use without acquiring a lock. Returns the value resulting from the\nincrement. Overflow will wrap around silently.\n\n=head2 sub atomic-dec-fetch\n\n    multi atomic-dec-fetch(atomicint $ is rw)\n\nPerforms an atomic decrement on a native integer. This will be performed using\nhardware-provided atomic operations. Since the operation is atomic, it is safe\nto use without acquiring a lock. Returns the value resulting from the\ndecrement. Overflow will wrap around silently.\n\n=head2 sub cas\n\n    multi cas(atomicint $target is rw, int $expected, int $value)\n    multi cas(atomicint $target is rw, Int() $expected, Int() $value)\n    multi cas(atomicint $target is rw, &operation)\n\nPerforms an atomic compare and swap of the native integer value in location\nC<$target>. The first two forms have semantics like:\n\n=for code :preamble<no strict;>\nmy int $seen = $target;\nif $seen == $expected {\n    $target = $value;\n}\nreturn $seen;\n\nExcept it is performed as a single hardware-supported atomic instruction, as\nif all memory access to C<$target> were blocked while it took place. Therefore\nit is safe to attempt the operation from multiple threads without any other\nsynchronization. For example:\n\n    my atomicint $master = 0;\n    await start {\n        if cas($master, 0, 1) == 0 {\n            say \"Master!\"\n        }\n    } xx 4\n\nWill reliably only ever print C<Master!> one time, as only one of the threads\nwill be successful in changing the 0 into a 1.\n\nBoth C<$expected> and C<$value> will be coerced to L<C<Int>|/type/Int> and unboxed if\nneeded. An exception will be thrown if the value cannot be represented as a\n64-bit integer. If the size of C<atomicint> is only 32 bits then the values\nwill be silently truncated to this size.\n\nThe third form, taking a code object, will first do an atomic fetch of the\ncurrent value and invoke the code object with it. It will then try to do an\natomic compare and swap of the target, using the value passed to the code\nobject as C<$expected> and the result of the code object as C<$value>. If\nthis fails, it will read the latest value, and retry, until a CAS operation\nsucceeds. Therefore, an atomic multiply of an C<atomicint> C<$i> by 2 could\nbe implemented as:\n\n=for code :preamble<no strict;>\ncas $i, -> int $current { $current * 2 }\n\nIf another thread changed the value while C<$current * 2> was being calculated\nthen the block would be called again with the latest value for a further\nattempt, and this would be repeated until success.\n\n=head1 Operators\n\n=head2 infix ⚛=\n\n    multi infix:<⚛=>(atomicint $ is rw, int $value)\n    multi infix:<⚛=>(atomicint $ is rw, Int() $value)\n\nPerforms an atomic assignment to a native integer, which may be in a lexical,\nattribute, or native array element. If C<$value> cannot unbox to a 64-bit\nnative integer due to being too large, an exception will be thrown. If the\nsize of C<atomicint> is only 32 bits, then an out of range C<$value> will be\nsilently truncated. The C<⚛=> operator ensures that any required barriers are\nperformed such that the changed value will be \"published\" to other threads.\n\n=head2 prefix ⚛\n\n    multi prefix:<⚛>(atomicint $ is rw)\n\nPerforms an atomic read of a native integer, which may live in a lexical,\nattribute, or native array element. Using this operator instead of simply\nusing the variable ensures that the latest update to the variable from other\nthreads will be seen, both by doing any required hardware barriers and also\npreventing the compiler from lifting reads. For example:\n\n    my atomicint $i = 0;\n    start { $i ⚛= 1 }\n    while ⚛$i == 0 { }\n\nIs certain to terminate, while in:\n\n    my atomicint $i = 0;\n    start { $i ⚛= 1 }\n    while $i == 0 { }\n\nIt would be legal for a compiler to observe that C<$i> is not updated in the\nloop, and so lift the read out of the loop, thus causing the program to never\nterminate.\n\n=head2 prefix ++⚛\n\n    multi prefix:<++⚛>(atomicint $ is rw)\n\nPerforms an atomic increment on a native integer. This will be performed using\nhardware-provided atomic operations. Since the operation is atomic, it is safe\nto use without acquiring a lock. Returns the value resulting from the\nincrement. Overflow will wrap around silently.\n\n=head2 postfix ⚛++\n\n    multi postfix:<⚛++>(atomicint $ is rw)\n\nPerforms an atomic increment on a native integer. This will be performed using\nhardware-provided atomic operations. Since the operation is atomic, it is safe\nto use without acquiring a lock. Returns the value as seen before incrementing\nit. Overflow will wrap around silently.\n\n=head2 prefix --⚛\n\n    multi prefix:<--⚛>(atomicint $ is rw)\n\nPerforms an atomic decrement on a native integer. This will be performed using\nhardware-provided atomic operations. Since the operation is atomic, it is safe\nto use without acquiring a lock. Returns the value resulting from the\ndecrement. Overflow will wrap around silently.\n\n=head2 postfix ⚛--\n\n    multi postfix:<⚛-->(atomicint $ is rw)\n\nPerforms an atomic decrement on a native integer. This will be performed using\nhardware-provided atomic operations. Since the operation is atomic, it is safe\nto use without acquiring a lock. Returns the value as seen before decrementing\nit. Overflow will wrap around silently.\n\n=head2 infix ⚛+=\n\n    multi infix:<⚛+=>(atomicint $ is rw, int $value)\n    multi infix:<⚛+=>(atomicint $ is rw, Int() $value)\n\nPerforms an atomic addition on a native integer. This will be performed using\nhardware-provided atomic operations. Since the operation is atomic, it is safe\nto use without acquiring a lock. Evaluates to the result of the addition.\nOverflow will wrap around silently. If C<$value> is too big to unbox to a\n64-bit integer, an exception will be thrown. If C<$value> otherwise overflows\nC<atomicint> then it will be silently truncated before the addition is\nperformed.\n\n=head2 infix ⚛-=\n\n    multi infix:<⚛-=>(atomicint $ is rw, int $value)\n    multi infix:<⚛-=>(atomicint $ is rw, Int() $value)\n\nPerforms an atomic subtraction on a native integer. This will be performed\nusing hardware-provided atomic operations. Since the operation is atomic, it is\nsafe to use without acquiring a lock. Evaluates to the result of the\nsubtraction.  Underflow will wrap around silently. If C<$value> is too big to\nunbox to a 64-bit integer, an exception will be thrown. If C<$value> otherwise\noverflows C<atomicint> then it will be silently truncated before the\nsubtraction is performed.\n\n=head2 infix ⚛−=\n\nSynonym for ⚛-= using U+2212 minus.\n\n=end pod\n"
  },
  {
    "path": "doc/Type/independent-routines.rakudoc",
    "content": "=begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"fundamental\")\n\n=TITLE Independent routines\n\n=SUBTITLE Routines not defined within any class or role.\n\nThese routines are defined in different files along with one or several other\nclasses, but are not actually attached to any particular class or role.\n\n=head2 routine EVAL\n\n=begin code :method\nproto EVAL($code where Blob|Cool|Callable, Str() :$lang = 'Raku',\n                PseudoStash :$context, Str() :$filename, Bool() :$check, *%_)\n=end code\n=begin code :method\nmulti EVAL($code, Str :$lang where { ($lang // '') eq 'Perl5' },\n                PseudoStash :$context, Str() :$filename, :$check)\n=end code\n\nThis routine executes at runtime a fragment of code, C<$code>, of a given language,\nC<$lang>, which defaults to C<Raku>.\n\nIt coerces L<C<Cool>|/type/Cool> C<$code> to L<C<Str>|/type/Str>. If\nC<$code> is a L<C<Blob>|/type/Blob>, it'll be processed using the same encoding as\nthe C<$lang> compiler would: for C<Raku> C<$lang>, uses C<utf-8>; for C<Perl5>,\nprocesses using the same rules as Perl.\n\nThis works as-is with a literal string parameter. More complex input,\nsuch as a variable or string with embedded code, is illegal by default.\nThis can be overridden in any of several ways:\n\n    use MONKEY-SEE-NO-EVAL; # Or...\n    use MONKEY;             # shortcut that turns on all MONKEY pragmas, or...\n    use Test;               # a module that activates MONKEY-SEE-NO-EVAL.\n\n    my $init = 0;\n    my $diff = 10;\n    my Str $changer = '$init += ' ~ $diff; # contains a Str object with value '$init += 10'\n    # any of the above allows:\n    EVAL $changer;\n    EVAL $changer;\n    say $init;                         # OUTPUT: «20␤»\n\nIn case the C<MONKEY-SEE-NO-EVAL> pragma is not activated, the compiler will\ncomplain with C<EVAL is a very dangerous function!!!>. And it is\nessentially right, since that will run arbitrary code with the same permissions\nas the program. You should take care of cleaning the code that is going to pass\nthrough EVAL if you activate the C<MONKEY-SEE-NO-EVAL> pragma.\n\nPlease note that you can interpolate to create routine names using\nquotation, as can be seen in\nL<this example|/language/quoting#index-entry-%26_(interpolation)>\nor\nL<other ways to interpolate to create identifier names|/language/syntax#Identifiers>.\nThis only works, however, for already declared functions and other\nobjects and is thus safer to use.\n\nSymbols in the current lexical scope are visible to code in an C<EVAL>.\n\n    my $answer = 42;\n    EVAL 'say $answer;';    # OUTPUT: «42␤»\n\nHowever, since the set of symbols in a lexical scope is immutable after\ncompile time, an C<EVAL> can never introduce symbols into the surrounding\nscope.\n\n=for code :skip-test<compile time error>\nEVAL 'my $lives = 9'; say $lives;   # error, $lives not declared\n\nFurthermore, the C<EVAL> is evaluated in the current package:\n\n    module M {\n        EVAL 'our $answer = 42'\n    }\n    say $M::answer;         # OUTPUT: «42␤»\n\nAnd also in the current language, meaning any added syntax is available:\n\n    sub infix:<mean>(*@a) is assoc<list> {\n        @a.sum / @a.elems\n    }\n    EVAL 'say 2 mean 6 mean 4';     # OUTPUT: «4␤»\n\nAn C<EVAL> statement evaluates to the result of the last statement:\n\n=begin code\nsub infix:<mean>(*@a) is assoc<list> {\n    @a.sum / @a.elems\n}\nsay EVAL 'say 1; 2 mean 6 mean 4';         # OUTPUT: «1␤4␤»\n=end code\n\nC<EVAL> is also a gateway for executing code in other languages:\n\n=for code\nEVAL \"use v5.20; say 'Hello from perl!'\", :lang<Perl5>;\n\nYou need to have L<C<Inline::Perl5>|https://github.com/niner/Inline-Perl5> for\nthis to work correctly.\n\nMore languages may be supported with additional\nmodules which may be found from the\nL<Raku Modules Directory|https://raku.land/?q=inline>.\n\nIf the optional  C<$filename> parameter is given, the\nL«C<$?FILE>|/language/variables#index-entry-$%3FFILE» variable is set to\nits value. Otherwise C<$?FILE> is set to a unique and generated file name.\n\n=for code\nuse MONKEY-SEE-NO-EVAL;\nEVAL 'say $?FILE';                              # OUTPUT: «/tmp/EVAL_0␤»\nEVAL 'say $?FILE', filename => '/my-eval-code'; # OUTPUT: «/my-eval-code␤»\n\nIf the optional C<$check> parameter is C<True>, C<$code>\nis processed by the C<$lang> compiler but is not actually\nrun.  For C<Raku>, L«C<BEGIN>|/language/phasers#BEGIN», and\nL«C<CHECK>|/language/phasers#CHECK» blocks are run. The C<EVAL> routine\nthen returns L<C<Nil>|/type/Nil> if compilation was successful, otherwise an exception\nis thrown.\n\n=head2 sub EVALFILE\n\n    sub EVALFILE($filename where Blob|Cool, :$lang = 'Raku', :$check)\n\nSlurps the specified file and evaluates it. Behaves the same way as\nC<EVAL> with regard to L<C<Blob>|/type/Blob> decoding, scoping, the C<$lang>\nparameter and the C<$check> parameter. Evaluates to the value produced\nby the final statement in the file when C<$check> is not C<True>.\n\n=for code\nEVALFILE \"foo.raku\";\n\n=head2 sub repl\n\nI<Note>: C<repl> was introduced in release 2021.06 of the Rakudo compiler.\n\n    sub repl()\n\nPauses execution and enters a L<REPL|/language/REPL> (read-eval-print loop) in the current\ncontext.  This REPL is exactly like the one created when you run C<raku>\nL<without any arguments|/programs/04-running-raku#DESCRIPTION> except that\nyou can access/modify the program's current context (such as lexical\nvariables).\n\nFor example, if you run this code:\n\n=begin code\nmy $name = \"Alice\";\n\nsay \"Hello, $name\";\n\nrepl();\n\nsay \"Goodbye, $name\"\n=end code\n\nthen you'll get the output C<Hello, Alice> and then enter a REPL session\n(I<before> any output with \"goodbye\" is printed).  Your REPL session could\ngo as follows:\n\n\n    =begin code :lang<shell>\n    Type 'exit' to leave\n    [0] > $name\n    Alice\n    [1] > $name = \"Bob\"\n    Bob\n    [2] > exit\n    =end code\n\nAfter exiting the REPL session, Raku will resume running the program;\nduring this run, any changes you made in the REPL session will still be\nin effect.  Thus, after the session above, you'd get the output\nC<Goodbye, Bob> rather than C<Goodbye, Alice> as you would have without\nthe REPL session.\n\n=head2 sub get\n\n    multi get  (IO::Handle:D $fh = $*ARGFILES) { $fh.get  }\n\nThis routine is a wrapper for the L<method of the same name in C<IO::Handle>|/type/IO::Handle#routine_get>.\nIf no C<Handle> is specified, defaults to L<C<$*ARGFILES>|/language/variables#$*ARGFILES>.\n\n=head2 sub getc\n\n    multi getc  (IO::Handle:D $fh = $*ARGFILES) { $fh.getc  }\n\nThis routine is a wrapper for the L<method of the same name in C<IO::Handle>|/type/IO::Handle#routine_getc>>.\nIf no C<Handle> is specified, defaults to L<C<$*ARGFILES>|/language/variables#$*ARGFILES>.\n\n=head2 sub mkdir\n\n    sub    mkdir(IO() $path, Int() $mode = 0o777 --> IO::Path:D)\n\nCreates a new directory; see L«C<mode>|/routine/mode» for explanation and\nvalid values for C<$mode>. Returns the L<C<IO::Path>|/type/IO::Path> object pointing to\nthe newly created directory on success;\nL<fails|/routine/fail> with L<C<X::IO::Mkdir>|/type/X::IO::Mkdir> if directory cannot be created.\n\nAlso creates parent directories, as needed (similar to *nix utility\nC<mkdir> with C<-p> option); that is, C<mkdir \"foo/bar/ber/meow\"> will\ncreate C<foo>, C<foo/bar>, and C<foo/bar/ber> directories if they do not\nexist, as well as C<foo/bar/ber/meow>.\n\n=head2 sub chdir\n\n    sub chdir(IO() $path, :$d = True, :$r, :$w, :$x --> IO::Path:D)\n\nChanges value of C<$*CWD> variable to the provided C<$path>, optionally ensuring\nthe new path passes several file tests. B<NOTE:> that this routine does I<NOT>\nalter the process's current directory (see\nL«C<&*chdir>|/routine/&*chdir»).\n\nReturns L«C<IO::Path>|/type/IO::Path»\nrepresenting new C<$*CWD> on success. On failure, returns\nL«C<Failure>|/type/Failure» and leaves C<$*CWD> untouched.\nThe C<$path> can be any object with an IO method that returns an\nL«C<IO::Path>|/type/IO::Path» object. The available file tests are:\n\n=item C<:d> — check L«C<.d>|/routine/d» returns C<True>\n\n=item C<:r> — check L«C<.r>|/routine/r» returns C<True>\n\n=item C<:w> — check L«C<.w>|/routine/w» returns C<True>\n\n=item C<:x> — check L«C<.x>|/routine/x» returns C<True>\n\nBy default, only C<:d> test is performed.\n\n=for code\nchdir         '/tmp'; # change $*CWD to '/tmp' and check its .d is True\nchdir :r, :w, '/tmp'; # … check its .r and .w are True\nchdir '/not-there';   # returns Failure\n\nNote that the following construct is a mistake:\n\n=for code\n# WRONG! DO NOT DO THIS!\nmy $*CWD = chdir '/tmp/';\n\nUse L«C<indir>|/routine/indir» instead.\n\n=head2 sub &*chdir\n\n=for code\nPROCESS::<&chdir> = sub (IO() $path --> IO::Path:D) { }\n\nChanges value of C<$*CWD> variable to the provided C<$path> and sets\nthe process's current directory to the value of\nL«C<$path.absolute>|/routine/absolute». B<NOTE:> that in most cases,\nyou want to use L«C<chdir>|/routine/chdir» routine instead.\n\nReturns an L«C<IO::Path>|/type/IO::Path»\nrepresenting the new C<$*CWD> on success. On failure, returns\nL«C<Failure>|/type/Failure» and leaves C<$*CWD> untouched.\nThe C<$path> can be any object with an IO method that returns an\nL«C<IO::Path>|/type/IO::Path» object.\n\nNote that unlike regular L«C<chdir>|/routine/chdir», there are no arguments\nto specify which file tests to perform.\n\n=for code\n&*chdir('/tmp');  # change $*CWD and process's current directory to '/tmp'\n&*chdir('/not-there'); # returns Failure\n\nNote that the following construct is a mistake:\n\n=for code\n# WRONG! DO NOT DO THIS!\nmy $*CWD = &*chdir('/tmp');\n\nUse the following, instead; or see L«C<indir>|/routine/indir» if\nyou do not need to change process's current directory:\n\n=for code\ntemp $*CWD;\n&*chdir('/tmp');\n\n=head2 sub chmod\n\n    sub chmod(Int() $mode, *@filenames --> List)\n\nCoerces all C<@filenames> to L«C<IO::Path>|/type/IO::Path» and calls\nL«C<IO::Path.chmod>|/type/IO::Path#method_chmod» with C<$mode> on them.\nReturns a L«C<List>|/type/List» containing a subset of C<@filenames> for which\nC<chmod> was successfully executed.\n\n    chmod 0o755, <myfile1  myfile2>; # make two files executable by the owner\n\n=head2 sub indir\n\n    sub indir(IO() $path, &code, :$d = True, :$r, :$w, :$x)\n\nTakes L«C<Callable>|/type/Callable» C<&code> and executes it after locally (to\nC<&code>) changing C<$*CWD> variable to an L<C<IO::Path>|/type/IO::Path> object based on C<$path>,\noptionally ensuring the new path passes several file tests. If C<$path> is\nrelative, it will be turned into an absolute path, even if an L<C<IO::Path>|/type/IO::Path>\nobject was given. B<NOTE:> that this routine does I<NOT> alter the process's\ncurrent directory (see L«C<&*chdir>|/routine/&*chdir»). The C<$*CWD>\noutside of the C<&code> is not affected, even if C<&code> explicitly assigns\na new value to C<$*CWD>.\n\nReturns the value returned by the C<&code> call on success. On failure to\nsuccessfully change C<$*CWD>, returns L«C<Failure>|/type/Failure».\nB<WARNING:> keep in mind that lazily evaluated things might end up NOT\nhaving the C<$*CWD> set by C<indir> in their dynamic scope by the time\nthey're actually evaluated. Either ensure the generators have their\nC<$*CWD> set or L<eagerly evaluate|/routine/eager> them before returning\nthe results from C<indir>:\n\n    say indir(\"/tmp\", {\n        gather { take \".\".IO }\n    })».CWD; # OUTPUT: «(/home/camelia)␤»\n\n    say indir(\"/tmp\", {\n        eager gather { take \".\".IO }\n    })».CWD; # OUTPUT: «(/tmp)␤»\n\n    say indir(\"/tmp\", {\n        my $cwd = $*CWD;\n        gather { temp $*CWD = $cwd; take \".\".IO }\n    })».CWD; # OUTPUT: «(/tmp)␤»\n\nThe routine's C<$path> argument can be any object with an IO method that\nreturns an L«C<IO::Path>|/type/IO::Path» object. The available file\ntests are:\n\n=item C<:d> — check L«C<.d>|/routine/d» returns C<True>\n\n=item C<:r> — check L«C<.r>|/routine/d» returns C<True>\n\n=item C<:w> — check L«C<.w>|/routine/d» returns C<True>\n\n=item C<:x> — check L«C<.x>|/routine/d» returns C<True>\n\nBy default, only C<:d> test is performed.\n\n    say $*CWD;                   # OUTPUT: «\"/home/camelia\".IO␤»\n    indir '/tmp', { say $*CWD }; # OUTPUT: «\"/tmp\".IO␤»\n    say $*CWD;                   # OUTPUT: «\"/home/camelia\".IO␤»\n\n    indir '/not-there', {;};     # returns Failure; path does not exist\n\n=head2 sub print\n\n    multi print(**@args --> True)\n    multi print(Junction:D --> True)\n\nPrints the given text on standard output (the\nL«C<$*OUT>|/language/variables#index-entry-%24%2AOUT» filehandle), coercing\nnon-L<C<Str>|/type/Str> objects to L<C<Str>|/type/Str> by calling L«C<.Str>\nmethod|/routine/Str». L<C<Junction>|/type/Junction> arguments\nL<autothread|/language/glossary#Autothreading> and the order of\nprinted strings is not guaranteed.\n\n    print \"Hi there!\\n\";       # OUTPUT: «Hi there!␤»\n    print \"Hi there!\";         # OUTPUT: «Hi there!»\n    print [1, 2, 3];           # OUTPUT: «1 2 3»\n    print \"Hello\" | \"Goodbye\"; # OUTPUT: «HelloGoodbye»\n\nTo print text and include the trailing newline, use\nL«C<put>|/type/independent-routines#sub_put».\n\n=head2 sub put\n\n    multi put()\n    multi put(**@args --> True)\n    multi put(Junction:D --> True)\n    multi put(Str:D \\x)\n    multi put(\\x)\n\nSame as L«C<print>|/type/independent-routines#sub_print», except it uses\nL«C<print-nl>|/routine/print-nl» (which prints a L<newline|/language/newline>,\nby default) at the end. L<C<Junction>|/type/Junction> arguments\nL<autothread|/language/glossary#Autothreading> and the order of\nprinted strings is not guaranteed.\n\n    put \"Hi there!\\n\";   # OUTPUT: «Hi there!␤␤»\n    put \"Hi there!\";     # OUTPUT: «Hi there!␤»\n    put [1, 2, 3];       # OUTPUT: «1 2 3␤»\n    put \"Hello\" | \"Goodbye\"; # OUTPUT: «Hello␤Goodbye␤»\n\nBy itself, C<put()> will print a new line\n\n    put \"Hey\"; put(); put(\"Hey\"); # OUTPUT: «Hey␤␤Hey␤»\n\nbut please note that we have used parentheses after C<put>. Without these\nparentheses, it will throw an exception (with version 6.d and after). It will\nalso raise an exception if it's used that way before C<for>; use the method form\nC<.put> instead.\n\n    .put for <1 2 3>;             # OUTPUT: «1␤2␤3␤»\n\n=head2 sub say\n\n    multi say(**@args --> True)\n\nPrints the \"gist\" of given objects; it will always invoke C<.gist> in the\ncase the object is a subclass of L<C<Str>|/type/Str>. Same as\nL«C<put>|/type/independent-routines#sub_put»,\nexcept it uses L«C<.gist>|/routine/gist» method to obtain string\nrepresentation of the object; as in the case of C<put>, it will also\nautothread for L<C<Junction>|/type/Junction>s.\n\nB<NOTE:> the L«C<.gist>|/routine/gist» method of some objects, such as\nL<Lists|/type/List#method_gist>, returns only B<partial> information\nabout the object (hence the \"gist\"). If you mean to print textual\ninformation, you most likely want to use L«C<put>|/type/independent-routines#sub_put»\ninstead.\n\n    say Range;        # OUTPUT: «(Range)␤»\n    say class Foo {}; # OUTPUT: «(Foo)␤»\n    say 'I ♥ Raku';   # OUTPUT: «I ♥ Raku␤»\n    say 1..Inf;       # OUTPUT: «1..Inf␤»\n\n=head2 routine note\n\n    method note(Mu: -->Bool:D)\n    multi  note(            --> Bool:D)\n    multi  note(Str:D $note --> Bool:D)\n    multi  note(**@args     --> Bool:D)\n\nLike L«C<say>|/routine/say» (in the sense it will invoke the C<.gist> method\nof the printed object), except it prints output to\nL«C<$*ERR>|/language/variables#index-entry-%24%2AERR» handle (C<STDERR>).\nIf no arguments are given to subroutine forms, will use string C<\"Noted\">.\n\n=begin code\nnote;       # STDERR OUTPUT: «Noted␤»\nnote 'foo'; # STDERR OUTPUT: «foo␤»\nnote 1..*;  # STDERR OUTPUT: «1..Inf␤»\n=end code\n\nThis command will also autothread on L<C<Junction>|/type/Junction>s, and is guaranteed to call\nC<gist> on the object if it's a subclass of L<C<Str>|/type/Str>.\n\n=head2 sub prompt\n\n    multi prompt()\n    multi prompt($msg)\n\nL<Prints|/routine/print> C<$msg> to C<$*OUT> handle if C<$msg> was provided,\nthen L<gets|/routine/get> a line of input from C<$*IN> handle. By default, this\nis equivalent to printing C<$msg> to\nL<STDOUT|https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29>,\nreading a line from\nL<STDIN|https://en.wikipedia.org/wiki/Standard_streams#Standard_input_.28stdin.29>,\nremoving the trailing new line, and returning the resultant string. As of Rakudo\n2018.08, C<prompt> will create L<allomorphs|/language/numerics#Allomorphs> for\nnumeric values, equivalent to calling C<val prompt>.\n\n=for code\nmy $name = prompt \"What's your name? \";\nsay \"Hi, $name! Nice to meet you!\";\nmy $age = prompt(\"Say your age (number)\");\nmy Int $years = $age;\nmy Str $age-badge = $age;\n\nIn the code above, C<$age> will be duck-typed to the allomorph L<C<IntStr>|/type/IntStr> if it's\nentered correctly as a number.\n\n=head2 sub open\n\n    multi open(IO() $path, |args --> IO::Handle:D)\n\nCreates L<a handle|/type/IO::Handle> with the given C<$path>, and calls\nL«C<IO::Handle.open>|/type/IO::Handle#method_open», passing any of the\nremaining arguments to it. Note that L<C<IO::Path>|/type/IO::Path> type provides numerous\nmethods for reading and writing from files, so in many common cases you\ndo not need to C<open> files or deal with L<C<IO::Handle>|/type/IO::Handle> type directly.\n\n=begin code\nmy $fh = open :w, '/tmp/some-file.txt';\n$fh.say: 'I ♥ writing Raku code';\n$fh.close;\n\n$fh = open '/tmp/some-file.txt';\nprint $fh.readchars: 4;\n$fh.seek: 7, SeekFromCurrent;\nsay $fh.readchars: 4;\n$fh.close;\n\n# OUTPUT: «I ♥ Raku␤»\n=end code\n\n=head2 sub slurp\n\n    multi slurp(IO::Handle:D $fh = $*ARGFILES, |c)\n    multi slurp(IO() $path, |c)\n\nSlurps the contents of the entire file into a L<C<Str>|/type/Str> (or L<C<Buf>|/type/Buf> if\nC<:bin>). Accepts C<:bin> and C<:enc> optional named parameters, with\nthe same meaning as L<open()|/routine/open>; possible encodings are the\nsame as in all the other L<C<IO>|/type/IO> methods and are listed in\nL<C<encoding>|/type/IO::Handle#method_encoding> routine.  The routine\nwill C<fail> if the file does not exist, or is a directory. Without any\narguments, sub C<slurp> operates on C<$*ARGFILES>, which defaults to\nC<$*IN> in the absence of any filenames.\n\n=begin code\n# read entire file as (Unicode) Str\nmy $text_contents   = slurp \"path/to/file\";\n\n# read entire file as Latin1 Str\nmy $text_contents   = slurp \"path/to/file\", enc => \"latin1\";\n\n# read entire file as Buf\nmy $binary_contents = slurp \"path/to/file\", :bin;\n=end code\n\n=head2 sub spurt\n\n    multi spurt(IO() $path, |c)\n\nThe C<$path> can be any object with an IO method that returns an\nL«C<IO::Path>|/type/IO::Path» object. Calls L«C<IO::Path.spurt>|/routine/spurt»\non the C<$path>, forwarding any of the remaining arguments.\n\n=head3 Options\n\n=item :enc\n\nThe encoding with which the contents will be written.\n\n=item :append\n\nBoolean indicating whether to append to a (potentially) existing file.  If\nthe file did not exist yet, it will be created.  Defaults to C<False>.\n\n=item :createonly\n\nBoolean indicating whether to fail if the file already exists.  Defaults to\nC<False>.\n\n=head3 Examples\n\n=begin code\n# write directly to a file\nspurt 'path/to/file', 'default text, directly written';\n\n# write directly with a non-Unicode encoding\nspurt 'path/to/latin1_file', 'latin1 text: äöüß', :enc<latin1>;\n\nspurt 'file-that-already-exists', 'some text';           # overwrite file's contents:\nspurt 'file-that-already-exists', ' new text', :append;  # append to file's contents:\nsay slurp 'file-that-already-exists';                    # OUTPUT: «some text new text␤»\n\n# fail when writing to a pre-existing file\nspurt 'file-that-already-exists', 'new text', :createonly;\n# OUTPUT: «Failed to open file /home/camelia/file-that-already-exists: file already exists …»\n=end code\n\n    multi spurt(IO() $path)\n\nAs of the 2020.12 release of the Rakudo compiler, it is also possible\nto call the C<spurt> subroutine without any data.  This will either\ncreate an empty file, or will truncate any existing file at the given\npath.\n\n=begin code\n# create an empty file / truncate a file\nspurt 'path/to/file';\n=end code\n\n=head2 sub run\n\n=for code :method\nsub run(\n    *@args ($, *@),\n    :$in = '-',\n    :$out = '-',\n    :$err = '-',\n    Bool :$bin = False,\n    Bool :$chomp = True,\n    Bool :$merge = False,\n    Str:D :$enc = 'UTF-8',\n    Str:D :$nl = \"\\n\",\n    :$cwd = $*CWD,\n    Hash() :$env = %*ENV,\n    :$arg0,\n    :$win-verbatim-args = False\n--> Proc:D)\n\nRuns an external command I<without involving a shell> and returns a\nL<C<Proc>|/type/Proc> object. By default, the external command will print to\nstandard output and error, and read from standard input.\n\n    run 'touch', '--', '*.txt'; # Create a file named “*.txt”\n\n    run <rm -- *.txt>; # Another way to use run, using word quoting for the\n                       # arguments\n\nIf you want to pass some variables you can still use C«< >», but try\nto avoid using C<« »> as it will do word splitting if you forget to\nquote variables:\n\n=begin code\nmy $file = ‘--my arbitrary filename’;\nrun ‘touch’, ‘--’, $file;  # RIGHT\nrun <touch -->, $file;     # RIGHT\n\nrun «touch -- \"$file\"»;    # RIGHT but WRONG if you forget quotes\nrun «touch -- $file»;      # WRONG; touches ‘--my’, ‘arbitrary’ and ‘filename’\nrun ‘touch’, $file;        # WRONG; error from `touch`\nrun «touch \"$file\"»;       # WRONG; error from `touch`\n=end code\n\nNote that C<--> is required for many programs to disambiguate between\ncommand-line arguments and\nL<filenames that begin with hyphens|https://mywiki.wooledge.org/BashPitfalls#Filenames_with_leading_dashes>.\n\nA sunk L<C<Proc>|/type/Proc> object for a process that L<exited|/routine/exitcode>\nunsuccessfully will throw an L<C<Exception>|/type/Exception>. If you wish to ignore the\nexceptions, and return a L<C<Proc>|/type/Proc> you can introspect, use L<run|/routine/run> in non-sink context:\n\n    run 'false';     # SUNK! Will throw an Exception\n    run('false').so; # OK. Evaluates Proc in Bool context; no sinking. Ignore returned Proc\n    my $a = run('false'); # Can call methods on the Proc in $a.\n\nIf you want to capture standard output or error instead of having it printed\ndirectly you can use the C<:out> or C<:err> arguments, which will make them\navailable using their respective methods: L<C<Proc.out>|/type/Proc> and\nL<C<Proc.err>|/type/Proc>.\n\n    my $proc = run 'echo', 'Raku is Great!', :out, :err;\n    $proc.out.slurp(:close).say; # OUTPUT: «Raku is Great!␤»\n    $proc.err.slurp(:close).say; # OUTPUT: «␤»\n\nYou can use these arguments to redirect them to a filehandle, thus\ncreating a kind of I<pipe>:\n\n    my $ls-alt-handle = open :w, '/tmp/cur-dir-ls-alt.txt';\n    my $proc = run \"ls\", \"-alt\", :out($ls-alt-handle);\n    # (The file will contain the output of the ls -alt command)\n\nThese argument are quite flexible and admit, for instance, handles to\nredirect them. See L<C<Proc>|/type/Proc> and\nL<C<Proc::Async>|/type/Proc::Async> for more details.\n\nSee also L<C<new>|/type/Proc#routine_new> and L<C<spawn>|/type/Proc#method_spawn>\nfor more examples and explanation of all arguments.\n\n=head2 sub shell\n\n=begin code\nmulti shell($cmd, :$in = '-', :$out = '-', :$err = '-',\n                Bool :$bin, Bool :$chomp = True, Bool :$merge,\n                Str :$enc, Str:D :$nl = \"\\n\", :$cwd = $*CWD, :$env)\n=end code\n\nRuns a command through the system shell, which defaults to C<%*ENV<ComSpec> /c>\nin Windows, C</bin/sh -c> otherwise. All shell metacharacters are interpreted by\nthe shell, including pipes, redirects, environment variable substitutions and so\non. Shell escapes are a severe security concern and can cause confusion with\nunusual file names. Use L<run|#sub_run> if you want to be safe.\n\nThe return value is of L<type Proc|/type/Proc>.\n\n    shell 'ls -lR | gzip -9 > ls-lR.gz';\n\nSee L<C<Proc>|/type/Proc#method_shell> for more details, for example on how to\ncapture output.\n\n=head2 routine unpolar\n\n    method unpolar(Real $angle)\n    multi  unpolar(Real $mag, Real $angle)\n\nReturns a L<C<Complex>|/type/Complex> with the coordinates corresponding to the angle in\nradians and magnitude corresponding to the object value or C<$mag> in\nthe case it's being used as a C<sub>\n\n    say 1.unpolar(⅓*pi);\n    # OUTPUT: «0.5000000000000001+0.8660254037844386i␤»\n\n=head2 routine printf\n\n     multi printf(Cool:D $format, *@args)\n\nProduces output according to a format.  The format used is the invocant\n(if called in method form) or the first argument (if called as a routine).\nThe rest of the arguments will be substituted in the format following\nthe format conventions.  See L<sprintf|/routine/sprintf> for details on\nacceptable format directives.\n\n    \"%s is %s\".printf(\"þor\", \"mighty\");    # OUTPUT: «þor is mighty»\n    printf( \"%s is %s\", \"þor\", \"mighty\");  # OUTPUT: «þor is mighty»\n\nOn L<C<Junction>|/type/Junction>s, it will also autothread, without a guaranteed order.\n\n    printf( \"%.2f \", ⅓ | ¼ | ¾ ); # OUTPUT: «0.33 0.25 0.75 »\n\n=head2 routine sprintf\n\n    multi sprintf(Cool:D $format, *@args)\n\nReturns a string according to a format as described below.  The format\nused is the invocant (if called in method form) or the first argument\n(if called as a routine).\n\n    sprintf( \"%s the %d%s\", \"þor\", 1, \"st\").put; # OUTPUT: «þor the 1st␤»\n    sprintf( \"%s is %s\", \"þor\", \"mighty\").put;   # OUTPUT: «þor is mighty␤»\n    \"%s's weight is %.2f %s\".sprintf( \"Mjölnir\", 3.3392, \"kg\").put;\n    # OUTPUT: «Mjölnir's weight is 3.34 kg␤»\n    # OUTPUT: «Mjölnir's weight is 3.34 kg␤»\n\nThis function is mostly identical to the C library's C<sprintf> and C<printf>\nfunctions.  The only difference between the two functions is that C<sprintf>\nreturns a string while the C<printf> function writes to a filehandle. C<sprintf>\nreturns a L<C<Str>|/type/Str>, not a literal.\n\nThe C<$format> is scanned for C<%> characters. Any C<%> introduces a\nformat token. Directives guide the use (if any) of the arguments. When\na directive other than C<%> is used, it indicates how the next\nargument passed is to be formatted into the string to be\ncreated. I<Parameter indexes> may also be used in the format\ntokens. They take the form C<N$> and are explained in more detail\nbelow.\n\nThe C<$format> may be defined enclosed in single or double quotes. The\ndouble-quoted C<$format> string is interpolated before being scanned\nand any embedded string whose interpolated value contains a C<%>\ncharacter will cause an exception. For example:\n\n=begin code\nmy $prod = \"Ab-%x-42\";\nmy $cost = \"30\";\nsprintf(\"Product $prod; cost: \\$%d\", $cost).put;\n# OUTPUT: «Your printf-style directives specify 2 arguments, but 1 argument was supplied␤»\n          «  in block <unit> at <unknown file> line 1␤»\n=end code\n\nWhen handling unknown input you should avoid using such syntax by\nputting all variables in the C<*@args> array and have one C<%> for each\nin C<$format>. If you need to include a C<$> symbol in the format\nstring (even as a I<parameter index>) either escape it or use the\nsingle-quoted form.  For example, either of the following forms works\nwithout error:\n\n=begin code\nsprintf(\"2 x \\$20 = \\$%d\", 2*20).put; # OUTPUT: «2 x $20 = $40␤»\nsprintf('2 x $20 = $%d', 2*20).put;   # OUTPUT: «2 x $20 = $40␤»\n=end code\n\nIn summary, unless you need something very special, you will have\nfewer unexpected problems by using the single-quoted format string and\nnot using interpolated strings inside the format string.\n\nN<The information below is for a fully functioning C<sprintf> implementation\nwhich hasn't been achieved yet. Formats or features not yet implemented are\nmarked NYI.>\n\n=head3 Directives\n\n=begin table\n\n % |  a literal percent sign\n c |  a character with the given codepoint\n s |  a string\n d |  a signed integer, in decimal\n u |  an unsigned integer, in decimal\n o |  an unsigned integer, in octal\n x |  an unsigned integer, in hexadecimal\n e |  a floating-point number, in scientific notation\n f |  a floating-point number, in fixed decimal notation\n g |  a floating-point number, in %e or %f notation\n X |  like x, but using uppercase letters\n E |  like e, but using an uppercase \"E\"\n G |  like g, but with an uppercase \"E\" (if applicable)\n b |  an unsigned integer, in binary\n\n=end table\n\nCompatibility:\n\n=begin table\n\n i |  a synonym for %d\n D |  a synonym for %ld\n U |  a synonym for %lu\n O |  a synonym for %lo\n F |  a synonym for %f\n\n=end table\n\n=head3 Modifiers\n\nModifiers change the meaning of format directives, but are largely\nno-ops (the semantics are still being determined).\n\n=begin table\n\n     | h  | interpret integer as native \"short\"     (typically int16)\n NYI | l  | interpret integer as native \"long\"      (typically int32 or int64)\n NYI | ll | interpret integer as native \"long long\" (typically int64)\n NYI | L  | interpret integer as native \"long long\" (typically uint64)\n NYI | q  | interpret integer as native \"quads\" (typically int64 or larger)\n\n=end table\n\nBetween the C<%> and the format letter, you may specify several\nadditional attributes controlling the interpretation of the format. In\norder, these are:\n\n=head3 NYI Format parameter index using the '$' symbol\n\nAn explicit format parameter index (ranging from 1 to N args)\nbefore the directive, such as C<%2$d>. By default, C<sprintf> will\nformat the next unused argument in the list, but the parameter index\nallows you to take the arguments out of order (note single quotes\nare required unless you escape the C<$>):\n\n=head4 Without index:\n\n=begin code\nsprintf '%d %d', 12, 34;      # OUTPUT: «12 34␤»\nsprintf '%d %d %d', 1, 2, 3;  # OUTPUT: «1 2 3␤»\n=end code\n\n=head4 NYI With index:\n\nThe first example works as we expect it to when we index all\ndirectives.\n\n=begin code\nsprintf '%2$d %1$d', 12, 34;      # OUTPUT: «34 12␤»\n=end code\n\nBut notice the effect when mixing indexed and non-indexed directives\nin the second example (be careful what you ask for). The second,\nnon-indexed directive gets the first argument, but it is also\nspecifically requested in the last directive:\n\n=begin code\nsprintf '%3$d %d %1$d', 1, 2, 3;  # OUTPUT: «3 1 1␤»\n=end code\n\n=head3 Flags\n\nOne or more of:\n\n=begin table\n   space |  prefix non-negative number with a space\n----------------------------------------------------------------\n  \\+     |  prefix non-negative number with a plus sign\n----------------------------------------------------------------\n   -     |  left-justify within the field\n----------------------------------------------------------------\n   0     |  use leading zeros, not spaces, for required padding\n----------------------------------------------------------------\n   #     |  ensure the leading \"0\" for any octal,\n         |  prefix non-zero hexadecimal with \"0x\" or \"0X\",\n         |  prefix non-zero binary with \"0b\" or \"0B\"\n----------------------------------------------------------------\n   v     |  NYI vector flag (used only with directive \"d\"), see description below\n=end table\n\nFor example:\n\n  sprintf '<% d>',  12;   # OUTPUT: «< 12>␤»\n  sprintf '<% d>',   0;   # OUTPUT: «< 0>\"»\n  sprintf '<% d>', -12;   # OUTPUT: «<-12>␤»\n  sprintf '<%+d>',  12;   # OUTPUT: «<+12>␤»\n  sprintf '<%+d>',   0;   # OUTPUT: «<+0>\"»\n  sprintf '<%+d>', -12;   # OUTPUT: «<-12>␤»\n  sprintf '<%6s>',  12;   # OUTPUT: «<    12>␤»\n  sprintf '<%-6s>', 12;   # OUTPUT: «<12    >␤»\n  sprintf '<%06s>', 12;   # OUTPUT: «<000012>␤»\n  sprintf '<%#o>',  12;   # OUTPUT: «<014>␤»\n  sprintf '<%#x>',  12;   # OUTPUT: «<0xc>␤»\n  sprintf '<%#X>',  12;   # OUTPUT: «<0XC>␤»\n  sprintf '<%#b>',  12;   # OUTPUT: «<0b1100>␤»\n  sprintf '<%#B>',  12;   # OUTPUT: «<0B1100>␤»\n\nWhen a space and a plus sign are given as the flags at once, the space\nis ignored:\n\n  sprintf '<%+ d>', 12;   # OUTPUT: «<+12>␤»\n  sprintf '<% +d>', 12;   # OUTPUT: «<+12>␤»\n\nWhen the C<#> flag and a precision are given in the C<%o> conversion, the\nnecessary number of 0s is added at the beginning. If the value of the number is\nC<0> and the precision is 0, it will output nothing; precision 0 or smaller than\nthe actual number of elements will return the number with 0 to the left:\n\n  say sprintf '<%#.5o>', 0o12;     # OUTPUT: «<00012>␤»\n  say sprintf '<%#.5o>', 0o12345;  # OUTPUT: «<012345>␤»\n  say sprintf '<%#.0o>', 0;        # OUTPUT: «<>␤» zero precision and value 0\n                                   #               results in no output!\n  say sprintf '<%#.0o>', 0o1       # OUTPUT: «<01>␤»\n\n=head3 Vector flag 'v'\n\nThis special flag (C<v>, followed by directive C<d>) tells Raku to\ninterpret the supplied string as a vector of integers, one for each\ncharacter in the string (the `ord` routine is used for the conversion\nto an integer). Raku applies the format to each integer in turn, then\njoins the resulting strings with a separator (a dot C<'.'>, by\ndefault). This can be useful for displaying ordinal values of\ncharacters in arbitrary strings:\n\n=begin code\nNYI sprintf \"%vd\", \"AB\\x[100]\";           # OUTPUT: «65.66.256␤»\n=end code\n\nYou can also explicitly specify the argument number to use for the\nseparator string by using an asterisk with a parameter index (e.g.,\nC<*2$v>); for example:\n\n=begin code :skip-test<not yet implemented>\nNYI sprintf '%*4$vX %*4$vX %*4$vX',       # 3 IPv6 addresses\n        @addr[1..3], \":\";\n=end code\n\n=head3 Width (minimum)\n\nArguments are usually formatted by default to be only as wide as required to\ndisplay the given value. You specify a minimum width that can override the default width by putting a\nnumber here, or get the desired width from the next argument (with C<*> ) or\nfrom a specified argument (e.g., with C<*2$>):\n\n=begin code :skip-test<partly not yet implemented>\n sprintf \"<%s>\", \"a\";           # OUTPUT: «<a>␤»\n sprintf \"<%6s>\", \"a\";          # OUTPUT: «<     a>␤»\n sprintf \"<%*s>\", 6, \"a\";       # OUTPUT: «<     a>␤»\n NYI sprintf '<%*2$s>', \"a\", 6; # OUTPUT: «<     a>␤»\n sprintf \"<%2s>\", \"long\";       # OUTPUT: «<long>␤»   (does not truncate)\n=end code\n\nIn all cases, the specified width will be increased as necessary to accommodate the given integral numerical value or string.\nIf a field width obtained through C<*> is negative, it has the same\neffect as the C<-> flag: left-justification.\n\n=head3 Precision, or maximum width\n\nYou can specify a precision (for numeric conversions) or a maximum\nwidth (for string conversions) by specifying a C<.> followed by a\nnumber. For floating-point formats, except C<g> and C<G>, this\nspecifies how many places right of the decimal point to show (the\ndefault being 6). For example:\n\n  # These examples are subject to system-specific variation.\n  sprintf '<%f>', 1;    # OUTPUT: «\"<1.000000>\"␤»\n  sprintf '<%.1f>', 1;  # OUTPUT: «\"<1.0>\"␤»\n  sprintf '<%.0f>', 1;  # OUTPUT: «\"<1>\"␤»\n  sprintf '<%e>', 10;   # OUTPUT: «\"<1.000000e+01>\"␤»\n  sprintf '<%.1e>', 10; # OUTPUT: «\"<1.0e+01>\"␤»\n\nFor \"g\" and \"G\", this specifies the maximum number of digits to show,\nincluding those prior to the decimal point and those after it; for\nexample:\n\n  # These examples are subject to system-specific variation.\n  sprintf '<%g>', 1;        # OUTPUT: «<1>␤»\n  sprintf '<%.10g>', 1;     # OUTPUT: «<1>␤»\n  sprintf '<%g>', 100;      # OUTPUT: «<100>␤»\n  sprintf '<%.1g>', 100;    # OUTPUT: «<1e+02>␤»\n  sprintf '<%.2g>', 100.01; # OUTPUT: «<1e+02>␤»\n  sprintf '<%.5g>', 100.01; # OUTPUT: «<100.01>␤»\n  sprintf '<%.4g>', 100.01; # OUTPUT: «<100>␤»\n\nFor integer conversions, specifying a precision implies the\noutput of the number itself should be zero-padded to this width (where\nthe C<0> flag is ignored):\n\n(Note that this feature currently works for unsigned integer conversions, but\nnot for signed integer.)\n\n  =begin code\n  sprintf '<%.6d>', 1;         # OUTPUT: «<000001>␤»\n  NYI sprintf '<%+.6d>', 1;    # OUTPUT: «<+000001>␤»\n  NYI sprintf '<%-10.6d>', 1;  # OUTPUT: «<000001    >␤»\n  sprintf '<%10.6d>', 1;       # OUTPUT: «<    000001>␤»\n  NYI sprintf '<%010.6d>', 1;  # OUTPUT: «<    000001>␤»\n  NYI sprintf '<%+10.6d>', 1;  # OUTPUT: «<   +000001>␤»\n  sprintf '<%.6x>', 1;         # OUTPUT: «<000001>␤»\n  sprintf '<%#.6x>', 1;        # OUTPUT: «<0x000001>␤»\n  sprintf '<%-10.6x>', 1;      # OUTPUT: «<000001    >␤»\n  sprintf '<%10.6x>', 1;       # OUTPUT: «<    000001>␤»\n  sprintf '<%010.6x>', 1;      # OUTPUT: «<    000001>␤»\n  sprintf '<%#10.6x>', 1;      # OUTPUT: «<  0x000001>␤»\n  =end code\n\nFor string conversions, specifying a precision truncates the string to\nfit the specified width:\n\n  sprintf '<%.5s>', \"truncated\";   # OUTPUT: «<trunc>␤»\n  sprintf '<%10.5s>', \"truncated\"; # OUTPUT: «<     trunc>␤»\n\nYou can also get the precision from the next argument using C<.*>, or\nfrom a specified argument (e.g., with C<.*2$>):\n\n  =begin code\n  sprintf '<%.6x>', 1;           # OUTPUT: «<000001>␤»\n  sprintf '<%.*x>', 6, 1;        # OUTPUT: «<000001>␤»\n  NYI sprintf '<%.*2$x>', 1, 6;  # OUTPUT: «<000001>␤»\n  NYI sprintf '<%6.*2$x>', 1, 4; # OUTPUT: «<  0001>␤»\n  =end code\n\nIf a precision obtained through C<*> is negative, it counts as having\nno precision at all:\n\n  sprintf '<%.*s>',  7, \"string\";   # OUTPUT: «<string>␤»\n  sprintf '<%.*s>',  3, \"string\";   # OUTPUT: «<str>␤»\n  sprintf '<%.*s>',  0, \"string\";   # OUTPUT: «<>␤»\n  sprintf '<%.*s>', -1, \"string\";   # OUTPUT: «<string>␤»\n  sprintf '<%.*d>',  1, 0;          # OUTPUT: «<0>␤»\n  sprintf '<%.*d>',  0, 0;          # OUTPUT: «<>␤»\n  sprintf '<%.*d>', -1, 0;          # OUTPUT: «<0>␤»\n\n=head3 Size\n\nFor numeric conversions, you can specify the size to interpret the\nnumber as using C<l>, C<h>, C<V>, C<q>, C<L>, or C<ll>. For integer\nconversions (C<d> C<u> C<o> C<x> C<X> C<b> C<i> C<D> C<U> C<O>),\nnumbers are usually assumed to be whatever the default integer size is\non your platform (usually 32 or 64 bits), but you can override this to\nuse instead one of the standard C types, as supported by the compiler\nused to build Raku:\n\n(Note: None of the following have been implemented.)\n\n=begin table\n\n   hh          | interpret integer as C type \"char\" or \"unsigned char\"\n   h           | interpret integer as C type \"short\" or \"unsigned short\"\n   j           | interpret integer as C type \"intmax_t\", only with a C99 compiler (unportable)\n   l           | interpret integer as C type \"long\" or \"unsigned long\"\n   q, L, or ll | interpret integer as C type \"long long\", \"unsigned long long\", or \"quad\" (typically 64-bit integers)\n   t           | interpret integer as C type \"ptrdiff_t\"\n   z           | interpret integer as C type \"size_t\"\n=end table\n\n=head3 Order of arguments\n\nNormally, C<sprintf> takes the next unused argument as the value to\nformat for each format specification. If the format specification uses\nC<*> to require additional arguments, these are consumed from the\nargument list in the order they appear in the format specification\nbefore the value to format. Where an argument is specified by an\nexplicit index, this does not affect the normal order for the\narguments, even when the explicitly specified index would have been\nthe next argument.\n\nSo:\n\n   my $a = 5; my $b = 2; my $c = 'net';\n   sprintf \"<%*.*s>\", $a, $b, $c; # OUTPUT: «<   ne>␤»\n\nuses C<$a> for the width, C<$b> for the precision, and C<$c> as the value to\nformat; while:\n\n=for code :skip-test<not yet implemented>\nNYI sprintf '<%*1$.*s>', $a, $b;\n\nwould use C<$a> for the width and precision and C<$b> as the value to format.\n\nHere are some more examples; be aware that when using an explicit\nindex, the C<$> will need escaping if the format string is double-quoted:\n\n=for code\nsprintf \"%2\\$d %d\\n\",      12, 34;         # OUTPUT: «34 12␤␤»\nsprintf \"%2\\$d %d %d\\n\",   12, 34;         # OUTPUT: «34 12 34␤␤»\nsprintf \"%3\\$d %d %d\\n\",   12, 34, 56;     # OUTPUT: «56 12 34␤␤»\nNYI sprintf \"%2\\$*3\\$d %d\\n\",  12, 34,  3; # OUTPUT: « 34 12␤␤»\nNYI sprintf \"%*1\\$.*f\\n\",       4,  5, 10; # OUTPUT: «5.0000␤␤»\n\nOther examples:\n\n=for code\nNYI sprintf \"%ld a big number\", 4294967295;\nNYI sprintf \"%%lld a bigger number\", 4294967296;\nsprintf('%c', 97);                  # OUTPUT: «a␤»\nsprintf(\"%.2f\", 1.969);             # OUTPUT: «1.97␤»\nsprintf(\"%+.3f\", 3.141592);         # OUTPUT: «+3.142␤»\nsprintf('%2$d %1$d', 12, 34);       # OUTPUT: «34 12␤»\nsprintf(\"%x\", 255);                 # OUTPUT: «ff␤»\n\nSpecial case: C«sprintf(\"<b>%s</b>\\n\", \"Raku\")» will not work, but\none of the following will:\n\n=for code\nsprintf Q:b \"<b>%s</b>\\n\",  \"Raku\"; # OUTPUT: «<b>Raku</b>␤␤»\nsprintf     \"<b>\\%s</b>\\n\", \"Raku\"; # OUTPUT: «<b>Raku</b>␤␤»\nsprintf     \"<b>%s\\</b>\\n\", \"Raku\"; # OUTPUT: «<b>Raku</b>␤␤»\n\n=head2 sub flat\n\n    multi flat(**@list)\n    multi flat(Iterable \\a)\n\nConstructs a list which contains any arguments provided, and returns the result\nof calling the C<.flat> method (L<inherited from C<Any>|/type/Any#method_flat>)\non that list or L<C<Iterable>|/type/Iterable>:\n\n    say flat 1, (2, (3, 4), $(5, 6)); # OUTPUT: «(1 2 3 4 (5 6))␤»\n\n=head2 routine unique\n\n    multi unique(+values, |c)\n\nReturns a sequence of B<unique> values from the invocant/argument list, such\nthat only the first occurrence of each duplicated value remains in the\nresult list. C<unique> uses the semantics of the L<===|/routine/===> operator to decide\nwhether two objects are the same, unless the optional C<:with> parameter is\nspecified with another comparator. The order of the original list is preserved\neven as duplicates are removed.\n\nExamples:\n\n    say <a a b b b c c>.unique;   # OUTPUT: «(a b c)␤»\n    say <a b b c c b a>.unique;   # OUTPUT: «(a b c)␤»\n\n(Use L<squish|/routine/squish> instead if you know the input is sorted such that identical\nobjects are adjacent.)\n\nThe optional C<:as> parameter allows you to normalize/canonicalize the elements\nbefore unique-ing. The values are transformed for the purposes of comparison,\nbut it's still the original values that make it to the result list; however,\nonly the first occurrence will show up in that list:\n\nExample:\n\n    say <a A B b c b C>.unique(:as(&lc))      # OUTPUT: «(a B c)␤»\n\nOne can also specify the comparator with the optional C<:with> parameter.  For\ninstance if one wants a list of unique hashes, one could use the C<eqv>\ncomparator.\n\nExample:\n\n    my @list = %(a => 42), %(b => 13), %(a => 42);\n    say @list.unique(:with(&[eqv]))           # OUTPUT: «({a => 42} {b => 13})␤»\n\nB<Note:> since C<:with> L<C<Callable>|/type/Callable> has to be tried with all the\nitems in the list, this makes C<unique> follow a path with much higher\nalgorithmic complexity. You should try to use the C<:as> argument instead,\nwhenever possible.\n\n=head2 routine repeated\n\n    multi repeated(+values, |c)\n\nThis returns a sequence of B<repeated> values from the invocant/argument list.\nIt takes the same parameters as L<unique|/routine/unique>, but instead of passing through any\nelements when they're first seen, they're only passed through as soon as they're\nseen for the second time (or more).\n\nExamples:\n\n    say <a a b b b c c>.repeated;                   # OUTPUT: «(a b b c)␤»\n    say <a b b c c b a>.repeated;                   # OUTPUT: «(b c b a)␤»\n    say <a A B b c b C>.repeated(:as(&lc));         # OUTPUT: «(A b b C)␤»\n\n    my @list = %(a => 42), %(b => 13), %(a => 42);\n    say @list.repeated(:with(&[eqv]))               # OUTPUT: «({a => 42})␤»\n\nAs in the case of L<C<unique>|/type/Any#method_unique> the associative argument\nC<:as> takes a Callable that normalizes the element before comparison, and\nC<:with> takes the equality comparison function that is going to be used.\n\n=head2 routine squish\n\n    sub squish( +values, |c)\n\nReturns a sequence of values from the invocant/argument list where runs of one\nor more values are replaced with only the first instance. Like L<C<unique>|/routine/unique>,\nC<squish> uses the semantics of the L<===|/routine/===> operator to decide whether two\nobjects are the same. Unlike L<C<unique>|/routine/unique>, this function only removes adjacent\nduplicates; identical values further apart are still kept. The order of the\noriginal list is preserved even as duplicates are removed.\n\nExamples:\n\n    say <a a b b b c c>.squish; # OUTPUT: «(a b c)␤»\n    say <a b b c c b a>.squish; # OUTPUT: «(a b c b a)␤»\n\nThe optional C<:as> parameter, just like with L<C<unique>|/routine/unique>, allows values to be\ntemporarily transformed before comparison.\n\nThe optional C<:with> parameter is used to set an appropriate comparison\noperator:\n\n    say [42, \"42\"].squish;                      # OUTPUT: «(42 42)␤»\n    # Note that the second item in the result is still Str\n    say [42, \"42\"].squish(with => &infix:<eq>); # OUTPUT: «(42)␤»\n    # The resulting item is Int\n\n=head2 sub sleep\n\n    sub sleep($seconds = Inf --> Nil)\n\nAttempt to sleep for the given number of C<$seconds>.  Returns L<C<Nil>|/type/Nil> on\ncompletion.  Accepts L<C<Int>|/type/Int>, L<C<Num>|/type/Num>, L<C<Rat>|/type/Rat>, or L<C<Duration>|/type/Duration> types as an\nargument since all of these also do L<C<Real>|/type/Real>.\n\n=for code\nsleep 5;                # Int\nsleep 5.2;              # Num\nsleep (5/2);            # Rat\nsleep (now - now + 5);  # Duration\n\nIt is thus possible to sleep for a non-integer amount of time.  For\ninstance, the following code shows that C<sleep (5/2)> sleeps for 2.5\nseconds and C<sleep 5.2> sleeps for 5.2 seconds:\n\n    my $before = now;\n    sleep (5/2);\n    my $after = now;\n    say $after-$before;  # OUTPUT: «2.502411561␤»\n\n    $before = now;\n    sleep 5.2;\n    $after = now;\n    say $after-$before;  # OUTPUT: «5.20156987␤»\n\n=head2 sub sleep-timer\n\n    sub sleep-timer(Real() $seconds = Inf --> Duration:D)\n\nThis function is implemented like C<sleep>, but unlike the former it does\nreturn a L<C<Duration>|/type/Duration> instance with the number of seconds the system did not\nsleep.\n\nIn particular, the returned L<C<Duration>|/type/Duration> will handle the number of seconds remaining\nwhen the process has been awakened by some external event (e.g., Virtual Machine\nor Operating System events).\nUnder normal condition, when sleep is not interrupted, the returned L<C<Duration>|/type/Duration>\nhas a value of C<0>, meaning no extra seconds remained to sleep.\nTherefore, in normal situations:\n\n    say sleep-timer 3.14;  # OUTPUT: «0␤»\n\nThe same result applies to edge cases, when a negative or zero time to sleep\nis passed as argument:\n\n=begin code\nsay sleep-timer -2; # OUTPUT: 0\nsay sleep-timer 0;  # OUTPUT: 0\n=end code\n\nSee also L<sleep-until|/routine/sleep-until>.\n\n=head2 sub sleep-until\n\n    sub sleep-until(Instant $until --> Bool)\n\nWorks similar to C<sleep> but checks the current time and keeps sleeping\nuntil the required instant in the future has been reached.\nIt uses internally the C<sleep-timer> method in a loop to ensure that,\nif accidentally woken up early, it will wait again for the specified\namount of time remaining to reach the specified instant.\ngoes back to sleep\n\nReturns C<True> if the L<C<Instant>|/type/Instant> in the future has been achieved (either\nby mean of sleeping or because it is right now), C<False> in the case\nan L<C<Instant>|/type/Instant> in the past has been specified.\n\nTo sleep until 10 seconds into the future, one could write something like this:\n\n    say sleep-until now+10;   # OUTPUT: «True␤»\n\nTrying to sleep until a time in the past doesn't work:\n\n    my $instant = now - 5;\n    say sleep-until $instant; # OUTPUT: «False␤»\n\nHowever if we put the instant sufficiently far in the future, the sleep\nshould run:\n\n=for code\nmy $instant = now + 30;\n# assuming the two commands are run within 30 seconds of one another...\nsay sleep-until $instant; # OUTPUT: «True␤»\n\nTo specify an exact instant in the future, first create a L<C<DateTime>|/type/DateTime> at the\nappropriate point in time, and cast to an L<C<Instant>|/type/Instant>.\n\n=for code\nmy $instant = DateTime.new(\n    year => 2023,\n    month => 9,\n    day => 1,\n    hour => 22,\n    minute => 5);\nsay sleep-until $instant.Instant; # OUTPUT: «True␤» (eventually...)\n\nThis could be used as a primitive kind of alarm clock.  For instance, say\nyou need to get up at 7am on the 4th of September 2015, but for some reason\nyour usual alarm clock is broken and you only have your laptop.  You can\nspecify the time to get up (being careful about timezones, since\nC<DateTime.new> uses UTC by default) as an L<C<Instant>|/type/Instant> and pass this to\nC<sleep-until>, after which you can play an mp3 file to wake you up instead\nof your normal alarm clock.  This scenario looks roughly like this:\n\n=for code\n# DateTime.new uses UTC by default, so get timezone from current time\nmy $timezone = DateTime.now.timezone;\nmy $instant = DateTime.new(\n    year => 2015,\n    month => 9,\n    day => 4,\n    hour => 7,\n    minute => 0,\n    timezone => $timezone\n).Instant;\nsleep-until $instant;\nqqx{mplayer wake-me-up.mp3};\n\n=head2 sub emit\n\n    sub emit(\\value --> Nil)\n\nIf used outside any supply or react block, throws an exception C<emit without\nsupply or react>. Within a L<C<Supply>|/type/Supply> block, it will add a message to the stream.\n\n=begin code\nmy $supply = supply {\n  for 1 .. 10 {\n      emit($_);\n  }\n}\n$supply.tap( -> $v { say \"First : $v\" });\n=end code\n\nC<emit> is implemented as a L<control exception|/language/phasers#CONTROL> and\ncan therefore be used by something called from the C<supply> block that it\nrefers to.\n\nSee also L<the page for C<emit> methods|/routine/emit>.\n\n=head2 sub undefine\n\n    multi undefine(Mu    \\x)\n    multi undefine(Array \\x)\n    multi undefine(Hash  \\x)\n\nB<DEPRECATED> in 6.d language version and will be removed in 6.e. For\nL<C<Array>|/type/Array> and L<C<Hash>|/type/Hash>, it will become equivalent to\nassigning L<C<Empty>|/type/Slip#constant_Empty>; for everything else,\nequivalent to assigning L<C<Nil>|/type/Nil> or C<Empty> in the case of arrays or\nhashes, whose use is advised.\n\n=head1 Array manipulation\n\nRoutines that manipulate arrays and other mutable collections.\n\n=head2 sub pop\n\n    multi pop(@a) is raw\n\nCalls method C<pop> on the L<C<Positional>|/type/Positional> argument. That method is supposed to\nremove and return the last element, or return a L<C<Failure>|/type/Failure>\nwrapping an L<C<X::Cannot::Empty>|/type/X::Cannot::Empty> if the collection is\nempty.\n\nSee the documentation of the L<C<Array> method|/routine/pop#(Array)_method_pop>\nfor an example.\n\n=head2 sub shift\n\n    multi shift(@a) is raw\n\nCalls method C<shift> on the L<C<Positional>|/type/Positional> argument. That method, on\na mutable collection that actually implements it (such as an\nL<C<Array>|/routine/shift#(Array)_method_shift> or a\nL<C<Buf>|/type/Buf#method_shift>), is supposed to remove\nand return the first element, or return a L<C<Failure>|/type/Failure> if the\ncollection is empty.\n\nExample:\n\n    say shift [1,2]; # OUTPUT: «1␤»\n\n=for code\nmy @a of Int = [1];\nsay shift @a; # OUTPUT: «1␤»\nsay shift @a; # ERROR: «Cannot shift from an empty Array[Int]␤»\n\n=head2 sub push\n\n    multi push(\\a, **@b is raw)\n    multi push(\\a, \\b)\n\nCalls method C<push> on the first argument, passing the remaining arguments.\nMethod C<push> is supposed to add the provided values to the end of the\ncollection or parts thereof. See the documentation of the\nL<C<Hash> method|/routine/push#(Hash)_method_push> for an example where\nindirection via this subroutine can be helpful.\n\nThe C<push> method is supposed to flatten all arguments of type L<C<Slip>|/type/Slip>.\nTherefore, if you want to implement a conforming method for a new collection\ntype, it should behave as if its signature was just:\n\n    multi method push(::?CLASS:D: **@values is raw --> ::?CLASS:D)\n\nAutovivification to an instance of the new type is L<provided by the default\nbase class|/routine/append#(Any)_method_append> if the new type implements the\nL<C<Positional>|/type/Positional> role. If the new type is not L<C<Positional>|/type/Positional>, autovivification can\nbe supported by adding a multi method with a signature like\n\n    multi method push(::?CLASS:U: **@values is raw --> ::?CLASS:D)\n\n=head2 sub append\n\n    multi append(\\a, **@b is raw)\n    multi append(\\a, \\b)\n\nCalls method C<append> on the first argument, passing the remaining arguments.\nMethod C<append> is supposed to add the provided values to the end of the\ncollection or parts thereof. Unlike method C<push>, method C<append> should\nfollow the L<single argument rule|/language/functions#Slurpy_conventions>. So\nif you want to implement a conforming method C<append> for a new collection\ntype, it should behave as if its signature was just:\n\n    multi method append(::?CLASS:D: +values --> ::?CLASS:D)\n\nSimilar to L<routine C<push>|/routine/push#(Independent_routines)_sub_push>, you\nmay need to add a multi method if you want to support autovivification:\n\n    multi method append(::?CLASS:U: +values --> ::?CLASS:D)\n\nThe subroutine form of C<append> can be helpful when appending to the values of\na L<C<Hash>|/type/Hash>. Whereas L<method C<append>|/routine/append#(Hash)_method_append> will\nsilently ignore literal pairs that are interpreted as named arguments, the\nsubroutine will throw:\n\n    my %h = i => 0;\n    append %h, i => (1, 42);\n    CATCH { default { put .message } };\n    # OUTPUT: «Unexpected named argument 'i' passed␤»\n\n=head1 Control routines\n\nRoutines that change the flow of the program, maybe returning a value.\n\n=head2 sub exit\n\n    multi exit()\n    multi exit(Int(Any) $status)\n\nExits the current process with return code C<$status> or zero if no\nvalue has been specified. The exit value (C<$status>), when different\nfrom zero, has to be opportunely evaluated from the process that catches\nit (e.g., a shell); it is the only way to return an exit code different\nfrom zero from a L<Main|/routine/MAIN>.\n\nC<exit> prevents the L<LEAVE|/language/phasers#LEAVE> phaser to be\nexecuted, but it will run the code in the\nL<C<&*EXIT>|/language/variables#index-entry-%26*EXIT> variable.\n\nC<exit> should be used as last resort only to signal the parent process\nabout an exit code different from zero, and not to terminate\nexceptionally a method or a sub: use L<exceptions|/language/exceptions>\ninstead.\n\nThe first call of C<exit> in a process sets the return code, regardless\nof any subsequent calls to C<exit> in the same, or any other thread.\n\n=head2 sub done\n\n    sub done(--> Nil)\n\nIf used outside any supply or react block, throws an exception C<done without\nsupply or react>. Within a L<C<Supply>|/type/Supply> block, it will signal that\nthe supply will not emit further values, and leaves the supply block. See also\nL<documentation on method C<done>|/routine/done>.\n\nC<done> is implemented as a L<control exception|/language/phasers#CONTROL> and\ncan therefore be used by something called from the C<supply> or C<react> block\nthat it refers to.\n\n=for code\nmy $supply = supply {\n    for 1 .. 3 {\n        emit($_);\n    }\n    done;\n    say \"never reached\";\n}\n$supply.tap( -> $v { say \"Second : $v\" }, done => { say \"No more\" });\n# OUTPUT: «Second : 1␤Second : 2␤Second : 3␤No More␤»\n\nThe block passed to the C<done> named argument when tapping the supply will be\nrun when C<done> is called within the C<supply> block. Similarly, C<whenever>\nblocks that were used to tap the supply will have any C<LAST> phasers called.\n\nAs of the 2021.06 release of the Rakudo compiler, it is also possible to\nsupply a value with C<done>:\n\n    sub done($value --> Nil)\n\nThe specified value will first be C<emit>ted before an argumentless\nC<done> will be called.\n\n=for code\nmy $supply = supply {\n    for 1 .. 3 {\n        emit($_);\n    }\n    done 42;  # same as: emit 42; done\n}\n$supply.tap: -> $v { say \"Val: $v\" }, done => { say \"No more\" }\n# OUTPUT: OUTPUT: «Val: 1␤Val: 2␤Val: 3␤Val: 42␤No More␤»\n\n=head2 sub lastcall\n\n    sub lastcall(--> True)\n\nTruncates the current dispatch chain, which means any calls to\nC<nextsame>, C<callsame>, C<nextwith>, and C<callwith> will not\nfind any of the next candidates. Note that since C<samewith>\nrestarts the dispatch from the start, it's not affected by the\ntruncation of current chain with C<lastcall>.\n\nConsider example below. C<foo(6)> uses C<nextsame>\nwhen C<lastcall> hasn't been called, and so it reaches the L<C<Any>|/type/Any>\ncandidate. C<foo(2)> calls C<nextsame> as well, but since\nC<lastcall> was called first, the dispatch chain was truncated and\nthe L<C<Any>|/type/Any> candidate was not reached. The last call, C<foo(1)>,\ncalls C<lastcall> too, however, it then uses C<samewith>, which\nisn't affected by it, and so the dispatch re-starts from scratch,\nhits the L<C<Int>|/type/Int> candidate with the new argument C<6>, and then\nproceeds to the L<C<Any>|/type/Any> candidate via C<nextsame> (which\nisn't affected by the C<lastcall> that was used before the\nC<samewith> was called):\n\n    multi foo (Int $_) {\n        say \"Int: $_\";\n        lastcall   when *.is-prime;\n        nextsame   when *  %% 2;\n        samewith 6 when * !%% 2;\n    }\n    multi foo (Any $x) { say \"Any $x\" }\n\n    foo 6; say '----';\n    foo 2; say '----';\n    foo 1;\n\n    # OUTPUT:\n    # Int: 6\n    # Any 6\n    # ----\n    # Int: 2\n    # ----\n    # Int: 1\n    # Int: 6\n    # Any 6\n\n=end pod\n"
  },
  {
    "path": "doc/Type/utf8.rakudoc",
    "content": "=begin pod :kind(\"Type\") :subkind(\"class\") :category(\"composite\")\n\n=TITLE class utf8\n\n=SUBTITLE Mutable uint8 buffer for utf8 binary data\n\n    class utf8 does Blob[uint8] is repr('VMArray') {}\n\nA C<utf8> is a subtype of Blob which is specifically uint8 data for holding UTF-8\nencoded text.\n\n    my utf8 $b = \"hello\".encode;\n    say $b[1].fmt(\"0x%X\"); # OUTPUT: «0x65␤»\n\n=end pod\n"
  },
  {
    "path": "doc/announcements.rakudoc",
    "content": "=begin rakudoc :kind<Language> :subkind<Language> :category<beginning>\n=TITLE Announcements page\n=SUBTITLE A date-stamped list of notes relevant to the Raku documentation site.\n\n=begin Note :date<2024-05-12> :caption<New functionality>\nAn announcements page is now available. The most recent announcement will pop up when\nthe website is loaded, but it will not appear again.\n\nAnnouncements can contain all the RakuDoc elements, including:\n=item lists as here\n=item format / markup codes such C<inline code>, B<bolded text>, I<Italics>, B<I<bolded italics>>.\n\nThe only constraint is how much space is used in the popup.\n=end Note\n\n\n=end rakudoc\n"
  },
  {
    "path": "lib/Pod/Cache.rakumod",
    "content": "unit class Pod::Cache;\n\n=begin overview\n\nGiven a filename, generate a cached, rendered text version of the POD\nin that file. Return the C<IO> of the cached file.\n\nUse the new RakuAST generation as it's speedier (and more likely to be correct).\n\n=end overview\n\n\nmethod cache-file(Str $file --> Str) {\n\n    # We only cache rakudoc files.\n    return $file if ! $file.ends-with('.rakudoc');\n\n    my $outfile = '.pod-cache/' ~ $file;\n    my $output-io = $outfile.IO;\n\n    my $in-time = $file.IO.modified;\n    my $out-time = $output-io.e ?? $output-io.modified !! 0;\n\n    # If the input file is newer or the target file is empty, cache.\n    # The empty check helps in cases where the cache creation died for some reason\n\n    if $in-time > $out-time || $output-io.s == 0 {\n       mkdir $output-io.dirname;\n       my $outfile = $output-io.open(:w);\n       LEAVE $outfile.close;\n       $outfile.lock;\n\n       %*ENV<RAKUDO_RAKUAST>=\"1\"; # Activate AST mode\n       my $job = Proc::Async.new($*EXECUTABLE-NAME, '--doc', $file);\n       $job.stdout.tap(-> $buf {$outfile.print: $buf});\n\n       my $has-error = ! await $job.start;\n       if $has-error {\n           note \"Error occurred caching $file\";\n       }\n    }\n    $outfile\n}\n"
  },
  {
    "path": "lib/Pod/Convenience.rakumod",
    "content": "unit module Pod::Convenience;\n\n=begin overview\n\nProvide C<&extract-pod> which returns an object containing all the pod\nelements from a given file.\n\n=end overview\n\n# \"File\" class was deprecated; use the FileSystem if it's available, fall back to deprecated if not.\n# (should now work on both new and old rakudos, avoiding deprecation notice where possible\nmy $class = ::(\"CompUnit::PrecompilationStore::FileSystem\");\nif $class ~~ Failure {\n    $class = ::(\"CompUnit::PrecompilationStore::File\");\n}\n\nmy $precomp-store = $class.new(:prefix($?FILE.IO.parent(3).child(\".pod-precomp\")));\nmy $precomp = CompUnit::PrecompilationRepository::Default.new(store => $precomp-store);\n\nsub extract-pod(IO() $file) is export {\n    use nqp;\n    # The file name is enough for the id because POD files don't have depends\n    my $id = nqp::sha1(~$file);\n    my $handle = $precomp.load($id,:since($file.modified))[0];\n\n    if not $handle {\n        # precompile it\n        $precomp.precompile($file, $id, :force);\n        $handle = $precomp.load($id)[0];\n    }\n\n    return nqp::atkey($handle.unit,'$=pod')[0];\n}\n"
  },
  {
    "path": "resources/i18n/de/README.de.md",
    "content": "# Offizielle Dokumentation von Raku\n\n[![Build Status](https://travis-ci.org/perl6/doc.svg?branch=master)](https://travis-ci.org/perl6/doc) [![artistic](https://img.shields.io/badge/license-Artistic%202.0-blue.svg?style=flat)](https://opensource.org/licenses/Artistic-2.0)\n\n[![Run Status](https://api.shippable.com/projects/591e99923f2f790700098a30/badge?branch=master)](https://app.shippable.com/github/perl6/doc)\n\nEine HTML Version dieser Dokumentation findet sich unter [https://docs.perl6.org/](https://docs.perl6.org/).\nDies ist die momentan empfohlene Methode diese Dokumentation zu nutzen.\n\nAusserdem gibt es ein Kommandozeilen-Tool namens \"p6doc\".\n\n(Falls du dieses Repository via GitHub nutzt, werden die meisten\nDateien nicht korrekt angezeigt, weil sie in Raku Pod geschrieben\nsind, GitHub aber Perl Pod an nimmt).\n\n## README in anderen Sprachen\n\n* [README in Chinesisch](../zh/README.zh.md)\n* [README in Englisch](../../..README.md)\n* [README in Italienisch](../it/README.it.md)\n* [README in Spanisch](../es/README.es.md)\n* [README in Französisch](../fr/README.fr.md)\n\n## Installation von p6doc\n\nDieses Module ist im Raku Module Ecosystem verfügbar. Verwende\n\n    $ zef install p6doc\n\num die ausführbaren Dateien zu installieren und diese in deinem\nSuchpfad verfügbar zu machen.\n\n## Benutzung von p6doc\n\nFalls sich Rakudo `perl6` als ausführbare Datei in deinem `PATH`\nbefindet, verwende\n\n    $ ./bin/p6doc Str\n\num die Dokumentation der Klasse `Str` oder\n\n    $ ./bin/p6doc Str.split\n\num die Dokumentation für die Methode `split` in der Klasse `Str`\nanzuzeigen. Falls du `pod6doc` mit `zef` installiert hast, kannst du\n`./bin` weg lassen. Ausserdem kannst du\n\n    $ p6doc -f slurp\n\nverwenden, um die Dokumentation von Standard-Funktionen\nanzuzeigen. Abhängig von der Zugriffsgeschwindigkeit deiner Harddisk und der Rakudo Version kann dies eine Weile dauern.\n\n-------\n\n## Erzeugen der HTML Dokumentation\n\nInstalliere die Abhängigkeiten durch ausführen von\n\n    $ zef --deps-only install .\n\nin deinem Checkout-Verzeichnis.\n\nFalls du [`rakubrew`](https://rakubrew.org/) im `shim` Modus verwendest, führe\nden folgenden Befehl aus, um neu installierte Scripte verfügbar zu machen:\n\n    $ rakubrew rehash\n\nZusätzlich zu den Raku Abhängigkeiten musst du `graphviz`\ninstalliert haben. Unter Debian kannst du dies tun mit\n\n    $ sudo apt-get install graphviz\n\nUm die Web-Seiten der Dokumentation zu erstellen, verwende einfach\n\n    $ make html\n\nBitte beachte, dass du ausserdem [nodejs](https://nodejs.org)\ninstalliert haben musst, um die HTML Inhalte mit dem obigen Befehl zu\nerzeugen, insbesonders muss sich ein ausführbares `node` in deinem\n`PATH` befinden.\n\nNachdem die Web-Seiten erzeugt wurden, kannst du sie auf deinem lokalen Computer anzeigen, indem du das enthaltene Programm  `app.pl` mit\n\n    $ make run\n\nstartest. Dann kannst du die Beispiel-Dokumentation anschauen, indem\ndu in deinem web browser die URL\n[http://localhost:3000](http://localhost:3000) aufrufst.\n\nDu benötigst zumindest eine Installation von\n[Mojolicious](https://metacpan.org/pod/Mojolicious) auf deinem\nComputer und du benötigst ausserdem [nodejs](https://nodejs.org) für\nSyntax-Hervorhebung. Moglicherweise benötigst du noch weitere\nModule. Du kannst diese mit\n\n    $ cpanm --installdeps .\n\ninstallieren.\n\n---------\n\n## Wir brauchen deine Hilfe!\n\nRaku ist eine umfangreiche Sprache und die Erstellung der Dokumentation erfordert einen hohen Aufwand. Wir sind dankbar für jede Hilfe.\n\nHier einige Möglichkeiten, uns dabei zu unterstützen:\n\n * Erstellen von fehlender Dokumentation für Klassen, Rollen, Methoden\n   oder Operatoren.\n * Hinzufügen von Beispielen zur Verwendung zu bereits existierender\n   Dokumentation.\n * Korrekturlesen und korrigieren der Dokumentation.\n * Eröffnen einer Problemmeldung (issue) auf GitHub zu fehlender Dokumentation.\n * Verwende `git grep TODO` in diesem Repository und ersetze TODO\n   Abschnitte durch die eigentliche Dokumentation.\n\n[Issues page](https://github.com/Raku/doc/issues) hat eine Liste der\nderzeitigen Problemmeldungen und bekannte fehlende Teile der\nDokumentation. Das Dokument [CONTRIBUTING](CONTRIBUTING.md) erklärt\nkurz wie du beginnen kannst, zur Dokumentation beizutrage.\n\n--------\n\n## Einige Anmerkungen:\n\n**F:** Warum wird die Dokumentation nicht in die CORE Quellen integriert?<br>\n**A:** Einige Gründe sind:\n\n  1. Diese Dokumentation sill allgemeingültig sein in Bezug zu einer\n     bestimmten Version der Spezifikation und soll nicht an eine\n     spezifische Raku Implementierung gebunden sein.\n\n  2. Die Handhabung von eingebettetem Pod unterscheidet sich leicht\n     zwischen verschiedenen Implementationen. Wir verhindern so\n     potentielle Einflüsse der Laufzeit-Umgebung.\n\n  3. Ein separates Repository im perl6 GitHub Konto lädt potentiell\n     mehr Beitragende und Editoren ein.\n\n**F:** Sollte ich Methoden von Super-Klassen und Rollen integrieren?<br>\n\n**A:** Nein. Die HTML Version schliesst bereits Methoden von\n       Super-Klassen und Rollen ein und das `p6doc` Skript wird diese\n       zukünftig ebenfalls handhaben können.\n\n--------\n\n## Vision\n\n> Ich möchte, dass p6doc and docs.perl6.org die Nr. 1 Quelle wird, die\n> du nutzen kannst, wenn du etwas wissen willst über eine Raku\n> ElementEigenschaft , sei es betreffend die Sprache, eingebaute Typen\n> oder Routinen. Ich möchte dass sie nützlich ist für jeden Raku\n> Programmierer.\n>\n>    -- moritz\n\n--------\n\n# ENV VARS\n\n- Setze `RAKU_DOC_TEST_VERBOSE` auf einen `true` Wert, um ausführliche Meldungen während eines Runs der Test-Suite anzuzeigen.\nDies ist nützlich, um fehlgeschlagene Tests zu korrigieren.\n- `RAKU_DOC_TEST_FUDGE` wandelt `skip-test` Code Beispiele in TODO um im `xt/examples-compilation.t` Test.\n\n# LIZENZ\n\nDer Programm-Code in diesem Repository ist verfügbar unter der\nArtistic License 2.0, wie sie von der Perl Foundation veröffentlicht\nwurde. Der komplette Text ist in der Datei [LICENSE](LICENSE) zu\nfinden.\n\nDieses Repository enthält ausserdem Code, der von Dritten erstellt und\nmöglicherweise unter einer anderen Lizenz lizenziert wurde. Solche\nDateien enthalten Angaben zu Copyright und Lizenz am Anfang der\nDatei. Derzeit fallen unter anderem die folgenden Dateien unter diese\nKategorie:\n\n* Beispiele von Stack Overflow [MIT License](http://creativecommons.org/licenses/MIT); ([ref #1](http://stackoverflow.com/a/43669837/215487) for [1f7cc4e](https://github.com/Raku/doc/commit/1f7cc4efa0da38b5a9bf544c9b13cc335f87f7f6))\n* Tabellen-Sortier-Plugin von https://github.com/christianbach/tablesorter ;\n  [MIT License](http://creativecommons.org/licenses/MIT)\n"
  },
  {
    "path": "resources/i18n/es/README.es.md",
    "content": "# Documentación Oficial de Raku\n\n[![Build Status](https://travis-ci.org/perl6/doc.svg?branch=master)](https://travis-ci.org/perl6/doc) [![artistic](https://img.shields.io/badge/license-Artistic%202.0-blue.svg?style=flat)](https://opensource.org/licenses/Artistic-2.0)\n\n[![Run Status](https://api.shippable.com/projects/591e99923f2f790700098a30/badge?branch=master)](https://app.shippable.com/github/perl6/doc)\n\nUna versión HTML de esta documentación puede ser encontrada en [https://docs.perl6.org/](https://docs.perl6.org/).\nEsta es la documentación recomendada.\n\nTambién hay disponible un comando para la terminal: \"p6doc\".\n\n(Si estás buscando el repositorio en GitHub, la mayoría de los archivos no serán mostrados correctamente,\nya que esto es Raku Pod6, y GitHub asume que es Perl Pod).\n\n## README en otros lenguajes\n\n* [README en alemán](../de/README.de.md)\n* [README en chino](../zh/README.zh.md)\n* [README en italiano](../it/README.it.md)\n* [README en inglés](../../../README.md)\n* [README en francés](../fr/README.fr.md)\n\n## Instalar p6doc\n\nEste módulo está disponible en el ecosistema de módulos de Raku. Usa:\n\n    $ zef install p6doc\n\npara instalar los binarios y añadirlo a tu path.\n\n## Usar p6doc\n\nCuando tengas `perl6` (Rakudo) añadido al `PATH`, ejecuta\n\n    $ ./bin/p6doc Str\n\npara ver la documentación para la clase `Str`, o\n\n    $ ./bin/p6doc Str.split\n\npara ver la documentación del método `split` de la clase `Str`. Puedes\nomitir `./bin` si lo has instalado mediante `zef`.\nTambién puedes hacer\n\n    $ p6doc -f slurp\n\npara buscar la documentación estándar de funciones. Dependiendo de la velocidad\nde tu disco duro y de la versión de Rakudo, es posible que tarde unos minutos.\n\n-------\n\n## Generando la documentación en HTML\n\nInstala las dependencias ejecutando lo siguiente en el directorio correspondiente:\n\n    $ zef --deps-only install .\n\nSi usas [`rakubrew`](https://rakubrew.org/) en modo `shim`, ejecuta también:\n\n    $ rakubrew rehash\n\npara actualizar los correctores de compatibilidad de los ejecutables instalados.\n\nAparte de las dependencias de Raku, necesitas tener `graphviz` instalado. En Debian\nlo puedes instalar mediante:\n\n    $ sudo apt-get install graphviz\n\nPara generar las páginas webs de la documentación, simplemente ejecuta:\n\n    $ make html\n\nTen en cuenta que debes tener instalado [nodejs](https://nodejs.org)\npara producir el contenido HTML con el anterior comando, en particular,\n`node` debería estar en tu `PATH`.\n\nCuando las páginas hayan sido generadas, puedes verlas localmente\nen tu ordenador ejecutando el programa `app.pl`:\n\n    $ make run\n\nUna vez hecho lo anterior, puedes ver la documentación de ejemplo\ndirigiéndote a [http://localhost:3000](http://localhost:3000) en tu navegador.\n\nNecesitarás, por lo menos, tener [Mojolicious](https://metacpan.org/pod/Mojolicious)\ninstalado. Además precisarás [nodejs](https://nodejs.org) para activar el resaltado.\nTambién hay módulos adicionales que podrías necesitar, instálalos ejecutando:\n\n    $ cpanm --installdeps .\n\n---------\n\n## ¡Se precisa ayuda!\n\nRaku no es un lenguaje de programación pequeño, y documentarlo requiere mucho esfuerzo. Cualquier ayuda es bienvenida.\n\nAlgunas maneras en las que puedes ayudarnos:\n\n  * Añadiendo documentación de clases, roles, métodos u operadores.\n  * Añadiendo ejemplos de uso a la documentación existente.\n  * Revisando y corrigiendo la documentación.\n  * Abriendo issues en GitHub si consideras que falta documentación.\n  * Haciendo `git grep TODO` en este repositorio, y reemplazando los items TODO con documentación.\n\n[Esta página](https://github.com/Raku/doc/issues) tiene una lista de issues actuales y partes de la documentación que faltan. El documento [CONTRIBUTING](CONTRIBUTING.md) explica brevemente cómo empezar a contribuir.\n\n--------\n## Algunas aclaraciones:\n\n**P:** ¿Por qué no estáis incluyendo la documentación en el código fuente del CORE?<br>\n**R:** Debido a varias razones:\n\n  1. Esta documentación pretende ser universal con respecto a una versión dada de una especificación, y no necesariamente estar atada a una implementación específica de Raku.\n\n  2. El tratamiento que las implementaciones hacen de Pod6 es todavía un poco inconsistente; esto evita impactos potenciales en el tiempo de ejecución.\n\n  3. Un repo separado en la cuenta de Raku de GitHub invita a más contribuidores y editores a participar.\n\n**P:** ¿Debería incluir los métodos de las superclases o de los roles?<br>\n**A:** No. La versión en HTML ya los incluye, y el script `p6doc` también.\n\n--------\n\n## Objetivo\n\n> Quiero que p6doc y docs.perl6.org lleguen a ser el recurso número 1 para consultar cualquier\n> característica de Raku, ya sea del lenguaje o de sus tipos y rutinas. Quiero que sea útil para todo programador de Raku.\n>\n>    -- moritz\n\n--------\n\n# ENV VARS\n\n- Poner `RAKU_DOC_TEST_VERBOSE` a `true` para mostrar mensajes durante la ejecución del conjunto de tests. Práctico para depurar un test suite que falla.\n- `RAKU_DOC_TEST_FUDGE` cambia los ejemplos de código `skip-test` a TODO en el test `xt/examples-compilation.t`.\n\n# LICENCIA\n\nEl código en este repositorio está disponible bajo la Artistic License 2.0 como lo publicó la Perl Foundation. Ver el fichero [LICENSE](LICENSE) para ver el texto completo.\n\nEste repositorio también contiene código de terceros que podría tener otra licencia, en cuyo caso indican al principio de los mismos el copyright y sus términos de licencia. Actualmente incluyen:\n\n* Ejemplos de StackOverflow [Licencia MIT](http://creativecommons.org/licenses/MIT); ([ref #1](http://stackoverflow.com/a/43669837/215487) for [1f7cc4e](https://github.com/Raku/doc/commit/1f7cc4efa0da38b5a9bf544c9b13cc335f87f7f6))\n* Table sorter plugin from https://github.com/christianbach/tablesorter ;\n  [Licencia MIT](http://creativecommons.org/licenses/MIT)\n"
  },
  {
    "path": "resources/i18n/fr/README.fr.md",
    "content": "# Documentation officielle de Raku\n\n[![Build Status](https://travis-ci.org/perl6/doc.svg?branch=master)](https://travis-ci.org/perl6/doc) [![artistic](https://img.shields.io/badge/license-Artistic%202.0-blue.svg?style=flat)](https://opensource.org/licenses/Artistic-2.0)\n\n[![Run Status](https://api.shippable.com/projects/591e99923f2f790700098a30/badge?branch=master)](https://app.shippable.com/github/perl6/doc)\n\nLa version HTML de cette documentation peut être trouvée en [https://docs.perl6.org/](https://docs.perl6.org/).\nC'est la documentation reconmmandée.\n\nUne commande est également disponible pour le terminal: \"p6doc\".\n\n(Si vous recherchez ce repository via GitHub, la plupart des fichiers ne seront pas affichés correctement car la documentation est écrite avec Pod pour Raku et GitHub le considère comme Pod pour Perl)\n\n\n## README dans d'autres langues\n\n* [README en allemand](../de/README.de.md)\n* [README en anglais](../../../README.md)\n* [README en chinois](../zh/README.zh.md)\n* [README en espagnol](../es/README.es.md)\n* [README en italien](../it/README.it.md)\n* [README en japonais](../jp/README.jp.md)\n\n## Installez p6doc\n\n`p6doc` est un module disponible dans l'écosystème des modules Raku. Utilisez la comande suivante:\n\n    $ zef install p6doc\n\npour installer le module et l'ajouter à votre path.\n\n## Utilisez p6doc\n\nUne fois que vous ajoutez `perl6` (Rakudo) au `PATH`, exécutez la commande\n\n\n    $ ./bin/p6doc Str\n\npour voir la documentation de la classe `Str`, vous pouvez aussi exécuter la commande\n\n    $ ./bin/p6doc Str.split\n\npour voir la documentation de la méthode `split` dans la classe `Str`.\nIl est possible d'omettre le préfixe `./Bin` s'il est intallé via `zef`.\nVous pouvez également utiliser la commande\n\n    $ p6doc -f slurp\n\npour parcourir la documentation des fonctions standard. Selon la vitesse de votre disque et la version de Rakudo, cela peut prendre un certain temps.\n\n-------\n\n## Générer la documentation HTML\n\nPour installez les dépendances exécutez la commande suivante dans le répertoire correspondant:\n\n    $ zef --deps-only install .\n\nSi vous utilisez [`rakubrew`](https://rakubrew.org/) en mode `shim`, exécutez également la commande suivante afin de mettre à jour les `shims` pour les exécutables installés:\n\n    $ rakubrew rehash\n\nEn plus des dépendances Raku, vous devez avoir `graphviz` installé, que vous pouvez installer avec la commande:\n\n    $ sudo apt-get install graphviz\n\nPour générer la documentation au format `HTML`, il suffit d'exécuter la commande:\n\n    $ make html\n\nVous devez avoir installé [nodejs](https://nodejs.org) pour pouvoir produire le contenu au format `HTML` avec la commande précédente, en particulier, `node` devrait être dans le `PATH`.\n\nUne fois les pages HTML ont été générés, elles peuvent être visualisées sur votre ordinateur via `app.pl`, en exécutant la commande:\n\n    $ make run\n\nAprès cela, vous pouvez voir la documentation dans votre navigateur internet au [http://localhost:3000](http://localhost:3000)\n\nVous devez avoir installé [Mojolicious](https://metacpan.org/pod/Mojolicious).\nVous aurez également besoin [nodejs](https://nodejs.org) pour pouvoir utiliser le surlignement.\nIl y a aussi des modules supplémentaires dont vous pourriez avoir besoin, pour les installer, exécutez la commande:\n\n    $ cpanm --installdeps .\n\n---------\n\n## Nous avons besoin de votre aide!\n\nRaku est un très grand langage de programmation, le documenter nécessite beaucoup d'efforts.\nToute aide est appréciée.\n\nIl y a plusieurs façons de nous aider, certaines d'entre elles sont:\n\n  * Ajouter la documentation manquante pour les classes, les rôles, les méthodes ou les opérateurs.\n  * Ajouter des exemples d'utilisation à la documentation existante.\n  * Examiner et corriger la documentation.\n  * Ouvrez `issues`sur GitHub si vous  pensez qu'il y a un manque d'information sur la documentation.\n  * Faites `git grep TODO` dans ce repository, et remplacez les éléments TODO par la documentation réelle.\n\n[Cette page](https://github.com/Raku/doc/issues) contient une liste des problèmes actuels e des parties de documentation manquantes.\nLe document [CONTRIBUTING](CONTRIBUTING.md) explique comment vous pouvez commencer à aider.\n--------\n## Quelques clarifications:\n\n**Q:** Pourquoi la documentation n'est-elle pas incluse dans le code source CORE?<br>\n**R:** Il y a plusieurs raisons:\n\n  1. Cette documentation est destinée à être universelle par rapport à une version spécifique, elle n'est pas destinée à être une documentaion spécifique d'une implémenation spécifique de Raku.\n\n  2. La gestion des implémentations de Pod intégré est encore un peu irrégulière; cela évite les impacts d'execution potentiels.\n\n  3. Un Repository séparé du compte Raku de GitHub encourage plus de contributeurs et éditeurs à participer.\n\n**Q:** Dois-je inclure des méthodes provenant de superclasses ou de rôles dans la documentation?<br>\n**R:** Non. La version HTML inclut déjà cette information, et le script `p6doc` l'inclut également.\n\n--------\n\n## Objetif\n\n> Je veux que `p6doc` et docs.perl6.org soient la première ressource à consulter\n> toute  fonctionnalité de Perl6,\n> soit la langue, ou les types et les routines integrées. Je veux qu'il soit utile pour tous les programmeurs de Perl6.\n>\n>    -- moritz\n\n--------\n\n# Variables d'environnement\n\n- Mettre `RAKU_DOC_TEST_VERBOSE` à `true` pour afficher des messages pendant l'exécution de l'ensemble des tests. Ceci est utile lors du débogage de la suite de tests défaillante.\n- `RAKU_DOC_TEST_FUDGE` modifie les échantillons de code `skip-test` comme TODO dans le test `xt/examples-compilation.t`.\n\n# LICENCE\n\nLe code de ce repository est disponible sous la licence `Artistic License 2.0` tel que publié par la Perl Foundation. Voir le fichier [LICENSE](LICENSE) pour voir le texte intégral.\n\nCe repository contient également du code créé par des tiers que peuvent être concédés sous une licence différente. Ces fichiers indiquent les droits d'auteur et les termes de la licence en haut du fichier. Actuellement, is comprendent:\n\n* Exemples de StackOverflow [Licence MIT](http://creativecommons.org/licenses/MIT); ([ref #1](http://stackoverflow.com/a/43669837/215487) for [1f7cc4e](https://github.com/Raku/doc/commit/1f7cc4efa0da38b5a9bf544c9b13cc335f87f7f6))\n* Tableau trieur plugin de https://github.com/christianbach/tablesorter ;\n  [Licence MIT](http://creativecommons.org/licenses/MIT)\n"
  },
  {
    "path": "resources/i18n/it/README.it.md",
    "content": "# Documentazione Ufficiale Raku\n\n[![Build Status](https://travis-ci.org/perl6/doc.svg?branch=master)](https://travis-ci.org/perl6/doc) [![artistic](https://img.shields.io/badge/license-Artistic%202.0-blue.svg?style=flat)](https://opensource.org/licenses/Artistic-2.0)\n\n[![Run Status](https://api.shippable.com/projects/591e99923f2f790700098a30/badge?branch=master)](https://app.shippable.com/github/perl6/doc)\n\nUna versione HTML di questa documentazione può essere trovata al seguente link [https://docs.perl6.org/](https://docs.perl6.org/).\nIl link precedente è il modo consigliato di leggere e usare la documentazione.\n\nEsiste uno strumento da riga di comando denominato \"p6doc\",\n\n(Se stai navigando questo repository via GitHub molti dei file non saranno visualizzati\ncorrettamente poiché la documentazione è scritta usando Pod per Raku e GitHub\nlo considera invece come Pod per Perl ).\n\n## README in altri linguaggi\n\n* [README in Cinese](../zh/README.zh.md)\n* [README in Inglese](../../../README.md)\n* [README in Spagnolo](../es/README.es.md)\n* [README in Tedesco](../de/README.de.md)\n* [README in Francese](../fr/README.fr.md)\n\n## Installare p6doc\n\nLo strumento p6doc è un modulo disponibile nell'ecosistema  Raku.\nIl seguente comando\n\n    $ zef install p6doc\n\ninstalla lo strumento e lo rende disponibile nel tuo path di esecuzione.\n\n## Usare p6doc\n\nUna volta che si ha una versione Rakudo `perl6` eseguibile nel proprio `PATH`, è sufficiente\nimpartire il comando\n\n    $ ./bin/p6doc Str\n\nper vedere la documentazione della classe  `Str`, o nello specifico\n\n    $ ./bin/p6doc Str.split\n\nper visualizzar ela documentazione del method  `split` nella classe `Str`.\nE' possibile omettere il prefisso  `./bin` se si è installato tramite `zef`.\nE' possibile anche usare il comando seguente\n\n    $ p6doc -f slurp\n\nper sfogliare la documentazione di una funzione.\nA seconda della velocità del disco e della versione di Rakudo, il rendering\npuò richiedere un po' di tempo.\n\n-------\n\n## Assemblare la documentazione HTML\n\nE' necessario installare le dipendenze eseguendo il seguente comando\nnella directory ove si è fatto il checkout del repository:\n\n    $ zef --deps-only install .\n\nSe si sta usando [`rakubrew`](https://rakubrew.org/) in modalità `shim`,\nè necessario anche eseguire il seguente comando in modo da aggiornare gli \"shims\"\nper gli eseguibili installati:\n\n    $ rakubrew rehash\n\nOltre alle dipendenze specifiche di  Raku, è necessario anche avere installato `graphviz`,\nche su sistemi Debian può essere installato con il seguente comando\n\n    $ sudo apt-get install graphviz\n\nPer costruire la documentazione in formato HTML è sufficiente eseguire il comando\n\n    $ make html\n\nIl comando precedente, al fine di generare contenuto HTML, richiede [nodejs](https://nodejs.org)\ninstallato, e in particolare un eseguibile `node` raggiungibile nel `PATH`,\n\nUna volta che le pagine HTML sono state generate, è possibile visualizzarle\nsul computer locale mediante l'applicazione `app.pl` che viene avviata con\nil comando\n\n    $ make run\n\nE' possibile visualizzare la documentazione puntanto il proprio browser web all'indirizzo\n[http://localhost:3000](http://localhost:3000).\n\nPer realizzare gli \"highlights\" è necessario avere installato\n[Mojolicious](https://metacpan.org/pod/Mojolicious)\ne [nodejs](https://nodejs.org).\nSono necessari anche alcuni altri moduli, tutti installabili con il comando\n\n    $ cpanm --installdeps .\n\n---------\n\n## Help Wanted!\n\nRaku è un linguaggio vasto e documentarlo richiede molta fatica.\nOgni forma di aiuto è apprezzata.\n\nAlcuni modi per aiutare il progetto includono:\n\n * aggiungere documentazione mancante per classi, ruoli, metodi e operatori;\n * aggiungere esempi di codice alla documentazione esistente;\n * leggere e correggere gli errori nella documentazione;\n * aprire dei ticket su GitHub riguardo documentazione mancante;\n * eseguire il comando `git grep TODO` sul repository, inserendo la documentazione mancante.\n   actual documentation.\n\nLa pagina dei ticket [Issues](https://github.com/Raku/doc/issues)\ncontiene una lista dei problemi noti e delle parti di documentazione che sono note essere incomplete,\ne il file [CONTRIBUTING](CONTRIBUTING.md)\nspiega brevemente come iniziare a contribuire alla documentazione.\n\n\n--------\n\n## Alcune note:\n\n**Q:** Perché la documentazione non viene inclusa nell'albero dei sorgenti CORE?<br>\n**A:** Ci sono diverse ragioni:\n\n  1. Questa documentazione è pensata per essere universale rispetto\n     a una data versione delle specifiche di linguaggio, e non necessariamente\n     legata a una specifica implementazione di  Raku.\n  2. Le implementazioni che gestiscono Pod Embedded sono ancora\n     non ottimali; e così facendo si evitano problemi di runtime.\n  3. Un repository separato sull'account perl6 Github invita un maggior numero di\n     potenziali volontari e scrittori.\n\n**Q:** Devo includere nella documentazione metodi dalle superclassi o ruoli?<br>\n**A:** No. La versione HTML include già automaticamente i metodi dalle superclassi e dei ruoli, e lo strumento `p6doc` sarà migliorato in questo senso.\n\n--------\n\n## Visione\n\n> I want p6doc and doc.perl6.org to become the No. 1 resource to consult\n> when you want to know something about a Raku feature, be it from the\n> language, or built-in types and routines. I want it to be useful to every\n> Raku programmer.\n>\n>    -- moritz\n\n\n*Io voglio che p6doc e docs.perl6.org siano la prima risorssa da consultare quanto vuoi sapere qualcosa riguardo a una funzionalità di Raku, sia essa di linguaggio, tipo di dato o routine. Voglio che sia utile a ogni programmatore Raku.*\n\n--------\n\n# Variabili di ambiente\n\n- `RAKU_DOC_TEST_VERBOSE` impostata a un valore true consente di visualizare messaggi \"verbose\"\ndurante l'esecuzione di una test-suite. E' utile per debuggare test che falliscono.\n- `RAKU_DOC_TEST_FUDGE` considera i frammenti di codice con `skip-test` come dei TODO quando esegue il test `xt/examples-compilation.t`.\n\n# Licenza\n\nIl codice in questo repository è disponibile mediante la licenza Artistic License 2.0\nnella versione pubblicata da  The Perl Foundation.\nSi veda il file [LICENSE](LICENSE) per l'intero contenuto della licenza.\n\nQuesto repository contiene anche codice scritto da autori terzi che potrebbe essere concesso con una licenza differente. Tali files indicano il copyright e i termini di licenza all'inizio del file stesso. Attualmente tali file includono:\n\n* Esempi da Stack Overflow [MIT License](http://creativecommons.org/licenses/MIT); ([ref #1](http://stackoverflow.com/a/43669837/215487) for [1f7cc4e](https://github.com/Raku/doc/commit/1f7cc4efa0da38b5a9bf544c9b13cc335f87f7f6))\n* Table sorter plugin da https://github.com/christianbach/tablesorter ;\n  [MIT License](http://creativecommons.org/licenses/MIT)\n"
  },
  {
    "path": "resources/i18n/jp/README.jp.md",
    "content": "# PERL6の公式文書\n\n[![Build Status](https://travis-ci.org/perl6/doc.svg?branch=master)](https://travis-ci.org/perl6/doc) [![artistic](https://img.shields.io/badge/license-Artistic%202.0-blue.svg?style=flat)](https://opensource.org/licenses/Artistic-2.0)\n\n[![Run Status](https://api.shippable.com/projects/591e99923f2f790700098a30/badge?branch=master)](https://app.shippable.com/github/perl6/doc)\n\nここにHTML版があります [https://docs.perl6.org/](https://docs.perl6.org/)。これを読むのがおすすめです。\n\nまた、\"p6doc\"と呼ばれるコマンドラインツールがあります。\n\nあなたがこのリポジトリをGitHubで閲覧しているのなら、ほとんどのファイルは正しく表示されないかもしれません。 GitHubはRaku PodをPerl Podとみなすからです。\n\n## 外国語のREADME\n\n* [README in Chinese](../zh/README.zh.md)\n* [README in Italian](../it/README.it.md)\n* [README in English](../../../README.md)\n* [README in German](../de/README.de.md)\n* [README in Spanish](../es/README.es.md)\n* [README in French](../fr/README.fr.md)\n\n## p6docの使用\n\n`PATH`にRakudo `perl6`が入った状態で、\n\n    $ ./bin/p6doc Str\n\nと打つと`Str`クラスの文書を閲覧することができます。また、\n\n    $ ./bin/p6doc Str.split\n\nと打つと、`Str`クラスの`split`メソッドの文書を閲覧することができます。zefでインストールした場合は、`./bin`を抜いて\n\n    $ p6doc -f slurp\n\nと打つと標準的な関数の文書を閲覧することができます。これは時間がかかることがあります。\n\n-------\n\n## HTMLの文書の構築\n\nチェックアウトしたディレクトリで依存関係をインストールしてください:\n\n    $ zef --deps-only install .\n\n[`rakubrew`](https://rakubrew.org/)を使用している場合は、次のコマンドも実行してください:\n\n    $ rakubrew rehash\n\nRakuの依存関係に加えて、 `graphiviz` がインストールしてある必要があります。\nDebian環境なら下記のコマンドでインストールすることができます:\n\n    $ sudo apt-get install graphviz\n\n公式文書のウェブページを構築するには、下記のコマンドを実行するだけで大丈夫です:\n\n    $ make html\n\n上記のコマンドでHTMLのコンテンツを生成するためには[nodejs](https://nodejs.org)が必要になるかもしれないことに注意してください。\nまた、 `node` の実行ファイルが `PATH` 以下にある必要があります。\n加えて、nodejsの依存モジュールをビルドするために `g++` もインストールされている必要があります。\nnodejsはコードにシンタックスハイライトをかけたい場合にのみ必要になります。\nもしもその必要がない場合は、次のコマンドを実行してください\n\n    $ make html-nohighlight\n\nページの生成後は、同梱の `app.pl` プログラムを実行させることで、ローカル環境でこれらのページを見ることができます:\n\n    $ make run\n\n次のアドレスをブラウザに入力して閲覧してください:\n[http://localhost:3000](http://localhost:3000).\n\n少なくとも [Mojolicious](https://metacpan.org/pod/Mojolicious) がインストールされている必要があります。\nまたシンタックスハイライトを行いたい場合は [nodejs](https://nodejs.org) が必要になります。\nその他の必要なモジュールについては、次のコマンドで全部インストールすることができます:\n\n    $ cpanm --installdeps .\n\n---------\n\n## あなたの助けが必要です！\n\nRakuは小さな言語ではありません。したがって、この言語の仕様を文書化するには多大な努力が必要です。\nどんな些細なことでも私たちの助けになります。\n\n例えばこんな方法があります:\n\n * クラス、ロール、メソッド、演算子について抜けていた文書を追加する\n * 使用例を追加する\n * 推敲し文書を修正する\n * GithubでISSUEを開いて抜けている文書についてメンテナーに報告する\n *  `git grep TODO` コマンドをこのリポジトリで実行し、TODOになっている事項を実際の文書に置き換える\n\n[Issues page](https://github.com/Raku/doc/issues) には現在のissueと足りない文書が掲載されています。\nまた、 [the CONTRIBUTING document](CONTRIBUTING.md)\nにはどうやって文書作成に貢献したらよいのか簡潔に述べられています。\n\n--------\n\n## いくつかの注意点:\n\n**Q:** どうしてコアのソースコードに文書を埋め込んでいないのですか?<br>\n**A:** いくつか理由があります:\n\n  1. この文書はあるバージョンの仕様に対して共通な内容が掲載されるようになっています。\n     特定のRakuの実装に対するものではありません。\n  2. 埋め込まれたPodに対する扱い方にはまだまだばらつきがあります。\n     実行時間に対する影響を避けています。\n  3. コアのソースコードとはまた別のリポジトリに対してコントリビューターや編集者を招待しています。\n\n**Q:** スーパークラスやロールのメソッドを含めるべきですか?<br>\n**A:** 含めるべきではありません。HTML版の文書にはすでにスーパークラスとロールのメソッドが含まれています。\n　　　　また `p6doc` スクリプトが先ほど述べたことと同じことを教えてくれるでしょう。\n\n--------\n\n## ビジョン\n\n> Rakuの機能について調べているときにp6docとdocs.perl6.orgがこの世界で一番の情報源になってほしい。\n> それは言語自体においても、組み込みの型においても、ルーチンにおいてもそうであってほしい。\n> この文書がすべてのRakuプログラマーにとって便利なものになってほしい。\n>    -- moritz\n\n--------\n\n# 環境変数\n\n- `RAKU_DOC_TEST_VERBOSE` をtrueにするとテストの実行中に詳細なメッセージを表示することができます。実行に失敗したデストをデバッグするときに便利です。\n- `RAKU_DOC_TEST_FUDGE` は `xt/examples-compilation.t` において、`skip-test` なコードを TODO として実行するようにします。\n\n# LICENSE\n\nThe code in this repository is available under the Artistic License 2.0\nas published by The Perl Foundation. See the [LICENSE](LICENSE) file for the full\ntext.\n\nThis repository also contains code authored by third parties that may be licensed under a different license. Such\nfiles indicate the copyright and license terms at the top of the file. Currently these include:\n\n* Examples from Stack Overflow [MIT License](http://creativecommons.org/licenses/MIT); ([ref #1](http://stackoverflow.com/a/43669837/215487) for [1f7cc4e](https://github.com/Raku/doc/commit/1f7cc4efa0da38b5a9bf544c9b13cc335f87f7f6))\n* Table sorter plugin from https://github.com/christianbach/tablesorter ;\n  [MIT License](http://creativecommons.org/licenses/MIT)\n"
  },
  {
    "path": "resources/i18n/nl/README.nl.md",
    "content": "# Officiële documentatie van Raku\n\n[![Build Status](https://travis-ci.org/perl6/doc.svg?branch=master)](https://travis-ci.org/perl6/doc) [![artistic](https://img.shields.io/badge/license-Artistic%202.0-blue.svg?style=flat)](https://opensource.org/licenses/Artistic-2.0)\n\n[![Run Status](https://api.shippable.com/projects/591e99923f2f790700098a30/badge?branch=master)](https://app.shippable.com/github/perl6/doc)\n\nEen HTML-versie van deze documentatie is te vinden onder [https://docs.perl6.org/](https://docs.perl6.org/);\ndit is momenteel de aanbevolen manier om de documentatie te raadplegen. Daarnaast bestaat er voor het raadplegen\nvan de documentatie ook een command line tool genaamd \"p6doc\".\n\nNOOT: Als je door deze repository bladert met behulp van GitHub, dan zullen de meeste bestanden niet correct\nworden weergegeven omdat ze zijn opgemaakt in Raku Pod, terwijl GitHub ze interpreteert als Perl Pod.\n\n## README in andere talen\n\n* [README in het Chinees](../zh/README.zh.md)\n* [README in het Duits](../de/README.de.md)\n* [README in het Italiaans](../it/README.it.md)\n* [README in het Spaans](../es/README.es.md)\n* [README in het Frans](../fr/README.fr.md)\n\n## Het installeren van p6doc\n\nDeze module is beschikbaar via het Raku module-ecosysteem. Geef het commando:\n\n    $ zef install p6doc\n\nom het p6doc programma te installeren, en het beschikbaar te maken via het zoekpad.\n\n## Het gebruik van p6doc\n\nGeef, met een uitvoerbaar Rakudo `perl6` bestand in het zoekpad `PATH`, het commando:\n\n    $ ./bin/p6doc Str\n\nom de documentatie voor klasse `Str` te bekijken, of het commando:\n\n    $ ./bin/p6doc Str.split\n\nom de documentatie voor methode `split` in klasse `Str` in te zien. Je kunt\nhet `./bin/`-deel achterwege laten als je Rakudo met behulp van `zef` hebt geïnstalleerd.\nJe kunt ook het commando:\n\n    $ p6doc -f slurp\n\ngebruiken om door de documentatie van de standaardfuncties te bladeren. De snelheid hierbij is\nafhankelijk van je schijfsnelheid en Rakudoversie.\n\n-------\n\n## Het genereren van de HTML-documentatie\n\nInstalleer de benodigde dependencies door het volgende commando uit te voeren in de checkout directory:\n\n    $ zef --deps-only install .\n\nAls je gebruik maakt van [`rakubrew`](https://rakubrew.org/) in `shim`-modus heb je ook\nhet volgende commando nodig om de shims voor de geïnstalleerde programma's te updaten:\n\n    $ rakubrew rehash\n\nNaast de Raku dependencies dien je ook 'graphviz' geïnstalleerd te hebben; op Debian kun\nje dit bewerkstelligen met het commando:\n\n    $ sudo apt-get install graphviz\n\nOm de documentatiewebpagina's te genereren geef je simpelweg het volgende commando:\n\n    $ make html\n\nMerk op dat je [nodejs](https://nodejs.org) geïnstalleerd dient te hebben om HTML pagina's\nte kunnen genereren met het bovenstaande commando. In het bijzonder dient het uitvoerbare\n`node` bestand via het zoekpad `PATH` vindbaar te zijn. Daarnaast moet ook `g++` zijn\ngeïnstalleerd om enkele dependencies die samen met nodejs zijn geïnstalleerd te compileren.\nnodejs is overigens alleen nodig voor het highlighten van opgenomen codefragmenten. Als\ndit niet vereist of gewenst is, dan volstaat het commando:\n\n    $ make html-nohighlight\n\nNa het genereren van de pagina's kun je ze lokaal op je computer bekijken door het starten van\nhet meegeleverde `app.pl`-programma:\n\n    $ make run\n\nJe kunt de documentatie dan bekijken door je webbrowser te verwijzen naar [http://localhost:3000](http://localhost:3000).\n\nJe dient ten minste [Mojolicious](https://metacpan.org/pod/Mojolicious) te hebben geïnstalleerd, en\nvoor syntax highlighting is ook [nodejs](https://nodejs.org) nodig. Eventuele andere modules die je\nnodig zou kunnen hebben kun je allemaal installeren middels het commando:\n\n    $ cpanm --installdeps .\n\n---------\n\n## Hulp gevraagd!\n\nRaku is geen kleine taal en het documenteren ervan is dan ook een hele onderneming.\nAlle hulp daarbij is van harte welkom, en wordt zeer gewaardeerd.\n\nDit zijn enkele manieren waarop je ons zou kunnen helpen:\n\n * Voeg ontbrekende documentatie toe voor klassen, rollen, methoden of operatoren.\n * Voeg gebruiksvoorbeelden toe aan bestaande documentatie.\n * Controleer en verbeter bestaande documentatie.\n * Wijs ons op ontbrekende documentatie door het openen van een issue op GitHub.\n * Doe een `git grep TODO` in deze repository, en vervang de TODO items door daadwerkelijke documentatie.\n\n\nDe [issues pagina](https://github.com/Raku/doc/issues) bevat een lijst van openstaande issues evenals een overzicht\nvan documentatieonderdelen waarvan bekend is dat ze ontbreken. Het [CONTRIBUTING dokument](CONTRIBUTING.md) legt\nbeknopt uit hoe je desgewenst kunt beginnen bij te dragen aan de documentatie.\n\n--------\n\n## Een paar kanttekeningen:\n\n**Q:** Waarom wordt de documentatie niet geëmbed in de CORE broncode?<br>\n**A:** Hiervoor bestaat een aantal redenen:\n\n  1. Deze documentatie beoogt universeel te zijn ten aanzien van een\n    gegeven versie van de specificatie, en is dus niet noodzakelijkerwijs\n    verbonden aan een specifieke Raku implementatie.\n  2. De verwerking van geëmbedde Pod door implementaties is vooralsnog\n    niet volkomen vlekkeloos; afzonderlijke documentatie voorkomt dus\n    potentiële runtime-complicaties.\n  3. Een aparte repository onder de perl6 GitHub-account werkt drempelverlagend,\n    en nodigt meer mensen uit bij te dragen en teksten te bewerken.\n\n**Q:** Kan ik ook bijdragen door methoden van superklassen of rollen op te nemen?<br>\n**A:** Nee. De HTML-versie omvat op dit moment al methoden van superklassen en\n    rollen, en het `p6doc`-script zal hieraan worden aangepast.\n\n--------\n\n## Visie\n\n> Ik wens dat p6doc en docs.perl6.org het nummer 1-naslagwerk worden dat\n> geraadpleegd kan worden wanneer je iets wilt weten over een Raku feature,\n> of dit nu behoort tot de taal zelf, of tot de ingebouwde typen en functies.\n> Ik wil dat het van praktisch nut is voor iedere Raku-programmeur.\n>\n>    -- moritz\n\n--------\n\n# Omgevingsvariabelen\n\n- Geef `RAKU_DOC_TEST_VERBOSE` een `true`-waarde om gedurende het doorlopen van de test suite uitvoerige meldingen weer te geven.\nDit is behulpzaam tijdens het debuggen van de test suite.\n- `RAKU_DOC_TEST_FUDGE` zet `skip-test` codevoorbeelden om in TODO in `xt/examples-compilation.t` test.\n\n# LICENTIE\n\nDe code in deze repository is beschikbaar onder de Artistic License 2.0 zoals gepubliceerd door The\nPerl Foundation. Zie het [LICENSE](LICENSE) bestand voor de volledige tekst.\n\nDeze repository bevat ook code die is geschreven door derde partijen en die onder een afwijkende licentie beschikbaar is gemaakt.\nDe betreffende bestanden vermelden het auteursrecht en de licentievoorwaarden aan het begin. Momenteel omvat deze categorie bestanden:\n\n* Examples from Stack Overflow [MIT License](http://creativecommons.org/licenses/MIT); ([ref #1](http://stackoverflow.com/a/43669837/215487) for [1f7cc4e](https://github.com/Raku/doc/commit/1f7cc4efa0da38b5a9bf544c9b13cc335f87f7f6))\n* Table sorter plugin from https://github.com/christianbach/tablesorter ;\n  [MIT License](http://creativecommons.org/licenses/MIT)\n"
  },
  {
    "path": "resources/i18n/pt/README.pt.md",
    "content": "# Documentação Oficial do Raku\n\n[![Build Status](https://travis-ci.org/perl6/doc.svg?branch=master)](https://travis-ci.org/perl6/doc) [![artistic](https://img.shields.io/badge/license-Artistic%202.0-blue.svg?style=flat)](https://opensource.org/licenses/Artistic-2.0)\n\n[![Run Status](https://api.shippable.com/projects/591e99923f2f790700098a30/badge?branch=master)](https://app.shippable.com/github/perl6/doc)\n\nUma versão HTML dessa documentação disponível em [https://docs.perl6.org/](https://docs.perl6.org/).\nQue é a versão recomendada.\n\nTambém disponível uma ferramenta de linha de comando: \"p6doc\".\n\n(Se está acessando pelo GitHub, a maioria dos documentos não serão exibidos corretamente, pois estão escritos em Raku Pod6\nmas o GitHub assume que são Perl Pod.)\n\n## README em outras línguas\n\n* [README em alemão](../de/README.de.md)\n* [README em chinês](../zh/README.zh.md)\n* [README em italiano](../it/README.it.md)\n* [README em inglês](../../../README.md)\n* [README em francês](../fr/README.fr.md)\n* [README em espanhol](../es/README.es.md)\n* [README em japonês](../jp/README.jp.md)\n* [README em neerlandês](../nl/README.nl.md)\n\n## Instalar p6doc\n\nEste módulo está disponivel no ecosistema de módulos do Raku. Use:\n\n    $ zef install p6doc\n\npara instalar os binários e adicionar ao path.\n\n## Usar p6doc\n\nCom o `perl6` (Rakudo) no `PATH`, execute\n\n    $ ./bin/p6doc Str\n\npara ver a documentacão da clase `Str`, ou\n\n    $ ./bin/p6doc Str.split\n\npara ver a documentacão do método `split` da clase `Str`. Pode\nomitir `./bin` se o `p6doc` foi instalado com o `zef`.\nTambém pode executar\n\n    $ p6doc -f slurp\n\npara pesquisar a documentacão padrão de subrotinas. Dependendo da velocidade\ndo disco rígido e da versão do Rakudo, é possivel que demore minutos.\n\n-------\n\n## Gerando a documentacão HTML\n\nInstale as dependências executando o siguinte no directório onde estão as fontes:\n\n    $ zef --deps-only install .\n\n[`rakubrew`](https://rakubrew.org/), precisa que seja executado tabém:\n\n    $ rakubrew rehash\n\npara atualizar os links de compatibilidade de executáveis.\n\nAlém das dependências de Raku, precisa do `graphviz` instalado. No Debian\ninstale usando:\n\n    $ sudo apt-get install graphviz\n\nPara suporte ao destaque de código, precisa também do [nodejs](https://nodejs.org) instalado e disponível no path.\nE também das suas depedências, incluindo `g++`.\n\nPara gerar as páginas web da documentacão com destaque de código, executa:\n\n    $ make html\n\nPara gerá-las sem destaque de código, use:\n\n    $ make html-nohighlight\n\nApós estarem criadas, pode ver localmente no teu computador com o incluso `app.pl`, executando:\n\n    $ make run\n\nFeito o anterior, a documentacão estará dsiponível em [http://localhost:3000](http://localhost:3000).\n\n`app.pl` depende do [Mojolicious](https://metacpan.org/pod/Mojolicious)\ninstalado. Tamabém é necesário o [nodejs](https://nodejs.org) para que funcione o destaque de código.\nE também outros módulos Perl, instalados executando:\n\n    $ cpanm --installdeps .\n\n---------\n\n## Precisamos de Ajuda!\n\nRaku não é uma linguagem de programação pequena, e documentá-la requer bastante esforço. Qualquer ajuda é bem-vinda.\n\nAlgumas maneira de nos ajudar:\n\n  * Adicionando documentacão de classes, roles, métodos e operadores.\n  * Adicionando exemplos de uso à documentacão existente.\n  * Revisando e corrigindo.\n  * Abrindo issues no GitHub se acha que falta documentacão.\n  * Fazendo `git grep TODO` neste repositório, e substituindo os items TODO por documentação.\n\n[Esta página](https://github.com/Raku/doc/issues) tem uma lista de issues atuais e partes da documentação que faltam.\n[CONTRIBUTING](CONTRIBUTING.md) explica brevemente como começar a contribuir.\n\n--------\n## Algumas questões:\n\n**P:** Por que não estão incluindo a documentação no código fonte do CORE?<br>\n**R:** Várias razões:\n\n  1. Esta documentação pretende ser universal com respeito a uma versão dada de uma especificacão, e não necesariamente estar\n  ligada a uma implementação específica de Raku.\n\n  2. O tratamento das implementações ao Pod6 é inconsistente; assim se evita impactos potenciais durante a execução.\n\n  3. Um repo separado na conta do Raku de GitHub convida mais contribuidores e editores a participar.\n\n**P:** Eu deveria incluir os métodos das superclases ou dos roles?<br>\n**A:** Não. A versão HTML já os inclui, e o `p6doc` também.\n\n--------\n\n## Objetivo\n\n> Quero que p6doc e docs.perl6.org se tornem o recurso número 1 para consultar quando quiser conhecer qualquer\n> característica do Raku, seja a linguagem ou seus tipos e rotinas. Quero que seja útil para todo programador de Raku.\n>\n>    -- moritz\n\n--------\n\n# ENV VARS\n\n- `RAKU_DOC_TEST_VERBOSE` como `true` para mostrar mensajens durante a execução do conjunto de testes. Prático para depurar testes\nque falham.\n- `RAKU_DOC_TEST_FUDGE` muda testes `skip-test` para TODO no teste `xt/examples-compilation.t`.\n\n# LICENÇA\n\nO código neste repositório está disponível sob a Artistic License 2.0 como publicado pela Perl Foundation. O arquivo\n[LICENSE](LICENSE) contém o texto completo.\n\nEste repositório também contém código de terceiros que podem ter outra licença, em cujo caso indicam o copyright e licença no\ntopo do próprio arquivo. Atualmente incluem:\n\n* Exemplos do StackOverflow [Licença MIT](http://creativecommons.org/licenses/MIT); ([ref #1](http://stackoverflow.com/a/43669837/215487) for [1f7cc4e](https://github.com/Raku/doc/commit/1f7cc4efa0da38b5a9bf544c9b13cc335f87f7f6))\n* Table sorter plugin from https://github.com/christianbach/tablesorter ;\n  [Licença MIT](http://creativecommons.org/licenses/MIT)\n"
  },
  {
    "path": "resources/i18n/zh/README.zh.md",
    "content": "# Raku 官方文档\n\n[![Build Status](https://travis-ci.org/Raku/doc.svg?branch=master)](https://travis-ci.org/Raku/doc) [![artistic](https://img.shields.io/badge/license-Artistic%202.0-blue.svg?style=flat)](https://opensource.org/licenses/Artistic-2.0) [![Run Status](https://api.shippable.com/projects/591e99923f2f790700098a30/badge?branch=master)](https://app.shippable.com/github/Raku/doc) [![CircleCI](https://circleci.com/gh/Raku/doc.svg?style=shield)](https://circleci.com/gh/Raku/doc/tree/master)\n\n本文档的 HTML 版本位于 [https://docs.raku.org/](https://docs.raku.org/) 和\n[`rakudocs.github.io`](https://rakudocs.github.io) （后者更新更频繁）。\n目前推荐使用这种方式来访问文档。\n\n## Docker 镜像\n\n官方文档的 Docker 镜像地址为 [`jjmerelo/perl6-doc`](https://hub.docker.com/r/jjmerelo/perl6-doc) 。\n这个镜像包含了文档的一份副本，对应的端口为 3000。你可以这样运行这个镜像：\n\n    docker run --rm -it -p 3000:3000 jjmerelo/perl6-doc\n\n或者，如果你想发布到其他端口：\n\n    docker run --rm -it -p 31415:3000 jjmerelo/perl6-doc\n\n现在，可以通过浏览器访问 http://localhost:3000 （或者 31415 端口，视情况而定）。\n\n## 其他语言版本的 README\n\n* [英文版 README](../../../README.md)\n* [荷兰文版 README](../nl/README.nl.md)\n* [法文版 README](../fr/README.fr.md)\n* [德文版 README](../de/README.de.md)\n* [意大利文版 README](../it/README.it.md)\n* [日文版 README](../jp/README.jp.md)\n* [葡萄牙文版 README](../pt/README.pt.md)\n* [西班牙文版 README](../es/README.es.md)\n\n## 安装 rakudoc\n\n请查看 https://github.com/Raku/rakudoc 来了解在命令行查看文档的工具。\n\n## 构建 HTML 文档\n\n注意：如果你只是想要一份 HTML 站点的副本，而不想自己处理构建，你可以从这里克隆：[`https://github.com/rakudocs/rakudocs.github.io`](https://github.com/rakudocs/rakudocs.github.io)。\n\n本文档可以渲染为静态 HTML 页面和/或在本地网站服务。此过程涉及创建预编译文档的缓存，以便加快之后的生成速度。\n\n你需要安装以下这些才能生成文档：\n\n* perl 5.20 或更新。\n* node 10 或更新。\n* graphviz。\n* [Documentable](https://github.com/Raku/Documentable)。\n\n在 Ubuntu 中，请按照以下说明进行安装：\n\n    sudo apt install perl graphviz # 默认情况下，18.04 中未安装 perl\n    curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -\n    sudo apt-get install -y nodejs\n    cpanm --installdeps .\n    zef install --deps-only . ; # 在这个检出内运行\n\n> 你可以用任何方式安装 perl 和 node，包括使用版本管理器，只要它们可以从命令行运行即可。\n\n这应该安装了所有依赖，现在你可以克隆本存储库并开始构建：\n\n    git clone https://github.com/Raku/doc.git # 克隆存储库\n    cd doc # 进入克隆的存储库\n    # 生成 CSS 和 JS，安装高亮模块并构建缓存和页面\n    make html\n\n只有在第一次构建缓存时才需要这样做。当源代码发生变化（由你自己完成或从本存储库中拉取）后，运行\n\n    make update-html\n\n将只会重新生成有变化的页面。\n\n文档将在 `html` 子目录中生成。你可以使用任何静态 Web 服务器指向该目录，也可以使用基于 Mojolicious 的开发服务器，运行\n\n    make run\n\n这会在 3000 端口服务文档。\n\n## 生成 EPUB 和/或“单页 HTML”文档\n\n本文档也可以生成 EPUB 格式以及“单页 HTML”格式。请注意，有些功能（如类型部分中继承的方法和类型图，以及代码示例的语法高亮）在这些格式中（暂时）不可用。\n\n你需要安装以下这些：\n\n* Pod::To::BigPage 0.5.2 或更新。\n* Pandoc（仅 EPUB）。\n\n在 Ubuntu 或 Debian 上，你可以按照以下说明安装：\n\n    zef install \"Pod::To::BigPage:ver<0.5.2+>\"\n    sudo apt install pandoc     # 如果你想生成 EPUB\n\n现在你已经安装了依赖关系，克隆这个仓库，并生成 EPUB 或“单页 HTML”文档。\n\n    git clone https://github.com/Raku/doc.git # 克隆存储库\n    cd doc      # 进入克隆的存储库\n    make epub           # 生成 EPUB 格式，\n                        # 对于“单页 HTML”格式，使用 `make bigpage`\n\n生成的 EPUB 位于存储库根目录下，名为 `raku.epub`，生成的“单页 HTML”在 `html/raku.html`。\n\n## nginx 配置\n\n生成的文档的最新版本仅包含静态 HTML 页面。所有页面都以 `.html` 结尾；不过大多数内部链接不使用该后缀。大多数 Web 服务器（例如，服务 GitHub 页面的服务器）都会自动为你添加它。裸服务器不会。你需要向配置中添加这些以使其工作：\n\n```\n    location / {\n        try_files $uri $uri/ $uri.html /404.html;\n    }\n```\n\n这将为你重定向 URL。可能需要在其他服务器应用中做出同样的配置。\n\n---------\n\n## 我们需要帮助！\n\nRaku 不是小语言，为它做文档并维护这些文档需要付出很大的努力。我们会感激任何形式的帮助。\n\n以下是一些帮助我们的方式：\n\n * 添加缺少的 class，role，method 或 operator 的文档。\n * 为现有文档添加使用示例。\n * 校对与更正文档。\n * 通过 GitHub 的 issue 系统报告缺少的文档。\n * 在本存储库下执行 `git grep TODO`，并用实际文档替换 TODO。\n\n[Issues 页面](https://github.com/Raku/doc/issues)列出了当前的 issue 和已知缺失的文档。[CONTRIBUTING 文档](../../../CONTRIBUTING.md)简要描述了如何开始贡献文档。\n\n--------\n\n## 注记：\n\n**Q:** 为什么不把文档内嵌到 Rakudo 的核心开发文件中？<br />\n**A:** 有以下几点：\n\n  1. 这份文档与 Raku 的特定版本的语言标准相关联，\n     而不是跟某个 Raku 的具体实现相绑定。\n  2. 处理内嵌的 Pod 的功能还不太稳定，使用单独的文档仓库\n     可以避免潜在的运行时错误。\n  3. 一个 Raku GitHub 账号下的单独的仓库能吸引更多\n     潜在的贡献者。\n\n**Q:** 编写文档时我应该包括父类和 role 的方法吗？<br />\n**A:** 不用。HTML 版本的文档自动包括了这些方法。\n\n--------\n\n## 愿景\n\n> I want p6doc and docs.raku.org to become the No. 1 resource to consult\n> when you want to know something about a Raku feature, be it from the\n> language, or built-in types and routines. I want it to be useful to every\n> Raku programmer.\n>\n>    -- moritz\n\n--------\n\n# 环境变量\n\n- 设置 `RAKU_DOC_TEST_VERBOSE` 为真值以在运行测试时输出详细信息，这在调试不通过的测试时很有帮助。\n- 设置 `RAKU_DOC_TEST_FUDGE` 将在 `xt/examples-compilation.t` 测试中把标记为 `skip-test` 的代码实例当做 TODO 处理。\n\n# 更新\n\n现在暂时是手动更新。这大概需要改进。\n\n# 许可证\n\n本仓库代码使用 Perl 基金会发布的 Artistic License 2.0 协议，你可以在 [LICENSE](../../../LICENSE) 文件中查看完整的内容。\n\n本仓库可能包括使用其他协议的第三方代码，这些文件在它们的首部注明了版权和协议。目前包括：\n\n* 来自 Stack Overflow 的示例； [MIT License](http://creativecommons.org/licenses/MIT) ([ref #1](http://stackoverflow.com/a/43669837/215487) for [1f7cc4e](https://github.com/Raku/doc/commit/1f7cc4efa0da38b5a9bf544c9b13cc335f87f7f6))\n* 来自 https://github.com/christianbach/tablesorter 的表格排序插件；\n  [MIT License](http://creativecommons.org/licenses/MIT)\n"
  },
  {
    "path": "t/00-meta.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\nBEGIN plan :skip-all<Test applicable to git checkout only> unless '.git'.IO.e;\n\nuse Test::META;\nmeta-ok;\n\ndone-testing;\n"
  },
  {
    "path": "t/02-pod-valid.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\nBEGIN plan :skip-all<Test applicable to git checkout only> unless '.git'.IO.e;\n\nuse RakuDoc::Test::Files;\n\n=begin overview\n\nEnsure any text that isn't a code example is valid C<Pod6>.\n\n=end overview\n\nmy @files = RakuDoc::Test::Files.pods;\n\nif @files {\n    plan +@files;\n} else {\n    plan :skip-all<No rakudoc files specified>\n}\n\nmy %data;\nmy $lock = Lock::Async.new;\n\nmy $verbose = %*ENV<RAKU_DOC_TEST_VERBOSE>;\n\n@files.race.map: -> $file {\n    react {\n        my $proc = Proc::Async.new([$*EXECUTABLE-NAME, '-c', '--doc', $file]);\n\n        whenever $proc.stdout.lines {\n            ; #discard\n        }\n\n        whenever $proc.stderr.lines {\n            # An error occurred\n            $verbose and diag(\"$file error: $_\");\n            $lock.protect: {\n                %data{$file} = False;\n            };\n        }\n\n        whenever $proc.start {\n            $verbose and diag(\"processing $file\");\n            $lock.protect: {\n                if %data{$file}:!exists {\n                    %data{$file} = !.exitcode;  # 0 = True, anything else False\n                }\n            };\n            done;\n        }\n    }\n}\n\nfor %data.keys.sort -> $file {\n    ok %data{$file}, \"$file has clean Pod6\";\n}\n"
  },
  {
    "path": "t/03-tests-valid.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\nBEGIN plan :skip-all<Test applicable to git checkout only> unless '.git'.IO.e;\n\nuse RakuDoc::Test::Files;\n\n=begin overview\n\nEnsure any test file, including author tests, have clean syntax and POD\n\n=end overview\n\nmy @files = RakuDoc::Test::Files.tests;\n\nif @files {\n    plan +@files;\n} else {\n    plan :skip-all<No test files specified>\n}\n\nmy %data;\nmy $lock = Lock::Async.new;\n\nmy $verbose = %*ENV<RAKU_DOC_TEST_VERBOSE> // False;\n\n@files.race.map: -> $file {\n    react {\n        my $proc = Proc::Async.new([$*EXECUTABLE-NAME, '-c', $file]);\n\n        whenever $proc.stdout.lines {\n            ; #discard\n        }\n\n        whenever $proc.stderr.lines {\n            # An error occurred\n            $verbose and diag(\"$file error: $_\");\n            $lock.protect: {\n                %data{$file} = False;\n            };\n        }\n\n        whenever $proc.start {\n            $lock.protect: {\n                if %data{$file}:!exists {\n                    %data{$file} = !.exitcode;  # 0 = True, anything else False\n                }\n            };\n            done;\n        }\n    }\n}\n\nfor %data.keys.sort -> $file {\n    ok %data{$file}, \"$file rakudoc and syntax check out\";\n}\n"
  },
  {
    "path": "t/04-trailing-whitespace.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\nuse RakuDoc::Test::Files;\n\n=begin overview\n\nMake sure that no line includes trailing whitespace.\n\n=end overview\n\nmy @files = RakuDoc::Test::Files.files.grep({$_ ne 'LICENSE'});\n\nplan +@files;\n\nfor @files -> $file {\n    my $ok = True;\n    my $row = 0;\n    for $file.IO.lines -> $line {\n        ++$row;\n        if $line ~~ / \\s $/ {\n           $ok = False; last;\n        }\n    }\n    my $error = $file;\n    $error ~= \" (line $row)\" if !$ok;\n    ok $ok, \"$error: Must not have any trailing whitespace.\";\n}\n"
  },
  {
    "path": "t/05-tabs.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\nBEGIN plan :skip-all<Test applicable to git checkout only> unless '.git'.IO.e;\nuse RakuDoc::Test::Files;\n\nmy @files = RakuDoc::Test::Files.files\\\n    .grep({$_ ne 'LICENSE'|'Makefile'})\\\n    .grep({! $_.contains('custom-theme')});\n\nplan +@files;\n\nfor @files -> $file {\n    my @lines;\n    my $line-no = 1;\n    for $file.IO.lines -> $line {\n        @lines.push($line-no) if $line.contains(\"\\t\");\n        $line-no++;\n    }\n    if @lines {\n        flunk \"$file has tabs on lines: {@lines}\";\n    } else {\n        pass \"$file has no tabs\";\n    }\n}\n"
  },
  {
    "path": "t/06-double-dots.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\n\nuse Pod::Cache;\nuse RakuDoc::Test::Files;\n\n=begin overview\n\nAvoid using C<..> - usually a typo for C<.> or C<...>\n\n=end overview\n\nmy @files = RakuDoc::Test::Files.documents;\n\nif @files {\n    plan +@files;\n} else {\n    plan :skip-all<No document files specified>\n}\n\nsub test-it(Str $output, Str $file) {\n    my $ok = True;\n\n    for $output.lines -> $line {\n        if $line ~~ / <alpha> '..' (<space> | $) / {\n            diag \"Failure on line `$line`\";\n            $ok = False;\n        }\n    }\n    my $error = $file;\n    ok $ok, \"$error: file contains ..\";\n}\n\nfor @files -> $file {\n    test-it(Pod::Cache.cache-file($file).IO.slurp, $file)\n}\n"
  },
  {
    "path": "t/07-duplicates.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\n\nuse Pod::Cache;\nuse RakuDoc::Test::Files;\n\n=begin overview\n\nCheck for duplicate words in documentation; ignore case.\n\nSave the last word of each line, comparing it to the next line as well.\n\nAllow a few well known duplicates, like 'long long'\n\n=end overview\n\nmy $safe-dupes = Set.new(<method default that yada,>); # Allow these dupes\n\nmy @files = RakuDoc::Test::Files.files.grep(* ne 'LICENSE').grep(* ne 'CREDITS');\n\nplan +@files;\n\nsub test-it(Str $output, Str $file) {\n    my $ok = True;\n\n    my @dupes;\n    my $last-word = '';\n    my $line-num = 0;\n    for $output.lines -> $line is copy {\n        $line-num++;\n        if $line.starts-with: ' ' or $line eq '' {\n            # could be code, table, heading; don't check for dupes\n            $last-word = '';\n            next;\n        }\n        next unless $line.chars;\n\n        my @words = flat $last-word, $line.words;\n        @words .= grep(*.chars);\n\n        # End of a sentence resets word check, as do short lines (typically headings)\n        if $line.ends-with('.') or @words.elems <= 2 {\n            $last-word = '';\n        } elsif @words {\n            $last-word = @words[*-1];\n        }\n\n        my @line-dupes = @words.rotor(2=> -1).grep({$_[0] eq $_[1]}).map({$_[0]});\n        for @line-dupes -> $dupe {\n            # explicitly allowed duplicates\n            next if $safe-dupes ∋ ~$dupe[0];\n            # Single characters that are probably fine\n            next if $dupe ~~ /^ [<:Sm>|<:CS>] $/;\n            # Ignore numbers\n            next if $dupe ~~ /^ \\d+ $/;\n            @dupes.push: \"“\" ~ $dupe[0] ~ \"” on line $line-num\";\n        }\n    }\n    my $message = \"$file has duplicate words\";\n    is @dupes.join(\"\\n\"), '', $message;\n}\n\nfor @files -> $file {\n    test-it(Pod::Cache.cache-file($file).IO.slurp, $file)\n}\n"
  },
  {
    "path": "t/08-headings.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\nBEGIN plan :skip-all<Test applicable to git checkout only> unless '.git'.IO.e;\nuse RakuDoc::Test::Files;\n\n=begin overview\n\nC<=TITLE> and C<=SUBTITLE> headings must follow certain capitilization rules:\n\nIf the title is for something in the object model, we allow the lower case keyword and the\ncorrectly cased type, e.g. C<class Real>.\n\nIf the title contains one of the words in the skiplist, or something that matches a\nRaku type, ignore that word.\n\nFor the remaining words, the first character should be capitalized, and the remaining characters lowercase.\n\n=end overview\n\nmy @files = RakuDoc::Test::Files.documents;\n\nif @files {\n    plan +@files;\n} else {\n    plan :skip-all<No document files specified>\n}\n\n# these words don't have to be capitalized\n# my $stopwords = /^()$/;\n\nfor @files -> $file {\n    my @lines;\n    my @examples;\n    my $line-no = 0;\n    for $file.IO.lines -> $line {\n        $line-no++;\n        if $line.starts-with(\"=TITLE \") or $line.starts-with(\"=SUBTITLE \") {\n            # ignore first word like \"=TITLE\"\n            my $title = $line.substr($line.index(' ') + 1);\n            # ignore \"class X::TypeCheck\" and the like\n            $title ~~ s:g/^ ( class | role | module | enum | package ) \\s+ \\S+//;\n            # proper names, macros, acronyms, and other exceptions\n            $title ~~ s:g/ <?wb> (\n                I\n                | Raku | RakuAST | Rakudo | RakuDoc | Perl 6 | Pod6 | P6 | C3 | NQP\n                | AST | EVAL | PRE | POST | CLI | MOP\n                | TITLE | SUBTITLE | \"MONKEY-TYPING\"\n                | API | TCP | UDP | FAQ\n                | JavaScript | Node | Haskell | Python | Ruby | C | Node.js | Perl\n                | \"Input/Output\" | \"I/O\"\n                | \"Alice in Wonderland\"\n                | \"Virtual Machine\"\n                | \"Binary Large OBject\"\n                | Boolean | Unicode | ASCII\n                | \"Normal Form \" ( \"C\" | \"D\" | \"KC\" | \"KD\" )\n                | POSIX | QNX | Windows | Cygwin | Win32\n                # class names\n                | CompUnits\n                | Whatever\n                | Scheduler\n                | NaN\n                | ( <:Lu><:L>+ \"::\" )+ <:Lu><:L>+\n                # these seem fishy?\n                | Socket\n            ) <?wb> //;\n            $title ~~ s:g/ <?wb> <[ C ]> \\< .*? \\> //;\n            # ignore known classes like \"Real\" and \"Date\" which are capitalized\n            my @words = $title ~~ m:g/ <?wb> ( <:Lu> \\S+ ) /;\n            for @words -> $word {\n                # if it exists, skip it\n                try {\n                    ::($word);\n                    $title ~~ s:g/ << $word >> //;\n                }\n            }\n            # sentence case: all lowercase, titlecase for first\n            # character except for cases where the first word is a\n            # uncapitalized name of a program\n            if $title !~~ $title.lc.tc and $title !~~ /^ rakudoc / {\n                @lines.push($line-no);\n                @examples.push($line);\n            }\n        }\n    }\n    if @lines {\n        flunk \"$file has inconsistent capitalised headings on lines: {@lines}\\n\"\n        ~ @examples.join(\"\\n\");\n    } else {\n        pass \"$file capitalises headings consistently \";\n    }\n}\n"
  },
  {
    "path": "t/09-final-newline.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\nuse RakuDoc::Test::Files;\n\n=begin overview\n\nMake sure that text files end in a newline\n\n=end overview\n\nmy @files = RakuDoc::Test::Files.files\\\n    .grep({$_ ne 'LICENSE'})\\\n    .grep({! $_.contains: 'custom-theme'})\\\n    .grep({! $_.contains: 'util/trigger-rebuild.txt'});\n\nif @files {\n    plan +@files;\n} else {\n    plan :skip-all<No relevant files specified>;\n}\n\nfor @files -> $file {\n    ok $file.IO.slurp.substr(*-1) eq \"\\n\", \"$file must end in a newline\";\n}\n"
  },
  {
    "path": "t/10-vim-mode.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\nuse RakuDoc::Test::Files;\n\n=begin overview\n\nMake sure no files include the vim mode line.\n\nThis was historically useful but is now considered harmful.\n\nhttps://github.com/Raku/doc/issues/3058\n\n=end overview\n\nmy @files = RakuDoc::Test::Files.files;\n\nif @files {\n    plan +@files;\n} else {\n    plan :skip-all<No relevant files specified>;\n}\n\nfor @files -> $file {\n    nok $file.IO.slurp ~~ /^^ '# vim: '/, \"$file must not contain vim mode line\";\n}\n"
  },
  {
    "path": "t/11-return-type.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\nuse RakuDoc::Test::Files;\n\n# Every .rakudoc file in the Type directory.\nmy @files = RakuDoc::Test::Files.pods.grep(* ~~ /Type | Language/);\n\nif @files {\n    plan +@files;\n} else {\n    plan :skip-all<No rakudoc files specified>\n}\n\nfor @files -> $file {\n    my @lines;\n    my Int $line-no = 1;\n    for $file.IO.lines -> $line {\n        if so $line ~~ /(multi|method|sub) .+? ')' \\s+? 'returns' \\s+? (<alnum>|':')+? $/ {\n            @lines.push($line-no);\n        }\n        $line-no++;\n    }\n    if @lines {\n        flunk \"$file uses 'returns' at lines: {@lines}; should be -->\";\n    } else {\n        pass \"$file return types are ok\";\n    }\n}\n"
  },
  {
    "path": "t/12-perl-nbsp.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\nuse RakuDoc::Test::Files;\n\n=begin overview\n\nEnsure any text that mentions Perl uses a no-break space after it.\n\n=end overview\n\nmy @files = RakuDoc::Test::Files.documents;\n\nif @files {\n    plan +@files;\n} else {\n    plan :skip-all<No document files specified>\n}\n\nfor @files.sort -> $file {\n    my $err-count = 0;\n    my $content = $file.IO.slurp;\n    for $content ~~ m:g/ <!after 'implementing '> 'Perl' $<space>=(\\s+) \\d / -> $match {\n        my $spaces = ~$match<space>;\n        if $spaces.chars != 1 || $spaces.uniname ne \"NO-BREAK SPACE\" {\n            $err-count++;\n        }\n    }\n    my $error = $file;\n    if $err-count {\n        $error ~= \" ($err-count instance{$err-count==1 ?? '' !! 's'})\";\n    }\n    ok !$err-count, \"$error: Perl followed by a version should have a single non-breaking space.\" ;\n}\n"
  },
  {
    "path": "t/13-braces.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\n\nuse Pod::Cache;\nuse RakuDoc::Test::Files;\n\n=begin overview\n\nEnforce B<curly braces> and B<square> or B<angle> B<brackets>.\n\n=end overview\n\nmy @files = RakuDoc::Test::Files.documents.grep(* ne \"doc/Language/brackets.rakudoc\");\n\nif @files {\n    plan +@files;\n} else {\n    plan :skip-all<No document files specified>\n}\n\nsub test-it(Str $output, Str $file) {\n    my $ok = True;\n\n    my $msg;\n\n    my $line = $output.subst(/\\s+/, ' ', :g)                         # canonicalize whitespace\n                      .subst('Opening bracket is required for', ''); # rakudo/rakudo#2672\n\n    if $line ~~ /:i <!after curly> ' ' 'braces' >> / {\n        $msg ~= \"Found 'braces' without 'curly'. \";\n        $ok = False;\n    }\n\n    if $line ~~ /:i <!after square><!after angle><!after lenticular> ' ' ('bracket' [s|ed]?) >> / {\n        $msg ~= \"Found '{~$0}' without 'square' or 'angle'.\";\n        $ok = False;\n    }\n\n    ok $ok, $file ~ ($msg ?? \": $msg\" !! \"\");\n}\n\nfor @files -> $file {\n    test-it(Pod::Cache.cache-file($file).IO.slurp, $file);\n}\n"
  },
  {
    "path": "t/14-routine-definitions.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\n\nuse Pod::Convenience;\nuse RakuDoc::Test::Files;\n\n=begin overview\n\nLook for Pod sections about method, sub or routine and check that the\ndefinitions in the first code blocks match the routine form specified in\nthe section heading.\n\nref #3350\n\n=end overview\n\nmy @files = RakuDoc::Test::Files.pods;\n\nif @files {\n    plan +@files;\n} else {\n    plan :skip-all<No rakudoc files specified>\n}\n\n\nfor @files -> $file {\n    subtest $file => {\n        my @headings =\n            extract-pod($file.IO).contents.grep: Pod::Heading;\n\n        plan +@headings.grep({ contents($_) ~~\n            /^ \\s* ( routine || sub || method ) \\s+ <ident>+ \\s* $/ });\n\n        test-routine-definitions($file)\n    }\n}\n\nsub test-routine-definitions($file) {\n    my @chunks = extract-pod($file.IO).contents;\n    my $routine-form;\n    my Str $header;\n    my Str $code;\n    while @chunks {\n        my $chunk = @chunks.shift;\n\n        if $chunk ~~ Pod::Heading {\n            # if we encounter a new section while we were parsing the\n            # preceding one, check its definitions\n            if $header && $routine-form {\n              test-definitions($file, $header, $routine-form, $code);\n            }\n\n            # proceed with the new section\n            $header = contents($chunk);\n            if $header ~~ /^ \\s* ( routine || sub || method ) \\s+\n                           <ident>+ \\s* $/ {\n                # it is a routine/sub/method section\n                # we will start to parse it for definitions code blocks\n                $routine-form = $0;\n            } else {\n                # it is not\n                $routine-form = Any;\n            }\n        }\n\n        # found a code block in a routine section : accumulate its code\n        if $chunk ~~ Pod::Block::Code && $routine-form {\n            $code ~= contents($chunk);\n        }\n\n        # found a non code block in a routine section after seeing some\n        # code : assume we have collected all the code blocks of the\n        # section containing the routine definitions and proceed to\n        # check these definitions\n        if $chunk !~~ Pod::Block::Code && $code && $routine-form {\n            test-definitions($file, $header, $routine-form, $code);\n        }\n    }\n\n    # is there a last section to check ?\n    if $header && $routine-form {\n        test-definitions($file, $header, $routine-form, $code);\n    }\n}\n\nsub test-definitions($file, $header, $routine-form is rw, $code is rw) {\n    # if there is no code, everything is fine\n    if ! $code {\n        ok 1, \" section «\" ~ $header ~ \"»\";\n        $routine-form = Any;\n        return;\n    }\n\n    # otherwise check definitions in the code\n    my $error-reason;\n\n    my $has_sub = so $code ~~ /^^ \\h*\n                                [  (multi \\h+)? sub \\h+ <ident>+\n                                || multi \\h+ <!before method> <ident>+\n                                ]\n                              /;\n    my $has_method =\n        so $code ~~ /^^ \\h* (multi \\h+)? << method >>/;\n\n    if $routine-form eq 'sub' && $has_method {\n        $error-reason = 'has method definition';\n    }\n\n    if $routine-form eq 'method' && $has_sub {\n        $error-reason = 'has sub definition';\n    }\n\n    if $routine-form eq 'routine' && !($has_sub || $has_method) {\n        $error-reason = \"lacks both sub and method definition\";\n    }\n\n    if $error-reason {\n        flunk $file ~ \" section «\" ~ $header ~\n            \"» but code block starting with «\" ~\n            starts-with($code) ~ \"» $error-reason\";\n    } else {\n        ok 1, \" section «\" ~ $header ~ \"»\";\n    }\n\n    # we're done with this section\n    $routine-form = Any;\n    $code = '';\n}\n\nsub contents($arg) {\n    $arg.contents.map({walk $_}).join;\n}\n\nsub walk($arg) {\n    given $arg {\n        when Pod::FormattingCode { walk $arg.contents }\n        when Pod::Block::Para    { walk $arg.contents }\n        when Str   { $arg }\n        when Array { $arg.map({walk $_}).join }\n    }\n}\n\nsub starts-with (Str $str) {\n    $str.substr(0,20).trim\n}\n"
  },
  {
    "path": "t/15-word-variants.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\nuse RakuDoc::Test::Files;\n\n=begin overview\n\nMake sure certain words are normalized by checking regular expressions.\n\n=end overview\n\nmy @files = RakuDoc::Test::Files.pods;\n\nif @files {\n    plan +@files;\n} else {\n    plan :skip-all<No rakudoc files specified>\n}\n\n# Keys are the preferred variant, values are regex to complain about\nmy %variants = %(\n    # no lowercase 'boolean', unless it is followed by some selected\n    # characters as it might be included in a code snippet,\n    # see for example doc/Language/js-nutshell.rakudoc\n    Boolean    => rx/ << boolean <!before \\s* <[ \\= \\< \\> \\{ \\} ]> > /,\n    \"call site\" => rx/ <<'call' '-'? 'site'>>/,\n    \"environment variable\" => rx:i/ << env(ironmental)? [\\s+|\\-] variable/,\n    filehandle => rx:i/ << file [\\s+|\\-] handle /,\n    filesystem => rx:i/ << file [\\s+|\\-] system /,\n    left-hand => rx:i/ << left [\\s+] hand /,\n    lookahead  => rx:i/ << look \\- ahead /,\n    lookbehind => rx:i/ << look [\\s+|\\-] behind /,\n    lowercase  => rx:i/ << lower [\\s+|\\-] case /,\n    # Allow the one url with meta-object\n    metaobject  => rx:i/ << meta [\\s+|\\-] object <!before '-protocol' >/,\n    # The one meta we want a dash on\n    \"meta-info\"  => rx:i/ << meta [\\s*] info /,\n    # \"method\" is tricky with headings.\n    metamethod  => rx:i/ <<<!after [method|| \\$ || \\- || \\\"] \\s*> << meta [\\s+|\\-] method /,\n    NYI        => rx:i/ << niy /,\n    parameterization => rx:i/ << parametrization >> /,\n    precompil => rx:i/ << pre [\\s+|\\-] compil /,\n    right-hand => rx:i/ << right [\\s+] hand /,\n    runtime    => rx:i/ << run [\\s+|\\-] time /,\n    semicolon => rx:i/ << semi [\\s+|\\-] colon /,\n    shorthand  => rx:i/ << short [\\s+|\\-] hand /,\n    sigiled => rx:i/ << sigilled /,\n    smartmatch => rx:i/ << smart  [\\s+|\\-] match /,\n    subdirectories => rx:i/ << sub [\\s+|\\-] directories /,\n    subdirectory => rx:i/ << sub [\\s+|\\-] directory /,\n    substring  => rx:i/ << sub \\- string /,\n    tiebreak => rx:i/ << tie [\\s+|\\-] break /,\n    timezone   => rx:i/ << time [\\s+|\\-] zone /,\n    titlecase  => rx:i/ << title [\\s+|\\-] case /,\n    uppercase  => rx:i/ << upper [\\s+|\\-] case /,\n    zero-width => rx:i/ << zero \\s+ width<!before ' joiner'><!before ' no-break space'> /,\n);\n\nfor <character class data model operator package program role synta type> -> $meta {\n    %variants{\"meta$meta\"} = rx:i/ << meta [\\s+|\\-] $meta/;\n}\n\nmy %result;\n\nfor @files.race -> $file {\n    my $ok = True;\n    my $row = 0;\n    my @bad;\n    my $content =  $file.IO.slurp.lines.join(\" \");\n    for %variants.kv -> $word, $rx {\n        if $content ~~ $rx {\n            $ok = False;\n            @bad.push: \"«$/» found. We prefer ｢$word｣\";\n        }\n    }\n    %result{$file} = [$ok, @bad];\n}\n\nfor %result.keys.sort -> $file {\n    my $result = $file;\n    my $ok = %result{$file}[0];\n    my @bad = %result{$file}[1];\n    if !$ok {\n       $result ~= \" {@bad.join: ', '}: Certain words should be normalized.\";\n    }\n    ok $ok, $result;\n}\n"
  },
  {
    "path": "t/16-an-grammar.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\n\nuse Pod::Cache;\nuse RakuDoc::Test::Files;\n\n=begin overview\n\nAppropriately use \"a\" and \"an\".\n\n=end overview\n\nmy @files = RakuDoc::Test::Files.files.grep(* ne 'LICENSE' | 'CREDITS' | 'xt/an-grammar.rakutest');\n\nplan +@files;\n\nsub test-it(Str $output, Str $file) {\n    if $file.contains('/i18n/') {\n        skip(\"$file is not english\");\n        next;\n    }\n    subtest $file => {\n        # Look at every two words together...\n        for $output.words.rotor(2 => -1) -> ($an, $other) {\n            # ... if the first one is \"a\" or \"an\"\n            next unless $an.lc eq 'an'|'a';\n\n            # This is probably code\n            next if $other eq '=>' | '=' | '($a)' | '$.a' | 'l>' | 'l)}';\n            next if $other.starts-with('X<hash' | 'e)');\n\n            # A is probably a variable in this context\n            next if $other.lc eq 'is' | 'and' | 'or' | 'into' | 'if' | 'as' | 'o';\n\n            # Too much trouble to reword example/table\n            next if $other eq 'Extract' | 'expects';\n\n            # Assume we should be using 'a'\n            my $wanted = \"a\";\n\n            # In all cases, ignore a trailing . that is part of the word\n            my $word = $other.ends-with('.') ?? $other.chop !! $other;\n\n            # Process items where we care about the punctuation\n            if $word.starts-with('X::' | '@' | '&' ) {\n                $wanted = \"an\";\n            } elsif $word eq '=' | '&' {\n                $wanted = \"an\";\n            }\n\n            # Strip out any remaining punctuation to look at alpha/digits\n            $word = $word.subst(:g, /<-alpha -digit>+/, \" \").words[0] // '';\n\n            # Probably code example\n            next if $word eq 'A' and $an eq 'A';\n\n            # Still have to check?\n            if $wanted eq \"a\" {\n                # Words that are empty or Nil at this point should be failed\n                if $word.DEFINITE and $word ne \"\" {\n                    # Allow all vowels\n                    if $word.lc.starts-with(any(<a e i o u>)) {\n                        $wanted = \"an\";\n                        # Except for words that start with a consonant sound\n                        if $word    eq 'US' or\n                           $word.lc eq\n                            'once' | 'one' | 'u' | 'uc' | 'ucfirst' | 'udp' | 'ui' | 'unary' | 'uni' |\n                            'unicode' | 'uniform' | 'uniprops' | 'unique' | 'unit' | 'unitcheck' |\n                            'universally'| 'unix' | 'uri' | 'url' | 'usable' | 'usage' | 'use' |\n                            'useful' | 'used' | 'user' | 'usual' | 'usually' | 'utc' | 'utf8' | 'utility'\n                            {\n                            $wanted = \"a\";\n                        }\n                    }\n\n                    # Allow some single characters that start with vowel sounds\n                    if $word.lc eq any <m l n x> {\n                        $wanted = \"an\";\n\n                        # Special case for \\n, which is either \"newline\" or \"backslash n\"\n                        if $other.lc eq '\\n' {\n                            $wanted = \"a\";\n                        }\n                    }\n\n                    # Allow some words that have a consonant but use a vowel sound\n                    if $word.lc eq any(<mp3 hour lc lcfirst nfc nfd nfkc nfkd nqp html rvalue lvalue>) {\n                        $wanted = \"an\";\n                    }\n                }\n            }\n            is $an.lc, $wanted, \"$an $other\";\n        }\n    }\n}\n\nfor @files -> $file {\n    test-it(Pod::Cache.cache-file($file).IO.slurp, $file)\n}\n"
  },
  {
    "path": "t/17-space-after-comma.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\n\nuse Pod::Cache;\nuse RakuDoc::Test::Files;\n\n=begin overview\n\nEnsure any text that isn't a code example has a space after each comma.\n\n=end overview\n\nmy @files = RakuDoc::Test::Files.documents\\\n    .grep({not $_ ~~ / 'README.' .. '.md' /});\n\nif @files {\n    plan +@files;\n} else {\n    plan :skip-all<No document files specified>\n}\n\n\nsub test-it(Str $output, Str $file) {\n    my $ok = True;\n\n    my $msg = '';\n    for $output.lines -> $line-orig {\n        next if $line-orig ~~ / ^ '    '/;\n        my $line = $line-orig;\n\n        # ignore these cases already in docs/ that don't strictly follow rule\n        $line ~~ s:g/ \"Z,,\" //;\n        $line ~~ s:g/ \"','\" //;\n        $line ~~ s:g/ '\",\"' //;\n        $line ~~ s:g/ << 'a,a,a' >> //;\n        $line ~~ s:g/ << 'a,a,.' //;\n        $line ~~ s:g/ << 'a,a' >> //;\n        $line ~~ s:g/ << 'a,' //;\n        $line ~~ s:g/ ',a' >> //;\n        $line ~~ s:g/ '{AM,PM}' //;\n        $line ~~ s:g/ '(SELF,)' //;\n        $line ~~ s:g/ '\"1,2\"' //;\n        $line ~~ s:g/ '\"a,b\"' //;\n        $line ~~ s:g/ '($var,)' //;\n        $line ~~ s:g/ '(3,)' //;\n        $line ~~ s:g/ << 'thing,category' >> //;\n        $line ~~ s:g/ 'postfix ,=' //;\n        $line ~~ s:g/ ( '+' | '-') \\d* ',' \\d* //; # diff output\n\n        if $line ~~ / ',' [ <!before ' '> & <!before $> ] / {\n            $msg ~= \"Must have space after comma on line `$line`\\n\";\n            diag \"Failure on line `$line`\";\n            $ok = False;\n        }\n\n        if $line-orig ~~ / <alpha> '..' (<space> | $) / {\n            $msg ~= \"File contains .. in `$line-orig`\\n\";\n            diag \"Failure on line `$line`\";\n            $ok = False;\n        }\n    }\n    my $error = $file;\n    ok $ok, $error ~ ($msg ?? \": $msg\" !! \"\");\n}\n\nfor @files -> $file {\n    test-it(Pod::Cache.cache-file($file).IO.slurp, $file);\n}\n"
  },
  {
    "path": "t/18-rakuast-validate.rakutest",
    "content": "#!/usr/bin/env raku\n\n=begin overview\n\nValidate, in a single pass, several characteristics of our\nRakudoc sources using RakuAST.\n\n=head1 C<C>\n\nVerify any C<C<>> tags have no internal trailing whitespace.\nTo explicitly allow it, prepend the C<C<>> with a\nC<Z<ignore-code-ws>> comment, needed in rare cases.\n\n=head1 X<>\n\nEach reference should only have one item (Avoid creating multiple references in the same\nC<X<>> node.\n\n=head1 Links\n\nAll URLS should appear inside C<L<>> tags, not in raw text.\n\n=head1 brackets\n\nAuthors may forget to add a formatting code when\nwrapping something in angle brackets:\n\n    This was supposed to be <bold>.\n\nThis is valid pod, but in practice, these dangling <>'s often indicate an error.\nComplain whenever we find them, except for infix:<> and prefix:<>\n\n=end overview\n\nuse experimental :rakuast;\n\nuse Test;\n\nuse RakuDoc::Test::Files;\n\nmy @files = RakuDoc::Test::Files.pods;\n\nif @files {\n    plan +@files;\n} else {\n    plan :skip-all<No rakudoc files specified>\n}\n\nmy $*TRAILING-C-WHITESPACE-OK = False;\nmy $*INSIDE-LINK = False;\n\nsub walk($node) {\n    my @children;\n    my $check-empty-tags = True;\n\n    if $node ~~ RakuAST::Doc::Paragraph {\n        @children = $node.atoms;\n    } elsif $node ~~ RakuAST::Doc::Block {\n        return if $node.type eq 'code'|'implicit-code'|'comment'|'table';\n        @children = $node.paragraphs;\n    } elsif $node ~~ RakuAST::Doc::Markup {\n        $check-empty-tags = False;\n\n        if $node.letter eq 'L' {\n            $*INSIDE-LINK = True;\n        }\n        if $node.letter eq 'Z' and $node.atoms[0] eq 'ignore-code-ws' {\n            $*TRAILING-C-WHITESPACE-OK = True;\n        }\n        elsif $node.letter eq 'C' {\n            my $content = ~$node.atoms;\n            if $*TRAILING-C-WHITESPACE-OK {\n                pass \"Allowed trailing space on $node\";\n            } else {\n                ok $content eq $content.trim-trailing, $node;\n            }\n            $*TRAILING-C-WHITESPACE-OK = False;\n        } elsif $node.letter eq 'X' {\n            my $meta = ~$node.meta.join('');\n            nok $meta.contains(';'), \"$node must not contain multiple indexes in one X<>\"\n        } else {\n            @children = $node.atoms;\n        }\n    } else {\n        # If this hits, need to adapt test\n        flunk \"new node type: $node.^name\";\n    }\n\n    for @children -> $child {\n        if $child ~~ Str {\n            if ! $*INSIDE-LINK {\n                if $child ~~ / $<url>=[ 'http' 's'? '://' <-[/]>* '/'? ] / {\n                    flunk \"URL found: $<url>\";\n                }\n            }\n            if $check-empty-tags && $child ~~ / $<bracketed>=['<' .*? '>'] / {\n                next if $child.contains(\"prefix:<\" | \"infix:<\" );\n                flunk ~$/<bracketed> ~ \" is likely missing a formatting code\";\n            }\n        } else {\n            walk($child);\n        }\n    }\n    $*INSIDE-LINK = False;\n}\n\nfor @files -> $file {\n    %*ENV<RAKUDO_RAKUAST>=1;\n    subtest $file => {\n        for $file.IO.slurp.AST.rakudoc -> $pod {\n            walk($pod);\n        }\n    }\n}\n"
  },
  {
    "path": "t/19-examples-compilation.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\nuse File::Temp;\n\nuse Pod::Convenience;\nuse RakuDoc::Test::Files;\n\n=begin SYNOPSIS\n\nTest all of the code samples in the document files. Wrap snippets\nin enough boilerplate so that we are just compiling and not executing\nwherever possible. Allow some magic for method declarations to\navoid requiring a body.\n\nSkip any bits marked C<:skip-test> unless the environment variable\nC<RAKU_DOC_TEST_FUDGE> is set to a true value.\n\nComplain about any stylistic issues unless the environment variable\nC<RAKU_DOC_TEST_LAX> is set to a true value.\n\nNote: This test generates a lot of noisy output to stderr; we\ndo hide $*ERR, but some of these are emitted from parts of\nthe compiler that only know about the low level handle, not the\nPerl 6 level one.\n\nError if leading whitespace is present in the code block.\n\n=end SYNOPSIS\n\nmy @files = RakuDoc::Test::Files.pods;\n\nif @files {\n    plan +@files;\n} else {\n    plan :skip-all<No rakudoc files specified>\n}\n\nfor @files -> $file {\n    subtest $file => {\n        plan +my @examples = code-blocks($file);\n        test-example $_ for @examples;\n    }\n}\n\nsub test-example ($eg) {\n    my @lines-all = $eg<contents>.lines;\n    my @lines-ws  = @lines-all.grep(/^ \\s /);\n\n    # nitpicky tests.\n    if !%*ENV<RAKU_DOC_TEST_LAX> {\n        if @lines-ws eq @lines-all {\n            flunk \"$eg<file> chunk starting with «\" ~ starts-with($eg<contents>) ~ '» has extra leading whitespace';\n            next;\n        }\n        # #1355 - don't like .WHAT in examples\n        if !$eg<ok-test>.contains('WHAT') && $eg<contents>.contains('.WHAT') {\n            flunk \"$eg<file> chunk starting with «\" ~ starts-with($eg<contents>) ~ '» uses .WHAT: try .^name instead';\n            next;\n        }\n        if !$eg<ok-test>.contains('dd') && $eg<contents> ~~ / << 'dd' >> / {\n            flunk \"$eg<file> chunk starting with «\" ~ starts-with($eg<contents>) ~ '» uses dd: try say instead';\n            next;\n        }\n        # #3309 - don't like .perl in examples\n        if !$eg<ok-test>.contains('perl') && $eg<contents>.contains('.perl') {\n            flunk \"$eg<file> chunk starting with «\" ~ starts-with($eg<contents>) ~ '» uses .perl: use .raku instead';\n            next;\n        }\n        # #1189 - don't use \"multi sub\"\n        if !$eg<ok-test>.contains('multi') && $eg<contents>.contains('multi sub ') {\n            flunk \"$eg<file> chunk $eg<count>\" ~ ' uses multi sub: use multi instead';\n            next;\n        }\n        # #1189 - don't use \"proto sub\"\n        if !$eg<ok-test>.contains('proto') && $eg<contents>.contains('proto sub ') {\n            flunk \"$eg<file> chunk $eg<count>\" ~ ' uses proto sub: use proto instead';\n            next;\n        }\n    }\n\n    # Wrap snippets in an anonymous class (so bare method works)\n    # and add in empty blocks if needed.\n\n    my $code;\n    if $eg<solo> {\n        $code  = $eg<preamble> ~ \";\\n\" if $eg<preamble>;\n        $code ~= $eg<contents>;\n    }\n    else {\n        $code  = 'no worries; ';\n        $code ~= \"class :: \\{\\n\";\n        $code ~= $eg<preamble> ~ \";\\n\" if $eg<preamble>;\n\n        for $eg<contents>.lines -> $line {\n            state $in-signature;\n\n            $code ~= $line;\n            # Heuristically add an empty block after things like C<method foo ($x)>\n            # to make it compilable. Be careful with multiline signatures:\n            # '(' and ',' at the end of a line indicate a continued sig.\n            # We wait until none of them is encountered before adding '{}'.\n            # Cases that are not covered by the heuristic and which contain\n            # nothing but a method declaration can use :method instead.\n            $in-signature ?|= $line.trim ~~ / ^ ('multi'|'method'|'submethod'|'proto'|'only'|'sub') >> /\n                           && not $eg<method>;\n            if $in-signature && !$line.trim.ends-with(any(« } , ( »)) {\n               $code ~= \" \\{}\";\n               $in-signature = False;\n            }\n            NEXT $code ~= \"\\n\";\n            LAST $code ~= \"\\{}\\n\" if $eg<method>;\n        }\n        $code ~= \"\\n}\";\n    }\n\n    my $msg = \"$eg<file> chunk $eg<count> starts with “\" ~ starts-with($eg<contents>) ~ \"” compiles\";\n\n    my $has-error;\n    my $error-reason;\n    {\n        # Does the test require its own file?\n        if $eg<solo> {\n            my ($tmp_fname, $tmp_io) = tempfile;\n            $tmp_io.spurt: $code, :close;\n            my $proc = Proc::Async.new($*EXECUTABLE, '-c', $tmp_fname);\n            $proc.stdout.tap: {;};\n            $proc.stderr.tap: {$error-reason ~= $_};\n            $has-error = ! await $proc.start;\n        }\n        else {\n            temp $*OUT = open :w, $*SPEC.devnull;\n            temp $*ERR = open :w, $*SPEC.devnull;\n            use nqp;\n            my $*LINEPOSCACHE;\n            my $parser = nqp::getcomp('Raku') || nqp::getcomp('perl6');\n            $has-error = not try { $parser.parse($code) };\n            $error-reason = $! if $!;\n            close $*OUT;\n            close $*ERR;\n\n        }\n    }\n\n    todo(1) if $eg<todo>;\n    if $has-error {\n        diag $eg<contents>;\n        diag $error-reason;\n        flunk $msg;\n    }\n    else {\n        pass $msg;\n    }\n}\n\nsub code-blocks (IO() $file) {\n    my $count;\n    my @chunks = extract-pod($file).contents;\n    gather while @chunks {\n        my $chunk = @chunks.pop;\n        if $chunk ~~ Pod::Block::Code  {\n            # Only testing Raku snippets.\n            next unless $chunk.config<lang>:v eq '' | 'raku' | 'perl6';\n\n            my $todo = False;\n            if $chunk.config<skip-test> {\n                %*ENV<RAKU_DOC_TEST_FUDGE> ?? ($todo = True) !! next;\n            }\n            take %(\n                'contents',  $chunk.contents.map({walk $_}).join,\n                'file',      $file,\n                'count',     ++$count,\n                'todo',      $todo,\n                'ok-test',   $chunk.config<ok-test> // \"\",\n                'preamble',  $chunk.config<preamble> // \"\",\n                'method',    $chunk.config<method>:v,\n                'solo',      $chunk.config<solo>:v,\n            );\n        }\n        else {\n            if $chunk.^can('contents') {\n                @chunks.push(|$chunk.contents)\n            }\n        }\n    }\n}\n\nsub walk ($arg) {\n    given $arg {\n        when Pod::FormattingCode { walk $arg.contents }\n        when Str   { $arg }\n        when Array { $arg.map({walk $_}).join }\n    }\n}\n\nsub starts-with (Str $chunk) {\n    ($chunk.lines)[0].substr(0,10).trim\n}\n"
  },
  {
    "path": "t/20-camelia-invocations.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\n\nuse Pod::Convenience;\nuse RakuDoc::Test::Files;\n\n=begin SYNOPSIS\n\nSearch through all code blocks (with C«:lang<raku>», C«:lang<perl6>» or unset C«:lang»)\nin the document files for lines beginning with \"m:\" which are likely\ncopy-pasted from an IRC log where Camelia or evalable was involved.\n\n\"m:\" can also be part of an adverb'd C«m///». We try to avoid such false\npositives heuristically by looking for match adverbs afterwards.\n\nWhat we can't distinguish are labels called \"m\".\n\n=end SYNOPSIS\n\nmy @files = RakuDoc::Test::Files.pods;\n\nunless @files {\n    plan :skip-all<No rakudoc files specified>;\n    exit;\n}\n\nsub walk($arg) {\n    given $arg {\n        when Pod::FormattingCode { walk $arg.contents }\n        when Str   { $arg }\n        when Array { $arg.map({walk $_}).join }\n    }\n}\n\n# Extract all the examples from the given files\nmy @examples;\n\nmy $counts = BagHash.new;\nfor @files -> $file {\n    my @chunks = extract-pod($file.IO).contents;\n    while @chunks {\n        my $chunk = @chunks.pop;\n        if $chunk ~~ Pod::Block::Code {\n            # Only test :lang<raku> or :lang<perl6> (which is the default)\n            next unless quietly $chunk.config<lang> eq '' | 'raku' | 'perl6';\n            @examples.push: %(\n                'contents',  $chunk.contents.map({walk $_}).join,\n                'file',      $file,\n                'count',     ++$counts{$file},\n            );\n        } else {\n            if $chunk.^can('contents') {\n                @chunks.push(|$chunk.contents)\n            }\n        }\n    }\n}\n\nplan +@examples;\n\nmy regex match-adverbs {\n    | 'i'  | 'ignorecase'\n    | 'm'  | 'ignoremark'\n    | 'r'  | 'ratchet'\n    | 's'  | 'sigspace'\n    | 'P5' | 'Perl5'\n    | \\d*  [ 'st' || 'nd' || 'rd' || 'nth' ]\n    | \\d*  [ 'c'  |  'continue' ]\n    | 'ex' | 'exhaustive'\n    | 'g'  | 'global'\n    | \\d*  [ 'p'  |  'pos' ]\n    | 'ov' | 'overlap'\n}\n\nfor @examples -> $eg {\n    my @camelias = $eg<contents>.lines».trim.grep: /\n        ^ 'm:' <.ws> <!before <match-adverbs> » >\n    /;\n\n    nok @camelias, \"$eg<file> chunk $eg<count> does not invoke camelia\";\n    diag $_ for @camelias;\n}\n"
  },
  {
    "path": "t/21-version-release.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\nuse RakuDoc::Test::Files;\n\n=begin overview\n\nEnsure that any references to a Rakudo release, e.g. 2020.05, are not preceded\nby the word version. 'version' is reserved for language versions, like 6.d.\n\n=end overview\n\nmy @files = RakuDoc::Test::Files.documents;\n\nif @files {\n    plan +@files;\n} else {\n    plan :skip-all<No document files specified>\n}\n\nfor @files.sort -> $file {\n    my $err-count = 0;\n    my $content = $file.IO.slurp;\n    for $content ~~ m:g:i/ <!after 'MoarVM '> 'version 2'\\d\\d\\d\\.\\d\\d / -> $match {\n        $err-count++;\n    }\n    my $error = $file;\n    if $err-count {\n        $error ~= \" ($err-count instance{$err-count==1 ?? '' !! 's'})\";\n    }\n    ok !$err-count, \"$error: Rakudo releases should not be called 'version'.\" ;\n}\n"
  },
  {
    "path": "t/22-glossary-sorted.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse experimental :rakuast;\nuse Test;\nuse RakuDoc::Test::Files;\n\n=begin overview\n\nVerify the glossary is sorted\n\n=end overview\n\nmy @files = RakuDoc::Test::Files.pods.grep(*.contains('glossary'));\n\nif @files {\n    plan +@files;\n} else {\n    plan :skip-all<Not testing the glossary>;\n}\n\n# Should just be the glossary\nfor @files -> $file {\n    subtest $file, {\n        my @headings;\n        for $file.IO.slurp.AST.rakudoc -> $node {\n            for $node.paragraphs -> $node2 {\n                next unless $node2 ~~ RakuAST::Doc::Block;\n                next unless $node2.type eq \"head\";\n                next unless $node2.level eq 1;\n                for $node2.paragraphs -> $node3 {\n                    if $node3 ~~ Str {\n                        flunk \"=head1 with no xref tag\";\n                    } else {\n                        my $xref = $node3.atoms[0];\n                        unless $xref.letter eq 'X' {\n                            flunk \"=head1 with invalid markup tag\";\n                        }\n                        @headings.push: ~$xref.atoms;\n                    }\n                }\n            }\n        }\n        is @headings, @headings.sort(*.fc), \"=head1 are sorted\";\n    }\n}\n"
  },
  {
    "path": "t/23-aspell.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\n\nuse Pod::Cache;\nuse RakuDoc::Test::Files;\n\n=begin overview\n\nSpell check all the pod and most markdown files in the documentation directory.\n\nIgnore case, and provide a repo-specific list of approved words,\nwhich include technical jargon, method and class names, etc.\n\nTo run this test, you'll need to install aspell and the English dictionary package.\n\nOn Mac OS X, you can install aspell using macports (https://macports.org/).\n\n=begin code\n$ sudo port install aspell\n$ sudo port install aspell-dict-en\n=end code\n\nOn Linux, both aspell and the C<en> dictionary should be available in your\ndistribution's package manager and may already be installed.  However, depending\non your distribution, you may need to update to aspell's C<en> dictionary to a\nmore recent version than the one available through your package manager. (The\n2019.10.06 version is known to work).  You can download up-to-date dictionary\nfiles directly from aspell at\nL<https://ftp.gnu.org/gnu/aspell/dict/0index.html>; the downloaded archive will\ninclude installation instructions.\n\nThis test uses separate lexicons for descriptive text and code, allowing us to\nspecify \"words\" that are only allowed in code (variable names, some output,\netc.).\n\nIf the test fails, you can make it pass again by changing the\ntext (fixing the spelling issue), or adding the new word to\nC<t/pws/words.pws> (if it's a word, a class/method name, known\nprogram name, etc.), or to C<t/pws/code.pws> (if it's a fragment of\ntext that is part of a code example)\n\n=end overview\n\nmy @files = RakuDoc::Test::Files.documents.grep({not $_ ~~ / 'README.' .. '.md' /});\n\nif @files {\n    plan +@files * 2;\n} else {\n    plan :skip-all<No document files specified>\n}\n\nmy $proc = shell('aspell -v');\nif $proc.exitcode {\n    skip-rest \"This test requires aspell\";\n    exit;\n}\n\n# generate a combined words file\n# a header is required, but is supplied by words.pws\n\nmy $dict = $*PROGRAM.parent.child(\"pws/aspell.pws\").open(:w);\n$dict.say($*PROGRAM.parent.child(\"pws/words.pws\").IO.slurp.chomp);\n$dict.say($*PROGRAM.parent.child(\"pws/code.pws\").IO.slurp.chomp);\n$dict.close;\n\nmy %output;\n\nmy $lock = Lock::Async.new;\n\n@files.race.map: -> $file {\n    # We use either the raw markdown or the rendered/cached Pod.\n    my $input-file = Pod::Cache.cache-file($file);\n\n    # split the input file into a block of code and a block of text\n    # anything with a leading space is considered code, and we just\n    # concat all the code and text into one block of each per file\n\n    my Str $code = '';\n    my Str $text = '';\n\n    # Process the text so that aspell understands it.\n    # Every line starts with a ^\n    # turn \\n and \\t into spaces to avoid \\nFoo being read as \"nFoo\" by aspell\n    for $input-file.IO.slurp.lines -> $line {\n        my Bool $is-code = $line.starts-with(' ');\n\n        my $processed =  '^' ~ $line.subst(/ \\S <( '\\\\' <[tn]> )>/ , ' ', :g) ~ \"\\n\";\n\n        $code ~= $processed if $is-code;\n        $text ~= $processed unless $is-code;\n    }\n\n    for <code text> -> $type {\n        # Restrict dictionary used based on block type\n        my ($dict, $body);\n        if $type eq \"code\" {\n            $body = $code;\n            $dict = $*PROGRAM.parent.child(\"pws/aspell.pws\").absolute;\n        } else {\n            $body = $text;\n            $dict = $*PROGRAM.parent.child(\"pws/words.pws\").absolute;\n        }\n\n        react {\n            my $proc = Proc::Async.new:\n                :w,\n                ['aspell', '-a', '-l', 'en_US', '--dont-suggest',\n                '--encoding=utf-8', '--ignore-case', \"--extra-dicts=$dict\", '--mode=url'];\n\n            whenever $proc.stdout.lines {\n                $lock.protect: {\n                    %output{$file}{$type}<output> ~= \"$_\\n\";\n                }\n            }\n\n            whenever $proc.start {\n                done;\n            }\n\n            whenever $proc.print: \"!\\n$body\\n\" {\n                $proc.close-stdin;\n            }\n        }\n    }\n}\n\nfor %output.keys.sort -> $file {\n    for %output{$file}.keys -> $type {\n        my $spelling-errors =\n            %output{$file}{$type}<output>.lines.tail(*-1).map: -> $line {\n                $line ?? $line.words[1] !! Empty\n            }\n\n        nok $spelling-errors, \"$file ($type) has {+$spelling-errors} spelling errors\";\n        if $spelling-errors -> $_  {\n            diag join(\"\\n\", 'Errors:', '='x 7, |$_).indent: 4 }\n    }\n}\n"
  },
  {
    "path": "t/24-words.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\n\n=begin overview\n\nVerify setup of lexicon files used to drive C<t/23-aspell.rakutest>.\n\nAvoid duplicates, verify header, lowercase, sorting.\n\n=end overview\n\nplan 6;\n\nmy @words = $*PROGRAM.parent.child('pws/words.pws').IO.lines;\nmy @code = $*PROGRAM.parent.child('pws/code.pws').IO.lines;\n\nmy $header = @words.shift;\n\nok($header ~~  / 'personal_ws-1.1 en ' \\d+  ' utf-8' /, \"header on t/pws/words.pws is correct\");\n\nsub sorted(@lexicon) {\n    return [&&] @lexicon.rotor(2 => -1).map({$_[0] lt $_[1]})\n}\n\nok(sorted(@words), \"t/pws/words.pws is sorted and unique\");\nok(sorted(@code), \"t/pws/code.pws is sorted and unique\");\n\nmy @dupes = @words.Set ∩ @code.Set;\n\nis(~@dupes, \"\", \"No duplicates between t/pws/words.pws and t/pws/code.pws\");\n\n# are all the words lower case?\n# (ignore some unicode that aspell doesn't case fold as well as we do.\nsub get-uppers(@lexicon) {\n    @lexicon.grep({ .lc ne $_ }).grep({ ! $_.contains('Þ') })\n}\n\nmy $uppers = get-uppers(@words);\nis($uppers.elems, 0, \"all words in t/pws/words.pws are lowercase\");\ndiag $uppers if $uppers.elems;\n\n$uppers = get-uppers(@code);\nis($uppers.elems, 0, \"all words in t/pws/code.pws are lowercase\");\ndiag $uppers if $uppers.elems;\n"
  },
  {
    "path": "t/pws/code.pws",
    "content": "aaaaaa\naaabbc\naaabbcccc\naaaxbbxc\naab\naabbccc\naabbccddaa\naac\naad\naaf\naagcct\naao\naapl\nabababa\nabacabadabacaba\nabb\nabba\nabbbbbcdddddeffg\nabcabc\nabcde\nabcdef\nabcdefg\nabcdefgh\nabcdefghi\nabcdefghij\nabcdefghijk\nabcdefghijklmnopqrstuvwxyz\nabd\nabf\nabra\nabraca\nabracada\nabstractserializable\naca\nacada\nacadabra\naccum\nacd\nacf\nacg\nacgtacgtt\nacgtcg\nadabra\naddrconfig\naddrlen\naddrnativecalllen\naddrstrlen\nade\nadipiscing\naec\naed\nafa\nailema\nailemac\naj\nalgebradebugger\nalgebraparser\nalpha'beta'gamma\namet\nanotherrole\nanyat\nao\napoint\nappdata\napperling\naq\narglist\nasciitilde\nasdf\nastringandanint\natf\natfoobar\naxi\naxxxbxxxc\nay\nayy\nazc\naäo\naå\naöä\naþðbþðc\naþðþbþðþc\nbada\nbak\nbao\nbarename\nbbbabb\nbbbbb\nbbbbbb\nbbbbbdddddeff\nbcd\nbd\nbeb\nbel\nbettercalculations\nbettercalculator\nbg\nbh\nbinarytree\nbirthdaycongrats\nbitrary\nbj\nbn\nbol\nboogaloo\nbq\nbracketleft\nbracketright\nbrakcet\nbt\nbtf\nbuz\nbv\nbw\nbz\nbú\ncadabra\ncaf\ncafé\ncagcggaagcct\ncannonname\ncanonidn\ncanonname\ncarefulclass\ncba\nccc\ncde\ncdef\ncdgh\ncentre\ncha\ncharbuf\nchildclass\nchildname\ncjk\ncliché\nclogger\ncn\ncntrl\ncodelines\ncommonancestor\nconfigurationsets\nconfigurationsetsactions\nconfigvalues\nconsectetur\nconsologger\ncp\ncppstruct\ncreateconnection\ncreateserver\ncsisolatin\ncvvf\ncześć\nczf\ndaemonize\ndccp\nddd\ndddddeff\ndebugtype\ndeclaratorone\ndefg\ndesigilname\ndest\ndf\ndgram\ndiceroll\ndigifier\ndigitmatcher\ndirstat\ndiskn\ndists\ndm\ndoit\ndojob\ndoorhandle\ndostuff\ndwflags\ndxex\neb\nee\nef\nefg\nehehe\nelit\nencodedbuffer\neoh\neoi\nesc\nesponja\ney\nfailer\nfairycake\nfalsenot\nfalses\nfb\nfba\nfcf\nfffd\nffff\nffffffffffffffffffffffffffffffff\nfgh\nfilea\nfileb\nfilec\nfindnodes\nfirstname\nfirstpos\nfirstvalue\nfizzbuzz\nflowinfo\nfname\nfnorbl\nfo\nfoobarbaz\nfoobaz\nfoober\nfoohandle\nfooo\nfoooo\nfooooo\nfoooooo\nfoox\nfooy\nfooz\nforbiddendirectory\nforgetit\nfotbar\nfp\nfreeaddrinfo\nfreija\nfrob\nfrobs\nfromcharcode\nfubar\nfullname\nfunmath\nfuu\nfx\nfxx\nfxxoo\nfxxx\ngaa\ngaatcc\ngargravarr\ngct\ngecos\ngeth\ngetter\ngg\ngha\nghghfxnnhrgfswe\nghi\nghidora\ngniht\ngnirts\ngoog\ngrammaradvice\ngrassmannnumber\ngreatunclebulgaria\ngreetbot\ngroß\ngtt\nguid\nguillemotleft\nguillemotright\nhallo\nhasour\nhavestaticattr\nhb\nhdr\nheapsnapshot\nhellogoodbye\nheyfoofoofoo\nhhgttu\nhou\nhtoken\nhttprequest\nic\nidaqt\nidn\nieq\nij\nijklmnop\nimm\nimplementationdetail\niniformat\ninnie\nintegralparser\nintillo\nintillos\nintliteral\ninv\ninvertiblepoint\nipsum\nisprime\niter\niters\nitotallyjustmadethisup\njin\njk\njpe\nkeyvaluepairs\nkxga\nlaer\nlaf\nlaquo\nlastname\nlchar\nlegacylambda\nlenticular\nlhex\nlibbar\nlinkedlist\nlistofstuff\nlistoid\nlmao\nlogdupe\nloggedversion\nlol\nlorem\nluca\nmakefromjson\nmakequestionable\nmalloc\nmanymanymany\nmarly\nmatchobject\nmatiroi\nmaybeval\nmctesty\nmday\nmegagigaterapetacorp\nmegingjörð\nmessageboxa\nmessageboxw\nmetamodelx\nmfoo\nmh\nmmn\nmodulename\nmoveup\nmsvc\nmuchmoresecure\nmugen\nmul\nmult\nmultihyphenate\nmvmheap\nmyapp\nmyclass\nmycstruct\nmydir\nmyfile\nmyfoo\nmyhome\nmyletter\nmylib\nmynew\nmynumber\nmyrange\nmyscript\nmysqlclient\nmystring\nmystruct\nmysum\nmyunion\nmøp\nnamedvector\nnana\nnbr\nnbsp\nneutronium\nnewclass\nnewfunc\nnextone\nniler\nnini\nnnbsp\nnoez\nnosuch\nnotthere\nnumbersign\nnumerichost\nnumericserv\nnumlist\nobai\nobjs\nohai\noioioioioioioioioioi\nonceuponatime\noob\nooooo\noooxo\nooxoo\nopensuse\noriglist\notherrole\noutahere\noutfor\noutputfile\noxooo\noðinn\npantuflo\nparentclass\nparseint\nperly\nplustwo\npostgre\npostorder\nppszpath\nprecompilationstore\nprettylist\npriv\nprog\nprogs\npwstruct\nq'this\nqqq\nqqrq\nqrstuvwx\nqs\nquant\nquietlevel\nquotedbl\nquotedstring\nqux\nqxelwq\nraker\nrakulambda\nrakuy\nranklist\nraquo\nrawheader\nrbar\nrchar\nrdm\nrectanglewithcachedarea\nregexname\nrememberit\nremy\nrenderbarchart\nrepcount\nrepeatchar\nrepositoryfilesystem\nreq\nresourceable\nrestnameds\nrestpos\nrfid\nrg\nrhex\nräku\nsar\nsayit\nsaysomething\nsdk\nseener\nseqpacket\nsetcallback\nsetencoding\nsetgoal\nsev\nshgetknownfolderpath\nshoriyuru\nsigabrt\nsigalrm\nsigbreak\nskippingarray\nsl\nsleepsorter\nsnitchee\nsnitcher\nsomeclass\nsomeerror\nsomefile\nsomeparentclass\nsometext\nsortedarray\nspoint\nstartee\nstatm\nstmt\nstrasse\nstraße\nstrillo\nstringone\nstringthree\nstrliteral\nsu\nsubsethow\nsyslog\ntac\ntalkin\ntcc\ntcg\ntenten\ntes\ntestanimal\ntestee\ntestgrammar\ntextnode\nthat'sawesome\nthorndike\ntobermory\ntok\ntoomany\ntouppercase\ntraceback\ntri\ntrin\ntring\ntrunc\ntsc\ntsil\ntvalue\ntwly\ntwodim\ntwowords\ntypedef\ntypehouse\ntête\nubits\nuff\nuia\nukar\nultraman\nunflat\nunitish\nunspec\nusafa\nvalueclasshow\nvaluemap\nversionmajor\nversionminor\nvn\nvu\nvvvvv\nvvvvvvvvv\nvvvvvvvvvvv\nvvvvvvvvvvvvv\nvvvvvvvvvvvvvvvvv\nvvvvvvvvvvvvvvvvvvvv\nvx\nwday\nwelp\nwhatevera\nwhateverable\nwithattribute\nwithattributes\nwithoutlinenumber\nxa\nxab\nxbb\nxbeef\nxc\nxf\nxffff\nxoooo\nxyz\nyday\nyeterani\nyourapp\nyourclass\nyourmodule\nyz\nza\nzapatilla\nzbcd\nzerobuf\nzeroorinf\nzipwith\nzwelp\nzycd\nzzbcd\nÞfl\nßub\nàáâãäåæ\näöüß\näộñ\nåäö\nðar\nüị\nþoo\nþð\nǣp\n"
  },
  {
    "path": "t/pws/words.pws",
    "content": "personal_ws-1.1 en 2172 utf-8\nabab\nababab\nabcd\nabi\nabsolutepath\naccessor\naccessors\nacgt\nacknowledgement\nacos\nacosec\nacosech\nacosh\nacotan\nacotanh\naddr\naddrinfo\naddrtype\nadhoc\nae\naeiou\nalap\nalgorithmically\nalikes\naliquot\nallcaps\nallee\nalloc\nallof\nallomorph\nallomorphic\nallomorphs\nalnum\nalphanumerics\nalreadystarted\naltgr\namic\namongst\naname\nandthen\nantipair\nantipairs\nanyof\napis\narchname\naref\narg\nargfiles\nargless\nargs\nargsfiles\nargumentless\nargv\nargvout\narithmetics\narity\narrayref\narraytype\nasciicircum\nasec\nasech\nasin\nasinh\nassignees\nassignval\nassociatively\nassociatives\nasstr\nast\nasts\nasync\nasynchronicity\nasynchrony\nasyncs\natan\natanh\natc\natomicint\natomicints\natomicity\natq\nattr\nattrib\nattributecontainer\nattrinit\nattrs\nauth\nauths\nautoboxed\nautoboxing\nautodie\nautoflush\nautogenerated\nautoincrement\nautolines\nautoload\nautomagically\nautopun\nautoquoted\nautoquotes\nautostart\nautothread\nautothreaded\nautothreading\nautothreads\nautovivification\nautovivified\nautovivifying\nawaitable\nawk\nbabaganush\nbackend\nbackends\nbackslashed\nbacktick\nbackticks\nbacktrace\nbacktraces\nbaggy's\nbaghash\nbaghash's\nbaghashes\nbaldr\nbarewords\nbarriering\nbarz\nbasename\nbasename's\nbasetime\nbasetype\nbaz\nber\nbigendian\nbigint\nbignum\nbigpage\nbigrat\nbinaryandencoding\nbinarymode\nbindingtype\nbindkey\nbindoruse\nbinmode\nbitbucket\nbitmask\nbitmaskenumeration\nbitwise\nbksl\nbolded\nbom\nbool\nbooleanification\nbooleans\nboolificationprotocol\nboolified\nboolifies\nboolify\nbools\nboooh\nbraceleft\nbraceright\nbrack\nbragi\nbrainer\nbuf\nbufs\nbuildplan\nbuiltins\nbytecode\nbytelength\ncalc\ncallables\ncallee\ncallframe\ncallsame\ncallwith\ncamelia\ncancelled\ncando\ncannotconvert\ncanonicalize\ncanonpath\ncanwrite\ncapita\ncapitan\ncapslock\ncaron\ncarray\ncarrays\ncas\ncaseless\ncatdir\ncatfile\ncathandle\ncathandle's\ncatpath\ncauseonlyvalidonbroken\ncglobal\nchainable\ncharset\ncharsorbytes\nchdir\ncheatsheet\ncheckee\nchmod\nchocolatey\nchown\nchr\nchroot\nchrs\ncircumfix\ncis\nclasshow\nclassname\ncli\nclosedir\ncmd\ncmp\ncodebase\ncodename\ncodepoint\ncodepoints\ncoderef\ncoercions\ncolonpair\ncolonpairs\ncolour\ncombinators\ncommandline\ncomparator\ncompat\ncompilable\ncompiletime\ncomplexstr\ncomposability\ncomposable\ncomposalizer\ncompunit\ncompunits\ncomspec\nconcat\nconcreterolehow\nconcretization\ncond\nconditionvariable\nconfig\nconfigitem\nconfigs\nconformant\nconfusability\nconfusable\nconnor\nconst\ncontextualizer\ncontextualizers\ncontrolflow\ncoprime\ncoroutines\ncosec\ncosecant\ncosech\ncotan\ncotanh\ncpan\ncpointer\ncpus\ncreateonly\ncrlf\ncro\ncrontab\ncstr\ncstruct\ncstructs\ncsv\nctrl\nctype\ncueing\ncueinnanseconds\nculting\ncunion\ncunions\ncurdir\ncurrentthreadscheduler\ncurriedrolehow\ncurupdir\ncustomizable\ncwd\ncx\ncygwin\ndaenerys\ndangerousness\ndany\ndataflow\ndatehash\ndateish\ndatetime\ndatetimes\ndaycount\ndbi\ndbiish\ndbm\ndbmclose\ndbmopen\ndbname\nddthh\ndeallocation\ndecl\ndeclarator\ndeclarators\ndeclaratortarget\ndecodable\ndecont\ndecontainerization\ndecontainerize\ndecontainerized\ndecrementing\ndeepmap\ndefaultparent\ndefinedness\ndefinitehow\ndefn\ndelegatee\ndelegatee's\ndelegator\ndeliminates\ndellingr\ndenormals\ndeopt\ndeopts\ndeparse\ndeparsing\ndependencyspecification\ndeprecations\ndeps\ndequeue\nderef\ndereference\ndereferenced\ndereferencing\ndesc\ndeserialize\ndeserializing\ndestructor\ndestructure\ndestructured\ndestructuring\ndesugars\ndet\ndev\ndevel\ndevnull\ndevs\ndevtype\ndex\ndiag\ndicts\ndifferentiator\ndiffy\ndirhandle\ndirname\ndirs\ndisambiguates\ndistro\ndistronames\ndividebyzero\ndl\ndll\ndmg\ndmy\ndns\ndocumenting's\ndoesnotexist\ndol\ndom\ndpkg\ndsl\ndsls\ndt\nduckmap\ndurations\ndwim\ndx\ndyld\ndylib\ndynlib\negid\neigenstate\neigenstates\nel\nelems\nelse's\nelsif\nenclosable\nencodings\nendgrent\nendhostent\nendian\nendianness\nendif\nendnetent\nendprotoent\nendpwent\nendservent\nenqueue\nenqueues\nentrapments\nents\nenum\nenum's\nenumhow\nenumhow's\nenums\nenv\neof\neol\neos\neq\nequalities\neqv\nerrno\nesque\neuid\neurosign\neval\nevalbot\nevalbytes\nevaled\nevalfile\nevdev\nexclam\nexe\nexecl\nexecutables\nexecv\nexecvp\nexecvpe\nexitcode\nexpmod\nexporthow\nexpr\nextern\neyewear\nfabc\nfac\nfacename\nfacenamedoublesize\nfacesize\nfailable\nfailgoal\nfailhash\nfailover\nfallbacks\nfallthru\nfalsy\nfatrat\nfatratstr\nfaçades\nfc\nfcntl\nfeff\nfff\nfh\nfilechanged\nfilechangeevent\nfilehandle\nfilehandles\nfileno\nfilerenamed\nfilesystem\nfilesystems\nfiletest\nfiletests\nfingerprintingprotection\nflatmap\nflipflop\nfmt\nfnew\nfoldl\nfoldr\nforbiddenword\nforeach\nforeigncode\nformatter\nformattingcode\nformline\nfoy\nfoy's\nfptr\nfqn\nfrobnicate\nfrobnication\nfrontend\nfsvo\nftfy\nfunc\ngammera\ngaz\ngc\ngcd\ngeekcook\ngenericsocket\ngeodesists\ngetaddrinfo\ngetc\ngetgrent\ngetgrgid\ngetgrnam\ngethostbyaddr\ngethostbyname\ngethostent\ngetlogin\ngetnetbyaddr\ngetnetbyname\ngetnetent\ngetopt\ngetoptions\ngetpeername\ngetpgrp\ngetppid\ngetpriority\ngetprotobyname\ngetprotobynumber\ngetprotoent\ngetpwent\ngetpwnam\ngetpwuid\ngetrusage\ngetservbyname\ngetservbyport\ngetservent\ngetsock\ngetsockname\ngetsockopt\ngettime\ngetuid\ngid\ngists\ngitlab\ngiveth\nglobals\nglyphs\ngmtime\ngmtime's\ngoku\ngoto\ngptrixie\ngrabpairs\ngrammaring\ngrapheme\ngraphemes\ngraphviz\ngroupname\ngtc\ngtk\ngtq\nguillemets\ngvim\ngw\ngz\ngzip\nhackery\nhagrid\nhardcoded\nhashref\nhaskelly\nheadn\nheatsink\nheredoc\nheredocs\nhexdump\nhh\nhll\nhoc\nhola\nhomebrew\nhomedrive\nhomepath\nhostname\nhostnames\nhotspot\nhowd\nhref\nhttps\nhuffmanize\nhuffmanizing\nhyperbolicus\nhypered\nhyperoperator\nhyperoperators\nhyperseq\nhyperseqs\nhyperwhatever\nhyperwhatever's\nibus\nident\nidir\nidna\nidrss\nidx\nignorecase\nignoremark\niirc\nilib\nilluminatus\nim\nimg\nimprecisions\ninb\ninblock\nincrementer\nincrementing\nindir\nindirections\ninet\ninfixes\ninfixintermposition\ninframan\nini\ninit\ninitializable\ninitializations\ninitializer\ninitializers\ninlined\ninlining\ninode\ninplace\ninstallable\ninstallermaker\ninstanceof\ninstantiation\ninstantiations\ninteroperate\ninteroperation\nintmax\nintrospectable\nints\nintstr\ninvalidconcreteness\ninvalidformat\ninvalidqualifier\ninvcsw\ninvocable\ninvocant\ninvocant's\ninvocantmarker\ninvocants\nipv\nisa\nisbuffer\nisdst\nisengard\nish\nisnan\nisnt\nisrss\niswhat\nitemizer\niterable\niterables\niterationbuffer\niterationend\niteratively\niwbn\nixress\niðunn\njit\njitted\njj\njmerelo\njnthn\njoffrey\njpegs\njpg\njs\njs's\njson\njunctive\njvm\nkaiepi\nkbar\nkd\nkde\nkernelnames\nkeycodes\nkeymap\nkeyof\nkeypress\nkeyvaluepairsactions\nkhaleesi\nkib\nknowhow\nkutta\nkv\nkvpair\nkxxv\nlakhs\nlangs\nlanguagelist\nlastable\nlastcall\nlatebound\nlayoutlist\nlcfirst\nld\nleftsinglequotemark\nlenz\nlenz's\nletterspace\nlexically\nlexicals\nlexicographically\nlexing\nlexpad\nlf\nlgtm\nlhf\nlhs\nlibera\nlibfoo\nlibidn\nlibmysql\nlibmysqlclient\nlibname\nlibs\nlibsomething\nlibwhatever\nlibxxhash\nlinearize\nlineeditor\nlinenoise\nlinters\nlistensocket\nlistop\nlistops\nlisty\nliteralize\nliteralizes\nlittleendian\nlizmat\nlje\nlm\nlocalhost\nlocalport\nlocaltime\nlogdir\nlongclassname\nlonglong\nlookahead\nlookaround\nlookbehind\nlookups\nlossy\nlowercased\nlowercases\nlsb\nlstat\nlta\nltm\nlval\nlvalue\nlvalues\nmacos\nmacosx\nmacports\nmacvim\nmajf\nmajflt\nmakefile\nmappable\nmasak\nmasterduke\nmatcher\nmatchers\nmattijsen\nmaxbuf\nmaxpairs\nmaxrss\nmaybevals\nmayspec\nmbc\nmbigint\nmdy\nmemoized\nmerelo\nmetacharacter\nmetacharacters\nmetaclass\nmetaclasses\nmetadocumentation\nmetagenomics\nmetalevel\nmetamethod\nmetamethod's\nmetamethods\nmetamodel\nmetaobject\nmetaobjects\nmetaop\nmetaoperator\nmetaoperators\nmetapackage\nmetaprogramming\nmetaquestions\nmetareduced\nmetarole\nmetasyntactic\nmetatype\nmetatypes\nmethodcontainer\nmethoddelegation\nmethodname\nmethodop\nminf\nminflt\nminibuffer\nminimalistic\nminmax\nminpairs\nmiscategorized\nmissinginitializer\nmixhash\nmixhashes\nmixin\nmixin's\nmixins\nmixy\nmjd\nmjölnir\nmjölnir's\nmkdir\nmmk\nmoar\nmoarperf\nmoarvm\nmoarvm's\nmodulehow\nmojo\nmojolicious\nmoritz\nmottos\nmplayer\nmrcv\nmro\nmrobasedmethoddispatch\nmrobasedtypechecking\nmsb\nmsgctl\nmsgget\nmsgrcv\nmsgsnd\nmsi\nmsnapper\nmsnd\nmultiline\nmultimethodcontainer\nmultimethods\nmultiness\nmultipleinheritance\nmultipletypeconstraints\nmultis\nmultiset\nmultithreaded\nmustbestarted\nmutator\nmutators\nmutex\nmutexes\nmyfunnyrole\nmymodule\nmyname\nmyprogram\nmysection\nmytype\nnada\nnameclash\nnamespace\nnamespaced\nnamespaces\nnanna\nnano\nnanosecs\nnativecall\nnativecast\nnativeendian\nnativehelpers\nnatively\nnativeness\nnativesize\nnativesizeof\nnativetype\nnegatedpair\nnewdir\nnewfile\nnewname\nnewsocket\nnewtype\nnextcallee\nnextcallee's\nnextsame\nnextwith\nnfd\nnfg\nnfkc\nnfkd\nniecza\nniner\nnivcsw\nnl\nnodality\nnodejs\nnodejs's\nnodemap\nnodir\nnodispatcher\nnofile\nnok\nnom\nnomatch\nnominalizable\nnominalize\nnominalized\nnonchaining\nnonintuitive\nnonspacing\nnoop\nnopackage\nnoproto\nnoself\nnosuchlang\nnosuchtype\nnotandthen\nnotcomposable\nnotcomposed\nnotdynamic\nnotfound\nnoto\nnowrite\nnqp\nnqp's\nnqpmatchrole\nnsems\nnsig\nnsignals\nnst\nnswap\nnswp\nntop\nnul\nnullish\nnum\nnumericenumeration\nnumerics\nnumericstringyenumeration\nnumified\nnumify\nnumillo\nnums\nnumstr\nnushi\nnvcsw\nnyi\nnée\nnótt\nobjat\nobjectioner\nofs\nofun\nol\noldfile\noldname\noldpwd\nomg\noneline\noneover\noo\noop\nopaquepointer\nopendir\nopenforwriting\nopstring\noptionparser\noptname\noptparse\noptval\norcish\nord\nords\norelse\norm\nors\norson\norwith\nosname\nosr\nosrs\notherphi\noublock\noutb\noutdented\noutdents\nouter's\nouters\noutofrange\nov\noverridable\noðin\npackagehow\npairup\nparallelization\nparallelize\nparam\nparameterization\nparameterizations\nparameterizer\nparameterizes\nparameterizing\nparameterless\nparametricconstant\nparametricrolegroup\nparametricrolegrouphow\nparametricrolehow\nparametricrolehows\nparams\nparen\nparenleft\nparenright\nparsable\nparsefile\nparsers\npasswd\npasttype\nperldb\nperldoc\nperlfunc\nperlito\nperllib\nperlop\nperlsyn\npgrp\nphaser\nphasers\nphotoshop\npickpairs\npid\npinnsler\npixelsize\nplaintext\npluggable\npmc\npng\npodtohtml\npolation\npolymod\npolymorphism\nportably\npos\npositionalat\npositionalbindfailover\npositionally\npositionals\nposix\npostamble\npostcircumfix\npostcircumfixed\npostcircumfixes\npostcondition\npostconditions\npostderef\npostfix\npostfixed\npostfixes\npostincrement\npostmatch\npov\npragma\npragma's\npragmas\npre\nprecedences\nprecomp\nprecompilation\nprecompilationid\nprecompilationrepository\nprecompilations\nprecompilationunit\nprecompile\nprecompiled\nprecompiles\nprecompiling\npred\npredictiveiterator\npreincrement\nprematch\npreorder\nprepend\nprepended\nprepending\nprepends\nprepost\npreprocessed\npreprocesses\nprev\nprimality\nprintf\nprivatemethodcontainer\nproc\nprocs\nprofiler\nprogramfile\nprogrammatically\nproleptic\npromisestatus\npropname\npropspec\nproscriptive\nproto\nproto's\nprotos\nprototyped\npseudocode\npseudopackage\npseudostash\nptrdiff\npty\nptys\npunct\npunycode\nputenv\npvalname\npwd\npy\npyc\nqast\nqnx\nqq\nqqw\nqqww\nqqx\nquaggas\nquanthash\nquanthashes\nquantifiervalue\nquasiquoting\nquaternion\nqueueing\nqueuesize\nquickstart\nquotelike\nquotemeta\nquoter\nquotewords\nquux\nqw\nqww\nqx\nraceseq\nraceseqs\nradix\nradixoutofrange\nraja\nrak\nraku\nraku's\nrakuast\nrakubrew\nrakuda\nrakudo\nrakudo's\nrakudoc\nrakudolib\nrakudow\nrakulib\nrakumod\nrakutest\nrakuw\nralt\nratstr\nrdev\nreadchars\nreaddir\nreadhandle\nreadline\nreadlines\nreadlink\nreadme\nreadonly\nreadonlyness\nreadpipe\nrebless\nreblessed\nreceiveonclosed\nrecurse\nrecv\nreddit\nredeclaration\nredeclarations\nredeclared\nredispatch\nredispatcher\nreducecheck\nrefinee\nregexes\nreifier\nrenderer\nrenderers\nrepl\nrepo\nrepo's\nrepositoryregistry\nrepr\nreprcomposeprotocol\nrepresentable\nreprs\nresultn\nresumable\nret\nrethrow\nrethrown\nrethrows\nreusability\nrewinddir\nrhs\nrightsinglequotemark\nrindex\nrlwrap\nrmdir\nrmtree\nro\nroadmap\nrolecontainer\nrolepunning\nrolish\nrootdir\nrosenfeld\nrotoring\nrotorizing\nroundrobin\nroundtrip\nrsn\nrss\nrubygems\nrubylib\nrunge\nrungekutta\nruntime\nruntime's\nruòxī\nrvalue\nrvalues\nrw\nrwx\nrz\nsamecase\nsamemark\nsamespace\nsamewith\nsaruman\nsbin\nscalarization\nscalarized\nscss\nsech\nsed\nseekable\nseekdir\nseekfrombeginning\nseekfromcurrent\nseekfromend\nseektype\nsemctl\nsemget\nsemilist\nsemilists\nsemnum\nsemop\nsendonclosed\nseq's\nseqs\nsessionstorage\nsetgrent\nsethash\nsethashes\nsethostent\nsetnetent\nsetpgrp\nsetpriority\nsetprotoent\nsetpwent\nsetservent\nsetsockopt\nsetty\nsetxkbmap\nsha\nshellquote\nshiftjis\nshitov\nshm\nshmctl\nshmget\nshmread\nshmwrite\nshortdescription\nshortname\nshoveller\nsig\nsigbus\nsighup\nsigil\nsigiled\nsigilless\nsigils\nsigint\nsigkill\nsignedness\nsigspace\nsigterm\nsigusr\nsimsalabim\nsinh\nsizeof\nskipbuiltinglyphs\nslangify\nslangs\nsliceable\nslurpies\nslurpily\nslurpiness\nslurpy\nslurpysentry\nsmartmatch\nsmartmatched\nsmartmatches\nsmartmatching\nsmtp\nsockaddr\nsocketpair\nsocklen\nsocktype\nsolitaryquantifier\nsomeauthor\nsomeblockname\nsomerole\nsortable\nspdx\nspectest\nspesh\nspeshed\nsplitdir\nsplitpath\nsplitter\nsplitters\nsprintf\nsqrt\nsrand\nsrc\nsref\nssize\nssz\nstackframe\nstackoverflow\nstacktrace\nstagestats\nstartidx\nstatementlist\nstayopen\nstderr\nstdin\nstdlib\nstdout\nstr\nstrdistance\nstrdup\nstringification\nstringified\nstringifies\nstringify\nstringifying\nstringyenumeration\nstrorarrayofstr\nstrs\nstruct\nstructs\nstubcode\nstyleguide\nsubarray\nsubbuf\nsubclassed\nsubclasses\nsubclassing\nsubdirectories\nsubdirectory\nsubexpression\nsubexpressions\nsublanguage\nsublanguages\nsublist\nsublists\nsubmatch\nsubmatches\nsubmethod\nsubmethods\nsubname\nsubnormals\nsubpackage\nsubparse\nsubref\nsubrule\nsubrules\nsubscriptable\nsubscripted\nsubscripting\nsubsep\nsubsequence\nsubsetting\nsubst\nsubstr\nsubstring\nsubstrings\nsubtest\nsubtest's\nsubtests\nsubthread\nsubtree\nsubtype\nsubtypes\nsubtyping\nsucc\nsudo\nsuperclass\nsuperclasses\nsuperglobals\nsuperset\nsupplys\nsvg\nsym\nsymlink\nsymlinked\nsymlinks\nsynoptics\nsyntaxes\nsys\nsyscall\nsysopen\nsysread\nsysseek\nsyswrite\ntabstop\ntagdata\ntaketh\ntakewhile\ntanh\ntapbeforespawn\ntbd\ntcd\ntcl\ntclc\ntcp\nteardown\ntelldir\ntestactions\ntestfile\nthaa\ntheclass\nthedamian\nthid\nthreadpool\nthreadpoolscheduler\nthusly\ntiebreaking\ntimespec\ntimezoneclash\ntimezones\ntimtoady\ntimtowtdi\ntitlecase\ntitlecases\ntitlemodes\ntjd\ntkey\ntlde\ntmi\ntmp\ntmpdir\ntmtowtdi\nto's\ntoc\ntodo\ntol\ntomtom\ntomtommaps\ntoolchain\ntoolkits\ntoperl\ntopicalize\ntopicalizes\ntopicalizing\ntostring\ntotalperspective\ntranscurred\ntransformative\ntranspiler\ntres\ntrie\ntrueness\ntruish\ntruthy\ntsd\ntspec\ntt\nttc\nttq\ntty\ntui\ntuxic\ntw\ntwigil\ntwigils\ntxt\ntyd\ntypecheck\ntypechecked\ntypechecks\ntypeclasses\ntypediag\ntypename\ntypenames\ntypeobject\ntypepretense\ntyper\ntys\ntz\nub\nuc\nucd\nucfirst\nudp\nugt\nui\nuid\nuim\nuint\nulong\nulonglong\nunallowed\nunary\nunbuffered\nuncached\nuncomment\nuncontainerized\nundef\nundefine\nundefinedness\nunencodable\nunescape\nunescaped\nunflattened\nunhandled\nunhidden\nunicmp\nunicodey\nunifont\nunimatch\nunimportable\nuniname\nuninames\nuninstantiable\nunintuitive\nuniparse\nuniprop\nuniprops\nuniquefying\nunitcheck\nunival\nunivals\nunlesselse\nunlink\nunmapped\nunpolar\nunportable\nunquantified\nunrepresentable\nunsetting\nunshift\nunshrunk\nunspace\nunspaced\nunspaces\nunthrown\nuntracked\nuntrusted\nuntyped\nupcase\nupdir\nuploader\nupto\nuri\nurxvt\nuseqq\nuserblock\nuserprofile\nusr\nutf\nutil\nutils\nutime\nvals\nvalueclass\nvalueidentifier\nvalueobjat\nvardeclaration\nvariadic\nvariantlist\nvarlist\nvaya\nvcs\nvec\nvegeta\nver\nverhulst\nverifications\nviewport\nvivification\nvm\nvmarray\nvmnames\nvms\nvolcsw\nwaitpid\nwallclock\nwantarray\nwat\nwb\nwchar\nwebsocket\nwebsockets\nwfm\nwget\nwhatevercode\nwhatevercodes\nwhenevers\nwhitespace\nwhoami\nwikia\nwincompose\nwineskins\nwip\nwithoutmonkeytyping\nwithoutobject\nwithstash\nwithstashhow\nwithtype\nwix\nwne\nwo\nwombling\nwoot\nwordcase\nwormtongue\nworthington\nwraphandle\nwritehandle\nwrongorder\nws\nxaf\nxcompose\nxdefaults\nxdigit\nxeqv\nxfa\nxfb\nxfc\nxfd\nxfe\nxfeff\nxfez\nxff\nxft\nxim\nxkb\nxkbcomp\nxorg\nxt\nxtest\nyada\nyasmin\nyay\nyot\nyouens\nyy\nyyyy\nzape\nzef\nzef's\nzipi\nzl\nzoffixznet\nzp\nzwj\nzz\nÞor\n"
  },
  {
    "path": "type-graph.txt",
    "content": "[Metamodel]\n# Metamodel\nclass Metamodel::Archetypes\nrole  Metamodel::AttributeContainer\nrole  Metamodel::BUILDPLAN\nrole  Metamodel::BaseType\nrole  Metamodel::BoolificationProtocol\nrole  Metamodel::C3MRO\nclass Metamodel::ClassHOW         does Metamodel::Naming does Metamodel::Documenting does Metamodel::Versioning does Metamodel::Stashing does Metamodel::AttributeContainer does Metamodel::Finalization does Metamodel::MethodContainer does Metamodel::PrivateMethodContainer does Metamodel::MultiMethodContainer does Metamodel::RoleContainer does Metamodel::MultipleInheritance does Metamodel::DefaultParent does Metamodel::C3MRO does Metamodel::MROBasedMethodDispatch does Metamodel::MROBasedTypeChecking does Metamodel::Trusting does Metamodel::BUILDPLAN does Metamodel::Mixins does Metamodel::BoolificationProtocol\nclass Metamodel::ConcreteRoleHOW  does Metamodel::Naming does Metamodel::Versioning does Metamodel::PrivateMethodContainer does Metamodel::MethodContainer does Metamodel::MultiMethodContainer does Metamodel::AttributeContainer does Metamodel::RoleContainer does Metamodel::MultipleInheritance\nclass Metamodel::ContainerDescriptor\nclass Metamodel::CurriedRoleHOW   does Metamodel::RolePunning does Metamodel::TypePretense\nrole  Metamodel::DefaultParent\nclass Metamodel::DefiniteHOW      does Metamodel::Documenting\nclass Metamodel::BaseDispatcher\nclass Metamodel::MethodDispatcher is Metamodel::BaseDispatcher\nclass Metamodel::MultiDispatcher  is Metamodel::BaseDispatcher\nclass Metamodel::WrapDispatcher   is Metamodel::BaseDispatcher\nrole  Metamodel::Documenting\nclass Metamodel::EnumHOW          does Metamodel::Naming does Metamodel::Stashing does Metamodel::AttributeContainer does Metamodel::MethodContainer does Metamodel::MultiMethodContainer does Metamodel::RoleContainer does Metamodel::BaseType does Metamodel::MROBasedMethodDispatch does Metamodel::MROBasedTypeChecking does Metamodel::BUILDPLAN does Metamodel::BoolificationProtocol does Metamodel::Mixins\nrole  Metamodel::Finalization\nclass Metamodel::GenericHOW       does Metamodel::Naming\nclass Metamodel::GrammarHOW       is Metamodel::ClassHOW does Metamodel::DefaultParent\nrole  Metamodel::MROBasedMethodDispatch\nrole  Metamodel::MROBasedTypeChecking\nrole  Metamodel::MethodContainer\nrole  Metamodel::MethodDelegation\nrole  Metamodel::Mixins\nclass Metamodel::ModuleHOW        does Metamodel::Naming does Metamodel::Documenting does Metamodel::Versioning does Metamodel::Stashing does Metamodel::TypePretense does Metamodel::MethodDelegation\nrole  Metamodel::MultiMethodContainer\nrole  Metamodel::MultipleInheritance\nrole  Metamodel::Naming\nclass Metamodel::NativeHOW        does Metamodel::Naming does Metamodel::Documenting does Metamodel::Versioning does Metamodel::Stashing does Metamodel::MultipleInheritance does Metamodel::C3MRO does Metamodel::MROBasedMethodDispatch does Metamodel::MROBasedTypeChecking\nclass Metamodel::PackageHOW       does Metamodel::Naming does Metamodel::Documenting does Metamodel::Stashing does Metamodel::TypePretense does Metamodel::MethodDelegation\nclass Metamodel::ParametricRoleGroupHOW does Metamodel::Naming does Metamodel::Stashing does Metamodel::TypePretense does Metamodel::RolePunning does Metamodel::BoolificationProtocol\nclass Metamodel::ParametricRoleHOW does Metamodel::Naming does Metamodel::Documenting does Metamodel::Versioning does Metamodel::MethodContainer does Metamodel::PrivateMethodContainer does Metamodel::MultiMethodContainer does Metamodel::AttributeContainer does Metamodel::RoleContainer does Metamodel::MultipleInheritance does Metamodel::Stashing does Metamodel::TypePretense does Metamodel::RolePunning\nclass Metamodel::Primitives         is Any\nrole  Metamodel::PrivateMethodContainer\nrole  Metamodel::RoleContainer\nrole  Metamodel::RolePunning\nrole  Metamodel::Stashing\nclass Metamodel::StaticLexPad\nclass Metamodel::SubsetHOW        does Metamodel::Naming does Metamodel::Documenting\nrole  Metamodel::Trusting\nrole  Metamodel::TypePretense\nrole  Metamodel::Versioning\n\n[Domain-specific]\n# Attributes\nclass Attribute\n\n[Domain-specific]\nclass Telemetry\nclass Telemetry::Period is Telemetry does Associative\nclass Telemetry::Sampler\nclass Telemetry::Instrument::ThreadPool\nclass Telemetry::Instrument::Thread\nclass Telemetry::Instrument::Usage\nclass Collation\nclass Encoding\nclass Encoding::Registry\n\n\n[Domain-specific]\n# VM\nrole  Systemic\nclass Raku does Systemic\nclass Compiler does Systemic\nclass Distro\nrole Distribution\nrole Distribution::Locally does Distribution\nclass Distribution::Hash does Distribution::Locally\nclass Distribution::Path does Distribution::Locally\nclass Distribution::Resource\nclass Kernel\nclass VM                            does Systemic\n\n[Basic]\n# Base types\nclass Mu\nclass Junction                      is Mu\nclass Any                           is Mu\nclass Scalar                        is Any\nclass Variable                      is Any\nclass Proxy                         is Any\nclass Cool                          is Any\nenum  Bool                          is Int\nclass Nil                           is Cool\n\n[Basic]\n# Callables\nrole  Callable[::T = Mu]\nclass Code                                         does Callable\nclass Block                         is Code\nclass Routine                       is Block\nclass Routine::WrapHandle\nclass Sub                           is Routine\nclass Method                        is Routine\nclass Submethod                     is Routine\nclass Macro                         is Routine\nclass ForeignCode                   does Callable\n\n[Basic]\nclass HyperWhatever\nclass Whatever\nclass WhateverCode                  is Code\nenum Endian                         is Int\n\n[Basic]\nclass CallFrame\nclass Parameter\nclass Signature\nclass AST\nclass ObjAt\nclass ValueObjAt                    is  ObjAt\nclass Version\nclass Label\n\n[Domain-specific]\n# Regex and Grammars\nclass Match                         is Capture is Cool\nclass Grammar                       is Match\nclass Regex                         is Method\n\n[Basic]\n# Strings\nrole  Stringy\nclass Str                           is Cool        does Stringy\n\n[Basic]\n# Numbers\nrole  Numeric\nrole  Real                                         does Numeric\nclass Int                           is Cool        does Real\nclass Num                           is Cool        does Real\nclass Complex                       is Cool        does Numeric\nclass int                           is Int\nclass UInt\nclass atomicint                     is Int\n\n[Basic]\nrole  Rational[::NuT, ::DeT]                       does Real\nclass Rat                           is Cool        does Rational[Int, Int]\nclass FatRat                        is Cool        does Rational[Int, Int]\n\n[Basic]\n# Allomorphs\nclass Allomorph                     is Str\nclass IntStr                        is Allomorph is Int\nclass NumStr                        is Allomorph is Num\nclass RatStr                        is Allomorph is Rat\nclass ComplexStr                    is Allomorph is Complex\n\n[Basic]\n# Temporal\nrole  Dateish\nclass DateTime                                     does Dateish\nclass Date                                         does Dateish\nclass Duration                      is Cool        does Real\nclass Instant                       is Cool        does Real\n\n[Domain-specific]\n# IO\nrole  IO\nclass IO::Special                                  does IO\nclass IO::Handle\nclass IO::CatHandle                 is IO::Handle\nclass IO::ArgFiles                  is IO::CatHandle\nclass IO::Pipe                      is IO::Handle\nclass IO::Path                      is Cool        does IO\nclass IO::Path::Unix                is IO::Path\nclass IO::Path::Win32               is IO::Path\nclass IO::Path::Cygwin              is IO::Path\nclass IO::Path::QNX                 is IO::Path\nclass IO::Path::Parts               does Positional does Associative does Iterable\nrole  IO::Socket\nclass IO::Socket::INET                             does IO::Socket\nclass IO::Socket::Async\nclass IO::Socket::Async::ListenSocket              is Tap\nclass IO::Spec\nclass IO::Spec::Unix                is IO::Spec\nclass IO::Spec::Win32               is IO::Spec::Unix\nclass IO::Spec::Cygwin              is IO::Spec::Unix\nclass IO::Spec::QNX                 is IO::Spec::Unix\nclass IO::Notification\nclass IO::Notification::Change\nclass Proc\n\n[Domain-Specific]\n# Pod\nclass Pod::Config\nclass Pod::Block\nclass Pod::Block::Code              is Pod::Block\nclass Pod::Block::Comment           is Pod::Block\nclass Pod::Block::Declarator        is Pod::Block\nclass Pod::Block::Named             is Pod::Block\nclass Pod::Block::Para              is Pod::Block\nclass Pod::Block::Table             is Pod::Block\nclass Pod::FormattingCode           is Pod::Block\nclass Pod::Heading                  is Pod::Block\nclass Pod::Item                     is Pod::Block\nclass Pod::Defn                     is Pod::Block\n\n[Domain-specific]\n# CompUnit\nclass CompUnit\nclass CompUnit::Repository\nrole  CompUnit::Repository::Locally\nrole  CompUnit::Repository\nrole  CompUnit::Repository::Installable\nclass CompUnit::Repository::FileSystem does CompUnit::Repository::Locally does CompUnit::Repository\nclass CompUnit::Repository::Installation does CompUnit::Repository::Locally does CompUnit::Repository::Installable\nrole  CompUnit::PrecompilationRepository\n\n[Domain-specific]\n# S17 / Concurrency\nrole Scheduler\nclass CurrentThreadScheduler    does Scheduler\nclass ThreadPoolScheduler       does Scheduler\nclass Cancellation\nclass Promise\nenum PromiseStatus              is Int\nclass Channel\nclass Tap\nclass Supply\nclass Supplier\nclass Supplier::Preserving      is Supplier\nenum Signal                     is Int\nenum Order                      is Int\nclass Semaphore\nclass Lock\nclass Lock::Async\nclass Lock::ConditionVariable\nclass Proc::Async\nclass Thread\n\n### COLLECTIONS\n\n[Composite]\n# Collections: Iteration\nrole  Iterable\nrole  Iterator\nrole  PredictiveIterator does Iterator\nrole  PositionalBindFailover\nrole  Sequence does PositionalBindFailover\nclass Seq                           is Cool        does Iterable does Sequence\nclass RaceSeq                                      does Iterable does Sequence\nclass HyperSeq                                     does Iterable does Sequence\n\n[Composite]\n# Collections: Positional\nrole  Positional[::T = Mu]\nclass Capture\nclass Range                         is Cool        does Positional does Iterable\nclass List                          is Cool        does Positional does Iterable\nclass Array                         is List\nclass Slip                          is List\n\n[Composite]\n# Collections: Stringy\nrole  Blob[::T = uint8]             does Positional[T] does Stringy\nrole  Buf[::T = uint8]  does Blob[T]\nclass Uni                           does Positional[uint32] does Stringy\nclass utf8                          does Blob[uint8]\nclass NFD               is Uni\nclass NFC               is Uni\nclass NFKD              is Uni\nclass NFKC              is Uni\n\n[Composite]\n# Collections: Associative\nrole  Associative[::T = Mu]\nrole  Enumeration\nrole  NumericEnumeration\nrole  StringyEnumeration\nclass StrDistance is Cool\nclass Pair                                         does Associative\nclass Map                           does Iterable is Cool does Associative\nclass Stash                         is Hash\nclass PseudoStash                   is Map\nclass Hash                          is Map\nrole  QuantHash                     does Associative\nrole  Setty                         does QuantHash\nrole  Baggy                         does QuantHash\nrole  Mixy                          does Baggy\nclass Set                           does Setty\nclass SetHash                       does Setty\nclass Bag                           does Baggy\nclass BagHash                       does Baggy\nclass Mix                           does Mixy\nclass MixHash                       does Mixy\n\n\n### EXCEPTIONS\n[Exceptions]\n# Exceptions: Base\nclass Failure                       is Nil\nclass Exception\nclass Backtrace\nclass Backtrace::Frame\nclass Deprecation\n\n[Exceptions]\n# Exceptions: Misc\nclass X::AdHoc                      is Exception\nclass X::Cannot::Empty              is Exception\nclass X::Cannot::Lazy               is Exception\nclass X::Method::NotFound           is Exception\nclass X::Method::InvalidQualifier   is Exception\nclass X::OutOfRange                 is Exception\nclass X::Routine::Unwrap            is Exception\nclass X::Constructor::Positional    is Exception\nclass X::Hash::Store::OddNumber     is Exception\nclass X::Phaser::PrePost            is Exception\nclass X::Sequence::Deduction        is Exception\nclass X::Assignment::RO             is Exception\nclass X::NoDispatcher               is Exception\nclass X::Localizer::NoContainer     is Exception\nclass X::Inheritance::NotComposed   is Exception\nclass X::Inheritance::Unsupported   is Exception\nclass X::HyperOp::NonDWIM           is Exception\nclass X::Set::Coerce                is Exception\nclass X::StubCode                   is Exception\nclass X::Eval::NoSuchLang           is Exception\nclass X::Seq::Consumed              is Exception\nclass X::Symbol::Kind               is Exception\nclass X::Caller::NotDynamic         is X::Symbol::Kind\nclass X::Proc::Unsuccessful         is Exception\n\n[Exceptions]\n# Exceptions: Numbers\nclass X::Numeric::CannotConvert     is Exception\nclass X::Numeric::Real              is X::Numeric::CannotConvert\n\n[Exceptions]\n# Exceptions: Strings\nclass X::Str::Numeric               is Exception\nclass X::Str::Match::x              is Exception\nclass X::Str::Trans::IllegalKey     is Exception\nclass X::Str::Trans::InvalidArg     is Exception\n\n[Exceptions]\n# Exceptions: Buffers\nclass X::Buf::AsStr                 is Exception\nclass X::Buf::Pack                  is Exception\nclass X::Buf::Pack::NonASCII        is Exception\n\n[Exceptions]\n# Exceptions: Proc::Async\nrole X::Proc::Async                     is Exception\nclass X::Proc::Async::AlreadyStarted    does X::Proc::Async\nclass X::Proc::Async::CharsOrBytes      does X::Proc::Async\nclass X::Proc::Async::MustBeStarted     does X::Proc::Async\nclass X::Proc::Async::OpenForWriting    does X::Proc::Async\nclass X::Proc::Async::TapBeforeSpawn    does X::Proc::Async\nclass X::Proc::Async::BindOrUse         does X::Proc::Async\n[Exceptions]\n# Exceptions: Concurrency\nclass X::Promise::CauseOnlyValidOnBroken is Exception\nclass X::Promise::Vowed                  is Exception\nclass X::Channel::SendOnClosed           is Exception\nclass X::Channel::ReceiveOnClosed        is Exception\n\n[Exceptions]\n# Exceptions: Time\nrole  X::Temporal                   is Exception\nclass X::Temporal::InvalidFormat    does X::Temporal\nclass X::DateTime::InvalidDeltaUnit does X::Temporal\nclass X::DateTime::TimezoneClash    does X::Temporal\nclass X::Scheduler::CueInNaNSeconds is Exception\n\n[Exceptions]\n# Exceptions: Composition\nclass X::Export::NameClash          is Exception\nclass X::Import::MissingSymbols     is Exception\nclass X::Composition::NotComposable is Exception\nclass X::Mixin::NotComposable       is Exception\n\n[Exceptions]\n# Exceptions: Type Checks\nclass X::TypeCheck                  is Exception\nclass X::TypeCheck::Binding         is X::TypeCheck\nclass X::TypeCheck::Return          is X::TypeCheck\nclass X::TypeCheck::Assignment      is X::TypeCheck\nclass X::TypeCheck::Splice          is X::TypeCheck\n\n[Exceptions]\n# Exceptions: Control Flow\nclass X::ControlFlow                is Exception\nclass X::ControlFlow::Return        is X::ControlFlow\n\n[Exceptions]\n# Exceptions: IO\nrole  X::OS                         is Exception\nrole  X::IO                                        does X::OS\nclass X::IO::Rename                 is Exception   does X::IO\nclass X::IO::Move                   is Exception   does X::IO\nclass X::IO::Copy                   is Exception   does X::IO\nclass X::IO::Mkdir                  is Exception   does X::IO\nclass X::IO::Chdir                  is Exception   does X::IO\nclass X::IO::Dir                    is Exception   does X::IO\nclass X::IO::Cwd                    is Exception   does X::IO\nclass X::IO::Rmdir                  is Exception   does X::IO\nclass X::IO::Link                   is Exception   does X::IO\nclass X::IO::Unlink                 is Exception   does X::IO\nclass X::IO::Symlink                is Exception   does X::IO\nclass X::IO::Chmod                  is Exception   does X::IO\nclass X::IO::DoesNotExist           is Exception   does X::IO\n\n[Exceptions]\n# Exceptions: Compile-Time\nrole  X::Comp                       is Exception\nclass X::Comp::Group                is Exception\nclass X::Anon::Augment                             does X::Comp\nclass X::Anon::Multi                               does X::Comp\nclass X::Attribute::NoPackage                      does X::Comp\nclass X::Attribute::Package                        does X::Comp\nclass X::Attribute::Undeclared      is X::Undeclared\nclass X::Attribute::Required                  is Exception does MOP\nclass X::Augment::NoSuchType                       does X::Comp\nclass X::Bind                       is Exception\nclass X::Bind::NativeType                          does X::Comp\nclass X::Bind::Slice                is Exception\nclass X::Bind::ZenSlice             is X::Bind::Slice\nclass X::Comp::AdHoc                is X::AdHoc    does X::Comp\nclass X::Comp::NYI                  is X::NYI      does X::Comp\nclass X::Trait::NotOnNative         is Exception\nclass X::Comp::Trait::NotOnNative   is X::Trait::NotOnNative does X::Comp\nclass X::Trait::Scope               is Exception\nclass X::Comp::Trait::Scope         is X::Trait::Scope does X::Comp\nclass X::Trait::Unknown             is Exception\nclass X::Comp::Trait::Unknown       is X::Trait::Unknown does X::Comp\nclass X::Declaration::Scope                        does X::Comp\nclass X::Declaration::Scope::Multi  is X::Declaration::Scope\nclass X::Does::TypeObject           is Exception\nclass X::EXPORTHOW::Conflict                       does X::Comp\nclass X::EXPORTHOW::InvalidDirective               does X::Comp\nclass X::EXPORTHOW::NothingToSupersede             does X::Comp\nclass X::Import::OnlystarProto                     does X::Comp\nclass X::Import::Redeclaration                     does X::Comp\nclass X::Method::Private::Permission               does X::Comp\nclass X::Method::Private::Unqualified              does X::Comp\nclass X::NYI                        is Exception\nclass X::Obsolete                                  does X::Comp\nclass X::Package::Stubbed                          does X::Comp\nclass X::Parameter::Default                        does X::Comp\nclass X::Parameter::InvalidType                    does X::Comp\nclass X::Parameter::MultipleTypeConstraints        does X::Comp\nclass X::Parameter::Placeholder                    does X::Comp\nclass X::Parameter::Twigil                         does X::Comp\nclass X::Parameter::WrongOrder                     does X::Comp\nclass X::Phaser::Multiple                          does X::Comp\nclass X::Placeholder::Block                        does X::Comp\nclass X::Placeholder::Mainline      is X::Placeholder::Block\nclass X::Placeholder::NonPlaceholder               does X::Comp\nclass X::PoisonedAlias                             does X::Comp\nclass X::PseudoPackage::InDeclaration              does X::Comp\nclass X::Redeclaration                             does X::Comp\nclass X::Redeclaration::Outer                      does X::Comp\nclass X::Role::Initialization       is Exception\nclass X::Signature::NameClash                      does X::Comp\nclass X::Signature::Placeholder                    does X::Comp\nclass X::Undeclared                                does X::Comp\nclass X::Undeclared::Symbols                       does X::Comp\nclass X::Value::Dynamic                            does X::Comp\nclass X::Dynamic::NotFound                         is Exception\n\n[Exceptions]\n# Exceptions: Syntax\nrole  X::Pod\nrole  X::Syntax                                    does X::Comp\nclass X::Backslash::NonVariableDollar              does X::Syntax\nclass X::Backslash::UnrecognizedSequence           does X::Syntax\nclass X::Syntax::Argument::MOPMacro                does X::Syntax\nclass X::Syntax::Augment::Illegal                  does X::Syntax\nclass X::Syntax::BlockGobbled                      does X::Syntax\nclass X::Syntax::CannotMeta                        does X::Syntax\nclass X::Syntax::Extension::Null                   does X::Syntax\nclass X::Syntax::KeywordAsFunction                 does X::Syntax\nclass X::Syntax::Malformed::Elsif                  does X::Syntax\nclass X::Syntax::NonAssociative                    does X::Syntax\nclass X::Syntax::Perl5Var                          does X::Syntax\nclass X::Syntax::Regex::MalformedRange             does X::Syntax\nclass X::Syntax::Regex::NullRegex                  does X::Syntax\nclass X::Syntax::Regex::SpacesInBareRange          does X::Syntax\nclass X::Syntax::Regex::UnrecognizedMetachar       does X::Syntax\nclass X::Syntax::Regex::Unspace                    does X::Syntax\nclass X::Syntax::Regex::Unterminated               does X::Syntax\nclass X::Syntax::AddCategorical::TooFewParts       does X::Syntax\nclass X::Syntax::AddCategorical::TooManyParts      does X::Syntax\nclass X::Syntax::Augment::WithoutMonkeyTyping      does X::Syntax\nclass X::Syntax::Comment::Embedded                 does X::Syntax\nclass X::Syntax::Confused                          does X::Syntax\nclass X::Syntax::Extension::Category               does X::Syntax\nclass X::Syntax::InfixInTermPosition               does X::Syntax\nclass X::Syntax::Malformed                         does X::Syntax\nclass X::Syntax::Missing                           does X::Syntax\nclass X::Syntax::Name::Null                        does X::Syntax\nclass X::Syntax::NegatedPair                       does X::Syntax\nclass X::Syntax::NoSelf                            does X::Syntax\nclass X::Syntax::Number::RadixOutOfRange           does X::Syntax\nclass X::Syntax::P5                                does X::Syntax\nclass X::Syntax::Pod::BeginWithoutEnd              does X::Syntax does X::Pod\nclass X::Syntax::Pod::BeginWithoutIdentifier       does X::Syntax does X::Pod\nclass X::Syntax::Regex::Adverb                     does X::Syntax\nclass X::Syntax::Regex::SolitaryQuantifier         does X::Syntax\nclass X::Syntax::Reserved                          does X::Syntax\nclass X::Syntax::Self::WithoutObject               does X::Syntax\nclass X::Syntax::Signature::InvocantMarker         does X::Syntax\nclass X::Syntax::Term::MissingInitializer          does X::Syntax\nclass X::Syntax::UnlessElse                        does X::Syntax\nclass X::Syntax::Variable::IndirectDeclaration     does X::Syntax\nclass X::Syntax::Variable::Match                   does X::Syntax\nclass X::Syntax::Variable::Numeric                 does X::Syntax\nclass X::Syntax::Variable::Twigil                  does X::Syntax\nclass X::Syntax::VirtualCall                       does X::Syntax\n\n[Exceptions]\n# Exceptions: Control Exceptions\nrole  X::Control                    is Exception\nclass CX::Next                                     does X::Control\nclass CX::Redo                                     does X::Control\nclass CX::Redo                                     does X::Control\nclass CX::Done                                     does X::Control\nclass CX::Last                                     does X::Control\nclass CX::Return                                   does X::Control\nclass CX::Emit                                     does X::Control\nclass CX::Take                                     does X::Control\nclass CX::Warn                                     does X::Control\nclass CX::Succeed                                  does X::Control\nclass CX::Proceed                                  does X::Control\n\n[Core]\nmodule Test\n"
  },
  {
    "path": "util/clean-spell",
    "content": "#!/usr/bin/env raku\n\n# Remove words in t/pws/*.pws that are no longer needed\n# * Bug fixes in the spell checker have removed the need\n#   to check certain words.\n# * Edits to the docs themselves no longer use some words.\n#\n# set UTIL_CLEAN_SPELL_REGEX environment variable to\n# only check words that match\n# that regex.\n#\n# set UTIL_CLEAN_SPELL_LAST environment variable to\n# note the last word that was processed. The\n# script will continue with the next word\n#\n# This test is slow, this gives\n# us an easy way to chunk the test runs.\n#\n# Try to be clever and only test files that match the word,\n# even if it's a partial match to speed up the testing.\n#\n# Trust but verify: make sure you rerun the entire spell check\n# after letting this program update the .pws files\n\nuse File::Temp;\n\nuse RakuDoc::Test::Files;\nuse Pod::Cache;\n\nmy $regex = %*ENV<UTIL_CLEAN_SPELL_REGEX> // \".\";\nmy $last  = %*ENV<UTIL_CLEAN_SPELL_LAST> // \"\";\n\n# How many files to check at a time?\nmy $at-a-time = 4;\n\n# Check the same files as t/23-aspell.rakutest does by default...\nmy @files = RakuDoc::Test::Files.documents.grep({not $_ ~~ / 'README.' .. '.md' /});\n\n# ... but use pre-generated/rendered Pod6 files for our quick search.\nnote \"Caching rakudoc files...\";\n@files = @files.map({\n    $_.ends-with('.rakudoc') ?? Pod::Cache.cache-file($_) !! $_;\n});\n\nfor <t/pws/words.pws t/pws/code.pws> -> $dict {\n    for $dict.IO.lines -> $word {\n        next unless $word gt $last;\n        next unless $word ~~ /<$regex>/;\n        next if $word.starts-with('personal_ws-1.1 en');\n        note \"Testing $dict / $word \";\n\n        my $proc = run( 'grep', '-li', $word, |@files, :out);\n        my $output = $proc.out.slurp;\n\n        # remove word, keep pointer to backup lexicon\n        my $backup = erase-word($dict, $word);\n\n        if $output eq '' {\n            note \"\\tnot found, removing.\";\n        } else {\n            my @min-files = $output.lines;\n            note \"\\tfound in {+@min-files} files, testing.\";\n            my $all-ok = True;\n            # use rotor, but get the partial chunk first\n            # so we can fail slightly faster\n            for @min-files.reverse.rotor($at-a-time, :partial).reverse -> @test-files {\n                note \"\\t\\t\" ~ @test-files.join(\"\\n\\t\\t\");\n                my $proc = run( 't/23-aspell.rakutest', |@test-files.reverse, :out, :err);\n                if $proc.exitcode != 0 {\n                    $all-ok = False;\n                    note \"\\taspell test failed, keeping word\";\n                    run('mv', $backup, $dict);\n                    last; # no need to test other files\n                }\n            }\n            if $all-ok {\n                note \"\\taspell test passed, removing word\";\n                # We removed the word to do the test, so just leave as is.\n            }\n        }\n    }\n}\n\nsub erase-word($dict, $word) {\n    # Create a temp copy of the lexicon that doesn't contain the word\n    my ($tmp_fname, $tmp_io) = tempfile;\n    for $dict.IO.lines -> $i {\n        $tmp_io.say($i) unless $i eq $word;\n    }\n    $tmp_io.close;\n\n    # backup the dictionary file\n    my ($backup_fname, $bkp_io) = tempfile;\n    $bkp_io.close;\n\n    run('cp', $dict, $backup_fname);\n\n    # try the updated copy\n    run('mv', $tmp_fname, $dict);\n\n    # return a link to the last good copy of the file in case caller needs to restore it.\n    return $backup_fname;\n}\n"
  },
  {
    "path": "util/create-brackets-table.raku",
    "content": "#!/usr/bin/env raku\n\n# TODO\n#   + get desired exit behavior from Coke\n#   + settle on table name and output file name\n\n\nif !@*ARGS {\n    say qq:to/HERE/;\n    Usage: {$*PROGRAM.IO.basename} go [refresh][debug]\n\n    Writes the HLL::Grammar '\\$brackets' chars into a Pod6 table.\n\n    The HLL::Grammar.nqp file as source is updated if it\n    is not found in /util or the 'refresh' option is used.\n\n    You may also define NQP_SRC to use another copy of NQP.\n    Ensure that path definition ends at 'nqp' as the checked\n    out copy, e.g., 'NQP_ SRC=/some/path/nqp'.\n    HERE\n    exit;\n}\n\nmy $refresh       = 0;\nmy $want-original = 0;\nmy $debug         = 0;\n\nfor @*ARGS {\n    when /^ r/ { ++$refresh }\n    when /^ d/ { ++$debug }\n}\n\n# The output table file:\nmy $repopath = $*PROGRAM.IO.absolute.IO.parent(2);\nmy $fdir1 = $repopath ~ \"/doc/Language\";\nmy $f1    = \"$fdir1/brackets.rakudoc\";\n\n# The local copy of HLL::Grammar.nqp:\nmy $fdir2 = $repopath ~ \"/util\";\nmy $f2    = \"$fdir2/Grammar.nqp\";\n\nif $debug {\n    say \"DEBUG: paths:\";\n    say \"  output table: $f1\";\n    say \"  Grammar.nqp : $f2\";\n    say \"DEBUG exit\"; exit;\n}\n\n# This array is defined dynamically by reading the source\n# file at https://github.com/Raku/nqp/src/HLL/Grammar.nqp.\nmy @bracket-chars = get-brackets :grammar-file($f2), :$refresh, :$debug;\n\nwrite-brackets-rakudoc-file :table-file($f1), :@bracket-chars, :$debug;\n\nsay \"Normal end.\";\nmy $of = $f1.IO.relative;\nsay \"See output file '$of'\";\n\nsub write-brackets-rakudoc-file(:$table-file, :@bracket-chars!, :$reorder?, :$debug?) {\n\n    # The pipe bracket is used to enclose the char pairs in the table.\n    # They must be escaped for use on doc site\n    my $P = '\\\\|';\n\n    my $fh = open $table-file, :w;\n\n    $fh.print: qq:to/HERE/;\n    =begin pod :kind(\"Language\") :subkind(\"Language\") :category(\"reference\")\n\n    =TITLE Brackets\n\n    =SUBTITLE Valid opening/closing paired delimiters\n\n    The following table shows all of the valid graphemes usable as opening\n    and closing paired delimiters in such constructs as I<Pod6 declarator\n    blocks>.  Note they are shown between pipe symbols so the extra bounding\n    space for any wide characters can be seen.\n\n    The data source for the table is the I<\\$brackets> string defined in the\n    I<HLL::Grammar> module in the I<github.com/Raku/nqp> repository.\n\n    The data are arranged in the order found in the source string.\n    Each opening bracket is shown in its printed form followed by its\n    paired closing bracket. Each pair is then followed by its codepoints.\n    There are two sets of bracket pairs shown per table row.\n\n    =begin table :caption<Bracket pairs>\n     LChar | RChar | LHex  | RHex  | LChar | RChar | LHex  | RHex\n    ======+======+======+======+======+======+======+======\n    HERE\n\n    my $n = @bracket-chars.elems;\n    my $even = $n mod 2 ?? False !! True;\n    print \"Found $n bracket pair elements ({$n div 2} pairs, \" if $debug;\n    if $debug {\n        if $even {\n            say \"an even number of elements).\"\n        }\n        else {\n            say \"an odd number of elements).\"\n        }\n    }\n\n    my $inc = 4; # two pairs per table row\n    # We need to march through the list $inc elements at a time\n    loop (my $i = 0;  $i < $n; $i += $inc)  {\n        my $i0 = $i;\n        my $i1 = $i+1;\n        my $i2 = $i+2;\n        my $i3 = $i+3;\n\n        my ($ai, $bi, $ci, $di); # Int value\n        my ($as, $bs, $cs, $ds); # Str value\n        my ($ap, $bp, $cp, $dp); # Str value enclosed in pipes\n        my ($ax, $bx, $cx, $dx); # hex value\n\n        $ai = $i0 < $n ?? @bracket-chars[$i0] !! '';\n        $bi = $i1 < $n ?? @bracket-chars[$i1] !! '';\n        $ci = $i2 < $n ?? @bracket-chars[$i2] !! '';\n        $di = $i3 < $n ?? @bracket-chars[$i3] !! '';\n\n        $as = $ai ?? $ai.chr !! '';\n        $bs = $bi ?? $bi.chr !! '';\n        $cs = $ci ?? $ci.chr !! '';\n        $ds = $di ?? $di.chr !! '';\n\n        # display the Int values as four-char hex, e.g. 0xAAAA\n        $ax = $ai ?? int2hex($ai) !! '';\n        $bx = $bi ?? int2hex($bi) !! '';\n        $cx = $ci ?? int2hex($ci) !! '';\n        $dx = $di ?? int2hex($di) !! '';\n\n        $ap = $ai ?? sprintf(\"%s%s%s\", $P, $as, $P) !! '';\n        $bp = $bi ?? sprintf(\"%s%s%s\", $P, $bs, $P) !! '';\n        $cp = $ci ?? sprintf(\"%s%s%s\", $P, $cs, $P) !! '';\n        $dp = $di ?? sprintf(\"%s%s%s\", $P, $ds, $P) !! '';\n\n        # first pair\n        $fh.print: \"$ap | $bp | $ax | $bx | \";\n        # the second pair may not exist on the last row\n        if $cp {\n            $fh.say:   \"$cp | $dp | $cx | $dx\";\n        }\n        else {\n            $fh.say:   \"$cp | $dp | $cx |\";\n        }\n\n        # underline first pair\n        $fh.print: \"--------+---------+---------+---------+\";\n        # underline second pair\n        $fh.say:   \"--------+---------+---------+---------\";\n\n        last if !$di;\n    }\n\n    $fh.print: qq:to/HERE/;\n    =end table\n    Z<This file was created by program '/util/{$*PROGRAM.IO.basename}'>\n    \\n=end pod\n    HERE\n\n    $fh.close;\n}\n\nsub int2hex($i --> Str) {\n    # Convert an Int to hex format\n    # Prefer upper-case hex letters\n    my $s = sprintf '%#.4X', $i;\n    # Prefer lower-case 'x' for string representation\n    $s ~~ s/X/x/;\n    $s\n}\n\nsub get-brackets(:$grammar-file, :$refresh!, :$debug! --> List) {\n    # Extracts the data from the nqp/HLL/Grammar.nqp file.\n    use Cro::HTTP::Client;\n\n    # The local copy of the nqp repo's source file\n    my $f = $grammar-file;\n\n    if $refresh or not $f.IO.r {\n        # See if there is a local checkout of NQP\n        my $end-path = \"/src/HLL/Grammar.nqp\";\n        if %*ENV<NQP_HOME>:exists {\n            $f = %*ENV<NQP_HOME> ~ $end-path;\n        }\n        elsif %*ENV<NQP_SRC>:exists {\n            $f = %*ENV<NQP_SRC> ~ $end-path;\n        }\n        # Otherwise, get it from Github\n        else {\n            my $ua = Cro::HTTP::Client.new;\n            my $uri = \"https://raw.githubusercontent.com/Raku/nqp/main\" ~ $end-path;\n            my $response = await $ua.get: $uri;\n            if $response.is-success {\n                spurt $f, $response.content;\n            }\n            else {\n                # TODO determine desired failure response\n                die $response.status-line;\n            }\n        }\n    }\n\n    my $bstr = '';\n    for $f.IO.lines -> $line {\n        # first line of interest:\n        #     my $brackets := \"\\x[0028]\\x[0029]\\x[003C]\\x[003E]\\x[005B]\\x[005D]\" ~\n        # an intermediate line:\n        #     \"\\x[3016]\\x[3017]\\x[3018]\\x[3019]\\x[301A]\\x[301B]\\x[301D]\\x[301E]\" ~\n        # last line of interest: note no ending tilde:\n        #     \"\\x[2E24]\\x[2E25]\\x[27EC]\\x[27ED]\\x[2E22]\\x[2E23]\\x[2E26]\\x[2E27]\"\n\n        if $line ~~ /^:i \\h* my \\h+ '$brackets' \\h+ ':=' \\h* '\"'\n            # the bracket string starts on this line\n                       (<[\\\\\\[\\]xa..f0..9]>+)\n                     '\"' \\h+ '~' \\h*\n                    $/ {\n            $bstr ~= ~$0\n        }\n        elsif $line ~~ /^:i \\h* '\"'\n            # the bracket string continues on this line (note ending tilde')\n                       (<[\\\\\\[\\]xa..f0..9]>+)\n                       '\"' \\h+ '~' \\h*\n                       $/ {\n            $bstr ~= ~$0\n        }\n        elsif $line ~~ /^:i \\h* '\"'\n            # the bracket string ends on this line (note NO ending tilde')\n                       (<[\\\\\\[\\]xa..f0..9]>+)\n                       '\"' \\h*\n                       $/ {\n            $bstr ~= ~$0;\n            last\n        }\n    }\n\n    # say \"See \\$bstr: $bstr\";\n    #    \\x[FF5B]\\x[FF5D]\\x[FF5F]\\x[FF60]\\x[FF62]\\x[FF63]\\x[27EE]\\x[27EF]\n    # turn the string into an int array that looks like this:\n    #    my @arr = [ 0xFF5B, 0xFF5D, 0xFF5F, 0xFF60, 0xFF62, 0xFF63, 0x27EE, 0x27EF ];\n\n    my @bracket-chars = [];\n    my @b = $bstr.comb;\n    while @b.elems {\n        my $c = '';\n        for 1..8 {\n            $c ~= @b.shift;\n        }\n        say \"word: '$c'\" if $debug;\n        # make the 8 chars into an int\n        #    transform this form: \\x[FF5B]\n        #    into this form     : 0xFF5B\n        my $b = $c;\n        $b ~~ s:g/\\\\/0/;\n        $b ~~ s:g/\\[//;\n        $b ~~ s:g/\\]//;\n        say \"    word: '$b'; as Int: {$b.Int}\" if $debug;\n        @bracket-chars.push: $b.Int;\n    }\n    @bracket-chars\n}\n"
  },
  {
    "path": "util/dumpast.raku",
    "content": "#!/usr/bin/env raku\n\n# Generate the rakudoc AST for a given file\n\nunit sub MAIN($file);\n\n.say for $file.IO.slurp.AST.rakudoc\n\n"
  },
  {
    "path": "util/github-action-test.sh",
    "content": "#!/bin/bash -\n\n# This script is run by the step 'Run tests' in the GitHub workflow \"test\"\n# See .github/workflows/test.yml\n\nset -ex\nset -o pipefail\n\n: ${TEST_IMAGE:=docker.io/coke/rakudo-docs-test:latest}\n: ${RAKU_DOC_TEST_VERBOSE:=1}\n\n# this default value allows one to run a command like\n# ./util/github-action-test.sh\n: ${GITHUB_WORKSPACE:=${PWD}}\n\n# if no argument is given run tests from t/\nif [[ $# -eq 0 ]]; then\n  set -- t\nfi\n\ndocker run -t \\\n  -v \"${GITHUB_WORKSPACE}\":/test:Z \\\n  -w \"/test\" \\\n  --entrypoint env \\\n  \"${TEST_IMAGE}\" \\\n  RAKU_DOC_TEST_VERBOSE=${RAKU_DOC_TEST_VERBOSE} \\\n  RAKULIB=. \\\n  TEST_FILES=\"${TEST_FILES}\" \\\n  prove6 \"$@\"\n"
  },
  {
    "path": "util/missing-types.raku",
    "content": "#!/usr/bin/env raku\n\n# This script parses the type-graph.txt file and checks\n# the existence of the corresponding rakudoc file for most entries\n# skips: Metamodel and PROCESS types\n\nuse lib 'lib';\nuse Doc::TypeGraph;\n\n# These are core but not loaded by default.\nuse Telemetry;\nuse Test;\n\nmy $t = Doc::TypeGraph.new-from-file('type-graph.txt');\n\nfor $t.sorted  -> $type {\n    next if $type.name.index('Metamodel').defined || $type.name eq 'PROCESS';\n    my $actual = try ::($type.name);\n    printf \"%-40s not defined in this version of Raku\\n\", $type.name()\n        if $actual === Any and $type.name ne \"Any\" | \"Failure\" | \"Nil\";\n    next unless $actual.^name eq $type.name;\n    my $filename = 'doc/Type/' ~ $type.name.subst(:g, '::', '/') ~ '.rakudoc';\n    printf \"%-40s not found in documentation\\n\", $type.name() unless $filename.IO.e;\n    CATCH { default { } }\n}\n"
  },
  {
    "path": "util/new-type.raku",
    "content": "#!/usr/bin/env raku\n\n# If the documentation for a type does not exist, create the skeleton of the doc\n# $ raku util/new-type.raku --kind=role Some::Role\n# this creates the file doc/Type/Some/Role.rakudoc\n\nsub MAIN($typename, :$kind='class') {\n    my @path-chunks =  $typename.split('::');\n    my $filename = @path-chunks.pop ~ '.rakudoc';\n    my $path = 'doc/Type';\n    for @path-chunks -> $c {\n        $path ~= \"/$c\";\n        unless $path.IO.d {\n            mkdir $path.IO.mkdir;\n        }\n    }\n\n    $path ~= \"/$filename\";\n    if $path.IO ~~ :e {\n        say \"The file $path already exists.\";\n        exit 1;\n    }\n    my $fh = open $path, :x;\n\n    spurt $fh, Q:s:to/HEADER/;\n        =begin pod\n\n        =TITLE $kind $typename\n\n        =SUBTITLE ...\n\n            $kind $typename is SuperClass { ... }\n\n        Synopsis goes here\n\n        HEADER\n    spurt $fh, Q:c:to/BODY/;\n\n        =head1 Methods\n\n        =head2 method flurb\n\n            method flurb({$typename}:D: *@args --> Str)\n\n        method description here\n\n        =end pod\n\n        BODY\n    $fh.close;\n    say \"'$path' written\";\n    say \"(remember to 'git add $path')\";\n}\n"
  },
  {
    "path": "util/perl-nbsp.raku",
    "content": "#!/usr/bin/env raku\n\n=begin overview\n\nRun this script to correct files to use no break spaces when\nxt/perl-nbsp.rakutest fails.\n\n=end overview\n\nuse lib 'lib';\nuse RakuDoc::Test::Files;\n\nenum Syntax <CodeDoc TextDoc>;\n\nmy $degree = %*ENV<UTIL_THREADS> // 2;\n\nsub check-line(Str $line, Syntax $state) {\n    given $line {\n        when / ^ '=begin code' / { CodeDoc }\n        when / ^ '=for code' /   { CodeDoc }\n        when / ^ '=end code' /   { TextDoc }\n        when / ^ '=' \\w+ /       { TextDoc }\n        when / ^ \\s ** 4 /       { CodeDoc }\n        default                  { $state  }\n    }\n}\n\nmulti sub replace-spaces(Str $file) {\n    nextwith $file.IO;\n}\nmulti sub replace-spaces(IO::Path $file) {\n    my Syntax $state    = TextDoc;\n    my Bool   $modified = False;\n    my Bool   $split    = False;\n    my Str    @in       = $file.lines;\n    my Str    @out      = @in.hyper(:$degree).map(anon sub (Str $in-line) {\n        return $in-line unless $in-line;\n\n        $state = check-line $in-line, $state;\n        # Perl and Raku should keep regular spaces in code.\n        return $in-line if $state == CodeDoc;\n\n        my Str $out-line = $in-line.clone;\n        if $split {\n            $out-line ~~ s/ ^ \\x[0020]? ( 6 | 5 ) /\\x[00A0]$0/;\n            $split = False;\n        } else {\n            $out-line ~~ s/ 'Perl' [ \\x[0020]+ | \\x[00A0] ]? $ /Perl/;\n            $split = True if $/;\n        }\n\n        $out-line ~~ s:g/ 'Perl' \\x[0020] ( 6 | 5 ) /Perl\\x[00A0]$0/;\n        $modified = True if $out-line ne $in-line;\n        $out-line\n    });\n\n    if $modified {\n        say \"Corrected mentions of Perl and Raku to use NBSP in '$file'.\";\n        $file.spurt(@out.join(\"\\n\"), :close);\n    }\n}\n\nmulti sub MAIN() {\n    Test-Files.documents.race(:$degree).map(&replace-spaces);\n}\nmulti sub MAIN(Str $file) {\n    die \"$file does not exist!\" unless $file.IO.e;\n    die \"$file is a directory!\" if $file.IO.d;\n    replace-spaces $file.IO;\n}\n"
  },
  {
    "path": "util/sort-words.raku",
    "content": "#!/usr/bin/env raku\n\n=begin overview\n\nSort words files as expected by t/24-words.rakutest\n\n=end overview\n\nmy $word-io = $*PROGRAM.parent.parent.child('t/pws/words.pws').IO;\nmy $code-io = $*PROGRAM.parent.parent.child('t/pws/code.pws').IO;\n\nmy @word = $word-io.lines;\nmy @code = $code-io.lines;\n\nmy $header = @word.shift;\n\nmy $word-out = $word-io.open(:w);\n$word-out.say: $header;\n$word-out.say: @word.sort.unique.join(\"\\n\");\n\nmy $code-out = $code-io.open(:w);\n$code-out.say: @code.sort.unique.join(\"\\n\");\n"
  },
  {
    "path": "util/test-modified.sh",
    "content": "#!/bin/sh\n\n# This script will run make xtest on any files in the repository that have not yet been committed\n# use before 'git commit' to ensure your commit doesn't require correction.\n\nexport TEST_FILES=`git status --porcelain | egrep '^( M|A |AM)' | awk '{print $2}'`\n\n[ \"$TEST_FILES\" = \"\" ] && echo \"nothing to test\"\n[ \"$TEST_FILES\" != \"\" ] && RAKULIB=. make xtest\n"
  },
  {
    "path": "util/test-website.raku",
    "content": "#!/usr/bin/env raku\n\nmy $dir = \"doc-website\".IO;\n\nif $dir.d {\n   run(<git pull --rebase>, :cwd($dir));\n} else {\n    run(<git clone git@github.com:Raku/doc-website.git>);\n}\n\nmy @files = $dir.child('Website').child('structure-sources').IO.dir;\n%*ENV<TEST_FILES>=@files.join(' ');\n\nrun(<make xtest>);\n"
  },
  {
    "path": "util/unskip.raku",
    "content": "#!/usr/bin/env raku\n\nuse File::Temp;\n\nuse lib 'lib';\nuse RakuDoc::Test::Files;\n\n=begin overview\n\nMany examples in the docs are tagged with :skip-test. This utility\nchecks to see if the code can be run with our usual tester, and if\nthat fails, with the C<:solo> attribute; If either of these work,\nthe file is modified in place, allowing the developer to inspect\nthe changes to the C<doc/> directory and commit the updated files.\n\nThis utility will also attempt to remove C<:solo>'s from tests that\nare being run; sometimes the attribute is copied unecessarily to a\nnew test. Because it's longer to run the test with this attribute,\nwe want to avoid it if possible.\n\nAs with C<xt/> tests, you can limit the files checked with the\nC<TEST_FILES> environment variable or by passing the named files as arguments\n\n=end overview\n\n# Return a list of skippable positions in this file.\nsub get-tries($file) {\n    say \"$file: Calculating tests to re-try\";\n    my @tries;\n    # $line-no is 0-based\n    for $file.IO.slurp.lines.kv -> $line-no, $line {\n        if $line ~~ / ^ \\s* '=' .* << 'code' >> .* ':skip-test'/ {\n            @tries.push: {\n                'line' => $line-no,\n                'type' => 'skip'\n            }\n        }\n        elsif $line ~~ / ^ \\s* '=' .* << 'code' >> .* ':solo'/ {\n            @tries.push: {\n                'line' => $line-no,\n                'type' => 'solo'\n            }\n        }\n    }\n    return @tries;\n}\n\nmy $test-script = 'xt/examples-compilation.rakutest';\n\n# Can this file pass the examples compilation test?\nsub run-ok($file) {\n    my $proc = Proc::Async.new($*EXECUTABLE, $test-script, $file, :out, :err);\n\n    # ignore the output, just care about the exitcode\n    $proc.stdout.tap: {;};\n    $proc.stderr.tap: {;};\n\n    return $proc.start.result.exitcode == 0;\n}\n\nsub remove-skip($file, $skip-pos, :$solo=False) {\n    my ($test-file, $test-io) = tempfile(:suffix<.rakudoc>, :!unlink);\n\n    for $file.IO.slurp.lines.kv -> $pos, $line  {\n        if $pos == $skip-pos {\n            if $line ~~ / (.*) \\s+ ':skip-test' / {\n                $test-io.print: ~$0;\n                if $solo {\n                    $test-io.print: ' :solo';\n                }\n                $test-io.print: \"\\n\";\n            } else {\n                say \"$file: Unexpected error occurred\";\n                dd $test-file, $pos, $skip-pos, $line;\n            }\n        } else {\n            $test-io.say: $line;\n        }\n    }\n    $test-io.close;\n\n    return $test-file;\n}\n\nsub remove-solo($file, $skip-pos) {\n    my ($test-file, $test-io) = tempfile(:suffix<.rakudoc>, :!unlink);\n\n    for $file.IO.slurp.lines.kv -> $pos, $line  {\n        if $pos == $skip-pos {\n            if $line ~~ / (.*) \\s+ ':solo' / {\n                $test-io.print: ~$0;\n                $test-io.print: \"\\n\";\n            } else {\n                say \"$file: Unexpected error occurred\";\n                dd $test-file, $pos, $skip-pos, $line;\n            }\n        } else {\n            $test-io.say: $line;\n        }\n    }\n    $test-io.close;\n\n    return $test-file;\n}\n\nRakuDoc::Test::Files.pods.race(:batch(1)).map: -> $file {\n    say \"$file: PROCESSING\";\n\n    my @tries = get-tries($file);\n\n    if !@tries {\n        say \"$file: no :skip-test/:solo present\";\n        next;\n    }\n\n    # Make sure the file runs without error as is.\n    if !run-ok($file) {\n        say \"$file: does not pass in its current state\";\n        next;\n    }\n    my $skip-pos = 0;\n    my $good-file = $file;\n\n    while $skip-pos < @tries.elems {\n        # For each skip-test, test a run that doesn't include the skip.\n        my $skip-line = @tries[$skip-pos]<line>;\n        my $working-file;\n\n        if @tries[$skip-pos]<type> eq 'solo' {\n            say \"$file: Trying to !solo at {$skip-line+1}\";\n            $working-file = remove-solo($good-file, $skip-line);\n            if run-ok($working-file) {\n                say \"$file: :solo not needed\";\n                $good-file = $working-file;\n                @tries = get-tries($good-file);\n                # Leave skip-pos where it was, as that :solo has been removed.\n             } else {\n                say \"$file: :solo still needed\";\n                $skip-pos++;\n             }\n        } elsif @tries[$skip-pos]<type> eq 'skip' {\n            $working-file = remove-skip($good-file, $skip-line);\n\n            say \"$file: trying to unskip at {$skip-line+1}\";\n\n            if run-ok($working-file) {\n                say \"$file: :skip-test not needed\";\n                # Point to this new good copy as our good version\n                $good-file = $working-file;\n                @tries = get-tries($good-file);\n                # Leave skip-pos where it was, as that position has been removed.\n            } else {\n                # If that didn't work, test it with :solo\n                say \"$file: Trying to :solo at {$skip-line+1}\";\n                $working-file = remove-skip($good-file, $skip-line, :solo);\n                if run-ok($working-file) {\n                    say \"$file: :skip-test switched to :solo\";\n                    # Point to this new good copy as our good version\n                    $good-file = $working-file;\n                    @tries = get-tries($good-file);\n                    # Leave skip-pos where it was, as that position has been removed.\n                } else {\n                    say \"$file: :skip-test still required\";\n                    # If that didn't work, then we try the next position\n                    $skip-pos++;\n                }\n            }\n        }\n    }\n    # Put our last good version of the file back.\n    copy $good-file, $file;\n}\n\nsay \"Completed - please use `git status` to see any updated files\";\n"
  },
  {
    "path": "util/update-and-test",
    "content": "#!/usr/bin/env raku\n\n=begin overview\n\nNot everyone runs the extended test suite; this gives developers the ability\nto test as they go; it updates the repository, runs xtest only on those\nfiles that have changed in that update, and leaves a local C<retest> script\nthat can be rerun against those changes until xtest is clean.\n\nNote that test files are allowed to skip certain tests if they are run on a restricted\nsubset of files; the full C<make xtest> should still be run on a regular basis.\n\n=end overview\n\n# Get the old and new commit IDs\n\nsub get-rev {\n    run(<git rev-parse HEAD>, :out).out.slurp(:close).chomp;\n}\n\nmy $old-rev = get-rev;\nrun(<git pull --rebase>);\nmy $new-rev = get-rev;\n\n\nif $old-rev eq $new-rev {\n    say \"No changes to test.\";\n} else {\n    say \"Updating prerequisites\";\n    run(<zef install --deps-only .>);\n\n    my $revs = $old-rev ~ \"..\" ~ $new-rev;\n    my $files = run('git', 'diff', '--name-only', $revs, :out).out.slurp(:close).chomp.split(\"\\n\").sort.join(\" \");\n    my $outfile = \"./retest\";\n\n    my $of = $outfile.IO.open(:w);\n\n    $of.say: \"#!/usr/bin/env raku\";\n    $of.say: \"\\%*ENV<RAKULIB>='.';\";\n    $of.say: \"\\%*ENV<TEST_FILES>='$files';\";\n    $of.say: \"say \\%*ENV<TEST_FILES>;\";\n    $of.say: \"run(<make xtest>).so\";\n\n    $of.close;\n\n    run('chmod', 'a+x', $outfile);\n\n    run($outfile).so;\n    say \"Test same set of files again with $outfile\";\n}\n"
  },
  {
    "path": "writing-docs/CREATING-NEW-DOCS.md",
    "content": "### Conventions\n\n1. It must be valid Raku pod\n2. The first non-comment or non-empty line must be:\n\n        =begin pod # optionally followed by :key<value> %config pairs\n\n3. The second non-comment or non-empty line must be:\n\n        =TITLE ...text...\n\n4. An optional (but usually desired) subtitle must be the third non-comment or non-empty line:\n\n        =SUBTITLE ...text...\n\n5. The last non-comment or non-empty line must be:\n\n        =end pod\n\nSee [TESTING.md](TESTING.md) for how to programmatically verify these and other requirements.\n\n### Valid example:\n\n```\n# this is a valid, non-pod comment\n=begin pod :my-link<foo> # another comment\n=TITLE Working with Raku pod\n=SUBTITLE Alice in Wonderland\n# ... more valid pod and text\n=comment a pod comment # a valid comment\n=end pod\n```\n\n### Invalid example:\n\n```\n=comment a pod comment # this is not a valid comment in this position\n=begin pod :my-link<foo> # another comment\n=TITLE Working with Raku pod\n=SUBTITLE Alice in Wonderland\n# ... more valid pod and text\n=end pod\n```\n"
  },
  {
    "path": "writing-docs/EXAMPLES.md",
    "content": "# Contributing examples to the documentation\n\nPlease follow these guidelines when adding sample code to the documentation.\n\n## Writing Examples\n\nPlease use code blocks to highlight example code; any indented blocks\nare considered to be code, but you can specify the `=for code` directive, or a\ncombination of `=begin code` and `=end code` to better control which\nblocks are considered. The rakudoc directives also allow you to set\nattributes for a block of code.\n\nWhen using a `=for code` directive or a `=begin code`/`=end code`\ncombination, the code block should not be indented. If it is, it\nwill impact the website rendering.\n\n## Testing Examples\n\n`t/19-examples-compilation.rakutest` will test the code from all the\nexamples. This file is run as part of continuous integration.\n\nTo test specific files (recommended), pass them as options on the command\nline to the test file, or set the environment variable TEST_FILES to\na space separated list. See [TESTING.md](TESTING.md) for more details.\n\nNote that method signatures are also compiled. They have an implied block\nadded to insure valid compilation.\n\nCare is taken to wrap the sample code in enough boilerplate so that no\nruntime code is executed, and that a class is available if needed.\n\nNote: because we are considering each POD code block independently,\nthere is no guarantee that a partial snippet will itself be compilable.\nFor this reason, it's fine to use `preamble` (see below) to give each\nblock enough information to compile.\n\nFor pedagogical reasons, it's\nOK to break what would otherwise be a large block of code into smaller\nchunks and discuss each one separately - we still want to do our best\nto compile these individual chunks. However, avoid this practice across\nmethods on a Type/ page, which can be split up to show only a single method.\nEven on a Language/ page, avoid continuing an example for more than a\npage or so.\n\n## Skipping or finessing tests\n\nWhile our goal is to test every example of Raku in the repository, some\nblocks are not easy to test. Here are some ways you can skip the test or\nfinesse it.\n\n### Other languages\n\nWe're just testing Raku here: to mark as another language, use `:lang`,\nand this will avoid testing:\n\n    =begin code :lang<tcl>\n    puts \"this is not Perl\"\n    =end code\n\nFor plain text use `:lang<text>`\n\n### Allow .WHAT\n\nOne of the checks is to dissuade using `.WHAT` in tests; However, in rare\ncases that is the explicit point of the test, so you can allow it with ok-test:\n\n    =begin code :ok-test<WHAT>\n    say 42.WHAT;\n    =end\n\n### Allow dd\n\n`dd` is a rakudo specific routine that isn't part of the specification; examples\nshouldn't use it unless they are explicitly trying to show how it works.\nYou can allow it with ok-test:\n\n    =begin code :ok-test<dd>\n    dd 42;\n    =end\n\n### Allow .perl\n\nOne of the checks is to discourage using `.perl` in tests: the `raku`\nmethod should be used instead.\nIf needed you can allow the use of the `perl` method with ok-test:\n\n    =begin code :ok-test<perl>\n    say {:42a}.perl;\n    =end\n\n### Methods\n\nIf a code snippet looks like a method declaration, it's automatically\nwrapped in additional code so you don't have to specify a body in the docs.\nMulti-line method signatures are much harder to detect, so if you have a\nmethod body that spans lines, use the `:method` tag:\n\n    =begin code :method\n    method arg (\n        Bool $one,\n        Bool $two\n    )\n    =end code\n\nThis helps keep the method detection logic in the test code simple.\n\nConversely, sometimes the method detection is overeager; you can disable it\nentirely with `:method<False>`\n\n### Preambles\n\nWhen writing examples, it's often helpful to refer to things that aren't\ndefined in that snippet; you don't want to have to have a full working\nexample in the code.\n\n    =begin code :preamble<no strict;>\n    $x = pi;\n    =end code\n\n    =begin code :preamble<my $x; sub frob {...};>\n    $x = frob();\n    =end code\n\nNote that when running the code, it's compiled inside an anonymous class.\nThe preamble is the first code in this class, so if you're testing the\ndefinition of a complex method signature that requires attributes, you can\ndeclare them using this construct.\n\n### Complicated Examples\n\nSome examples are too complicated to be run using our EVAL trick.\nTag these with `:solo`, and they will be run as a separate standalone\nscript. This is slower, so only use it on those examples that require\nit. Anything using `unit` or `export` is a good candidate. Note that\nusing this tag means the code is not wrapped as it is for the EVAL path.\n\n### Failures\n\nSome examples fail with compile time exceptions and would interrupt the test\nfor a file. Use the pod-config option `skip-test` to skip them. When possible,\nspecify a reason why you have to use this; it should be considered a last\nresort, and many examples might be amenable to using one of the\nprevious annotations.\n\n    =begin code :skip-test<compile time error>\n    if 1 \"missing a block\";\n    =end code\n\n### Code Indentation / Formatting\n\nDocumentation can be formatted as code using multiple source\nstyles.\n\n## Indented text\n\n4-space indented text is formatted as a code block. The indent is *not*\npart of the displayed code. It's not possible to add any rakudoc\ndirectives on this style.\n\n## =for code\n\nThe following block of text is treated as code. The indentation level\nis from the beginning of the line, regardless of how the `=for`\nis indented.\n\n## =begin code / =end code\n\nThe enclosed text is treated as code. The indentation level is\nrelative to the indentation of the rakudoc directives.\n\n##  Environment Variables\n\n* set `RAKU_DOC_TEST_VERBOSE` to a true value to display verbose messages during test suite run.\n* `RAKU_DOC_TEST_FUDGE` fudges `skip-test` code examples as TODO in `t/19-examples-compilation.rakutest` test.\n"
  },
  {
    "path": "writing-docs/INDEXING.md",
    "content": "# Search indexing rules\n\n### Synopsis\n\nA term or a location in a rakudoc document can be indexed so that it is\npossible to create a named reference pointing to it. This can be used\nto generate a reference in the rendered version of the documentation or\nimplement search function on the website hosting the rendered documentation.\n\n### Format\n\nAn index item is created using the Pod formatting code `X` in these formats:\n\n    X<text|category,item>\n    X<text|category1,item1;category2,item2;...>\n    X<|category,item>\n\nFor the first example, the `text` text is rendered,\nan item with text `item` under the category `category` is added to the index.\n\nNote it also creates a page anchor in the current website implementation.\n\nThe second example demonstrates how the `;` separator can be used to\nindex more than a single item, and the third item has no text rendered,\nbut an invisible anchor (e.g. for the HTML version) is created that can be used\nto navigate to via URL.\n\nValid examples are:\n\n    X<|Syntax,does>\n    X<|Language,\\ (container binding)>\n    X<Subroutines|Syntax,sub>\n    X<|Variables,$*PID>\n    X<Automatic signatures|Variables,@_;Variables,%_>\n    X<Typing|Language,typed array;Syntax,[ ] (typed array)>\n    X<Attributes|Language,Attribute;Other languages,Property;Other languages,Member;Other languages,Slot>\n\n### Categories\n\nTo avoid cluttering of index item categories, only 28 categories can be specified,\nso when indexing new items be sure to use one of:\n\n* `Types` (reference of Raku types)\n* `Modules` (built-in modules in Raku)\n* `Subroutines` (reference of Raku subroutines)\n* `Methods`(reference of Raku methods)\n* `Terms` (reference of Raku terms)\n* `Adverbs` (reference of Raku adverbs)\n* `Traits` (reference of Raku traits)\n* `Phasers` (reference of Raku phasers)\n* `Asynchronous phasers` (reference of Raku asynchronous phasers)\n* `Pragmas` (reference of Raku pragmas)\n* `Variables` (reference of Raku special variables)\n* `Control flow` (terms related to control flow)\n* `Regexes` (terms related to regexes)\n* `Operators` (cases of operators not fitting for other operator categories, for example operators like `s///`, hyper, method call operators etc.)\n* `Listop operators` (listop ops)\n* `Infix operators` (infix ops)\n* `Metaoperators` (meta ops)\n* `Postfix operators` (postfix ops)\n* `Prefix operators` (prefix ops)\n* `Circumfix operators` (circumfix ops)\n* `Postcircumfix operators` (postcircumfix ops)\n* `Tutorial` (indexing explanation of some item in a tutorial-like manner rather than pure reference)\n* `Other languages` (terms from other languages and migration guides)\n* `Syntax` (indexing various language syntax constructs not fitting into other categories (syntax))\n* `Language` (indexing reference-like explanation of various language concepts (semantics), for example, `hash slice` or `Unquoting`)\n* `Programs` (legacy, program writing-related topics) # to be decided\n* `Reference` (indexing various concepts and names not directly coming from Raku or other languages, for example, `opcode` or `MoarVM`)\n\nIf you see an item miscategorized, please give it some love or open a ticket if you are not sure where\nit fits best.\n\nOther than explicit creation, headers (`=head` elements of Pod) of certain format get an anchor automatically,\nsay `=head routine sin` creates an index item categorized as `Subroutines` automatically.\n\n### Testing\n\nThere is a test checking basic syntax of the references in the documentation\nin author tests, so the suite passing means the references are at least well-formatted.\n"
  },
  {
    "path": "writing-docs/README.md",
    "content": "# How to help\n\nRaku is not a small language, and documenting it and maintaining that\ndocumentation takes a lot of effort. Any help is appreciated.\n\nHere are some ways to contribute:\n\n * Add missing documentation for classes, roles, methods or operators. _Except\n   superclasses & roles, those are already included in the website generated from this repository._\n * Add usage examples to existing documentation.\n * Proofread and correct the documentation.\n * Tell us about missing documentation by [opening issues](https://github.com/Raku/doc/issues)\n * Do a `git grep TODO` in this repository, and replace the TODO items by\n   actual documentation.\n\n[Issues page](https://github.com/Raku/doc/issues) has a list of current issues and\ndocumentation parts that are known to be missing\nand [the CONTRIBUTING document](../CONTRIBUTING.md)\nexplains briefly how to get started contributing documentation.\n\n# Other docs\n\nFor specific topics, please see:\n\n   * [CREATING-NEW-DOCS.md](CREATING-NEW-DOCS.md)\n   * [EXAMPLES.md](EXAMPLES.md)\n   * [INDEXING.md](INDEXING.md)\n   * [STYLEGUIDE.md](STYLEGUIDE.md)\n\n# Pull Requests\n\nThe preferred mechanism for submitting content is [pull requests](https://github.com/Raku/doc/pulls).\n\nWhen submitting a PR, please ensure that you've run `make xtest` for any modified files. See [Testing.md](Testing.md)\nfor more details.\n"
  },
  {
    "path": "writing-docs/STYLEGUIDE.md",
    "content": "# Style guide\n\nPlease follow these style rules when contributing to the documentation.\n\n## Text\n\nPlease follow these rules when writing the text itself:\n\n* Avoid trailing whitespace in every line, including examples.\n* Use always space, never tabs.\n* Configure your editor for auto-flowing (or\nhard-wrapping) line length at 72 whenever possible.\n\nWhen writing new text, try to be consistent with the rest of the\ndocs. If it happens that there's no consistency and this style guide\ndoes not give a recommendation, consult\n[Wikipedia's Manual of Style](https://en.wikipedia.org/wiki/Wikipedia:Manual_of_Style)\nand see if the issue is covered there. Typically, style decisions that\nwork for Wikipedia can be safely used for writing Raku documentation.\n\n## Structure\n\n### How to document multiple similar routines\n\nAvoid writing a routine's documentation in the form\n\n    Like [other method] except [...]\n\neven when they're in the same class, because readers might not read\nthe whole class page, but rather navigate to a specific routine (maybe\neven out of context in the /routine/ section of the website) and\nexpect it to tell them how it works without being sent on a goose\nchase around the site.\n\nIn other words, give each routine documentation a self-contained\nintroduction, and only link to related/similar routines *below* that\nintroduction, even if that means duplicating some half-sentences\nmultiple times.\n\n### Links to docs\n\nTry to avoid absolute URLs.\n\n    L<foo|/routine/foo>\n\nWorks well instead. Specifically for types, follow this convention:\n\n    L<C<SomeClass>|/type/SomeClass>\n\nwhen referring to a type from another page (each time it appears), and\n\n    C<SomeClass>\n\non its own page.\n\nIf you have to use the full URL in the docs or elsewhere, ensure the\nsubdomain is `docs` and the protocol is `https://` (as in\n`https://docs.raku.org/blah/blah`). Other variations of the URL will\nstill work, for convenience, but they all simply redirect to the\ncanonical version, so it's best to use it from the start.\n\n## Language\n\n## Intent over syntax\n\nAs noted in the discussion on [#1748](https://github.com/Raku/doc/issues/1748),\nWhen writing examples for documentation, do not merely show the syntax with an\nunreasonable example - for example, from the ticket:\n\n    lazy 1..5\n\nWhile this does show the syntax, it is not something one would write, and having\nexamples that are too simplistic like this may lead to cargo culting or other\nbad practices.\n\n### Unambiguous is better than short\n\nWhen you have to choose between two sentence structures, opt for the\nunambiguous.\n\n```\nmy %hash = hash;\nmy @array = <1 2 3>\n```\n\nIn this case, `this code initializes a hash` is short, but\nambiguous. Opt for `The first line of this example initializes an\nempty hash`.\n\nTry to avoid abbreviations. For example, “RHS” is short, but\n“right-hand side” is much clearer for beginners.\n\nIn general, try to put yourself in the shoes of someone with no\nprevious exposure to the language or computer science. Although it\nmight seem obvious to you that only the first line can in fact\ninitialize a hash, the documentation is targeted at such novices.\n\n### 'say' vs 'put'\n\nWhile there is no hard and fast rule about which of these routines to use\nin a given situation, please try to follow these guidelines.\n\nWhen generating output in examples intended to be read by a user, use 'say'.\nAdditionally, add a comment showing the intended output, e.g.:\n\n    say 3.^name; # OUTPUT: «Int␤»\n\nFor examples where a particular format is required, or exact data is expected\n(e.g., for something sent over a network connection), prefer 'put'.\n\n### 'parameter' vs 'argument'\n\n* Argument: what it looks like to the caller\n* Parameter: what it looks like to the function\n\n    S06: \"In Raku culture, we distinguish the terms parameter and argument; a\n    parameter is the formal name that will attach to an incoming argument\n    during the course of execution, while an argument is the actual value that\n    will be bound to the formal parameter. The process of attaching these\n    values (arguments) to their temporary names (parameters) is known as\n    binding. (Some C.S. literature uses the terms \"formal argument\" and \"actual\n    argument\" for these two concepts, but here we try to avoid using the term\n    \"argument\" for formal parameters.)\"\n\n### 'object' vs 'value'\n\nYou may use `object` for anything you can call methods on, including\nvalue objects and type objects. Consider `instance` for defined\nobjects.\n\n### 'filehandle' vs 'file-handle', 'file handle' and other dashed or space-separated constructs\n\nThese are enforced by `t/15-word-variants.rakutest`, which is run as part of CI.\n\nIf you find a variant that is not covered by the test, please submit a PR that adds\nthe preference to the test, and updates the docs to pass the test.\n\n### Prefer clear and readable variable names\n\nWhile Raku allows all kinds of fancy characters in identifiers,\nstick to easily understandable names:\n\n    my $sub; # GOOD\n    my $ßub; # BAD; Is it a twigil? How do I type this? HELP!\n\nIf you want to add some fancy characters, please stick to\n[well-known characters from our Unicode set](https://docs.raku.org/language/unicode_ascii).\n\n### Ascii vs. Unicode Examples\n\nWhile Raku has great support for unicode, the documentation should be approachable by\na wide audience, and using unicode in code examples where it is not specifically relevant\nto learning the topic adds (an arguably small) barrier to adoption.\n\nFor example, in a section where we are talking about the sequence operator, this is preferred:\n\n    my @infinite-sequence = 1, 3 ... Inf;\n\nWhile the equivalent with all unicode may be more appealing to mathematicians, it makes it\nharder for the new user to start using the language.\n\n    my @infinite-sequence = 1, 3 … ∞;\n\n### Try to express intent, rather than just demonstrating the syntax\n\n    my @l = lazy 0..5;                             # Correct, but BAD\n    my @too-long-list = lazy 0..100000000          # GOOD\n    my @powers-of-eleven = lazy 1, 11, 121 … 10¹⁰⁰ # EVEN BETTER\n\nIn the first case, the syntax is totally correct. But a list with 5\nelements need not be made lazy. The second is better, because it does\nshow the intent: work with long lists that need not be filling up\nmemory until they are needed. However, the last one is better because\nit includes a real use case: in the progression, Raku does not need\nto actually compute its terms until they are really needed.\n\n## Perl and Raku\n\nStyle guidelines related to Perl family languages.\n\n### Don't reference Perl unless in a 5-to-6 document or related document\n\nWe are not expecting our users to have to know Perl to learn Raku,\nso this should not be part of the bulk of the documentation.\n\n### Use present tense when talking about Perl features\n\nPerl 5 is still an active language, therefore instead of \"In Perl\nthis was used for ..., but in Raku ...\"  use a form like \"In Perl\nthis is used for ..., but in Raku ...\"  ('was' has been made a\npresent 'is').\n\n## Domain\n\nWhat should be documented? The primary goal of the programmatic\ndocumentation is to cover items that are part of the specification (the\nroast test suite)\n\n* If something is visible to users of Raku and is in roast: document it.\n* If something is visible to users of Raku and is not in roast:\n  check with the dev team (#raku-dev on libera.chat) - This might need\n  have a test added (and therefore docs), or it might need to be\n  hidden so users cannot see it. In general, documentation of\n  implementation-specific features should be avoided; however, if\n  eventually the feature is added to the documentation, always specify\n  clearly its implementation-specific nature and where possible show\n  the first and latest version the documented feature is available.\n\nFuture considerations along this line include: documenting things that\nare Rakudo specific (like ```dd```), and documenting which versions of the\nspec items are available in.\n\n## Use of HTML\n\nDo not embed HTML in the documentation files.\n\n## Nits\n\nDo not leave trailing whitespace inside a `C<>` tag (CI tests will fail).\nIf there is a formatting reason why this is *absolutely* required, you can prefix\nthe use something like 'Z<ignore-code-ws>C<foo >`.\n"
  },
  {
    "path": "writing-docs/TESTING.md",
    "content": "# Testing\n\nHaving learned our lessons about how easy it is to introduce typos over the years,\nwe have several tests in the repository to help us keep our content as clean as\npossible.\n\n# Setup\n\nBefore running the tests, you may need to install modules required by the tests:\n\n```\n$ zef install --deps-only .\n```\n\nWe depend on something that depends on graphviz, but we don't need it ourselves.\nYou can skip it with:\n\n```\n$ zef install --deps-only --exclude=\"dot\" --/test .\n```\n\n## Continuous Integration / Pull Requests\n\nEach commit/PR will trigger the CI (only for the files that changed) and run the tests.\n\nEvery pull request should pass the CI tests.\n\n## Local testing\n\nIn your branch or fork, if you have non-committed changes for some files, you can run:\n\n```\n$ util/test-modified.sh\n```\n\nOr to run all tests on specific files regardless of their git status:\n\n```\n$ TEST_FILES=\"doc/Language/faq.rakudoc doc/Type/Complex.rakudoc\" RAKULIB=. make xtest\n```\n\nAuthor tests that are in `xt/` may not pass or have prerequisites.\n\nYou can run the basic tests against a subset of files with\n\n```\n$ TEST_FILES=\"doc/Language/faq.rakudoc doc/Type/Complex.rakudoc\" zef test --verbose .\n```\n\nOr all tests against everything that you haven't committed yet:\n```\n$ TEST_FILES=$(git ls-files --modified) RAKULIB=. make xtest\n```\n\n## NETWORK_TESTING\n\nSome tests make network connections to verify data; if this environment variable is not\nset, those tests will be skipped.\n"
  },
  {
    "path": "xt/01-raku-version.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\n\nuse JSON::Fast;\n\n=begin overview\n\nVerify that the version of rakudo used to run the tests is recent enough.\n\nTo avoid issues with a mismatch on source or compilation testing, and to\nrequire a recent enough version for RakuAST classes.\n\n=end overview\n\nplan 1;\n\n{\n    my $web = run(\n        'curl', '--silent', '-L', '-H', \"Accept: application/vnd.github+json\", '-H', \"X-GitHub-Api-Version: 2022-11-28\",\n            \"https://api.github.com/repos/rakudo/rakudo/releases?per_page=1\",\n        :out);\n    my $desired = Version.new((from-json $web.out.slurp(:close))[0]<tag_name>);\n\n    my $actual = $*RAKU.compiler.version;\n\n    ok $actual >= $desired, \"using at least version $desired for testing (found $actual)\";\n\n    CATCH {\n        default {\n            flunk \"Unable to check desired version; You may be offline.\";\n        }\n    }\n}\n"
  },
  {
    "path": "xt/check-signatures.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\nuse Telemetry; # so we can check it\n\nuse RakuDoc::Test::Files;\n\n=begin comment\nBy default, we test all files in 'doc/Type'.  You can specify different files to\ntest by passing them as arguments to the test, or using the TEST_FILES env. var.\n=end comment\n\nmy @doc-files = RakuDoc::Test::Files.pods.grep(*.starts-with('doc/Type'));\n\ngrammar TypeDocumentation {...}\n\n=begin SYNOPSIS\nCheck the signatures of documented methods against the Rakudo source code.\n\nFor each method documented in a .rakudoc file in doc/doc/Type/, this test compares\nthe documented signature against the signature in the Rakudo source code.\nBecause we are documenting I<Raku> and not I<Rakudo>, detecting a difference in\nthe signature does not automatically cause the test to fail: some differences in\nsignature (such as different names for positional parameters) represent\ndifferent implementation choices rather than an error in the docs.\n\nI<NOTE>: when you specify a rakudo source directory using the RAKUDO_SRC\nenvironment\nvariable, this script will attempt to test a specific version by using git checkout\nto switch that checkout to a specific version during the test, and run\n\"git checkout -\" at the end to reset the state.\n\nI<NOTE>: This test uses introspection from the running copy of Rakudo to find\ninformation in the source code. If you are running a different version of raku\nthan the RAKUDO_SRC directory, it may be unable to find certain method definitions.\n\nTo ensure that implementation details don't cause failing tests, we check only\nfor certain discrepancies that are guaranteed to indicate a\nsubstantive/non-implementation detail mismatch between Rakudo and the docs.\n\nCurrently, we only test for one category of discrepancies: Methods that are\ndefined with a specific invocant in Rakudo but not in the\ndocs (this helpfully also catches the situation where a documentation signature\nwas I<intended> to have an invocant, but where someone forgot to end the\ninvocant with a C<:>)\n\nIn the future, this test could be expanded to also check for:\n\n=item arity mismatches\n=item different names for named parameters\n=item times when the Rakudo code specifies a return constraint but the docs do\nnot (the inverse situation -- where we specify a return constraint that Rakudo\ndoes not -- would not necessarily represent an error in the docs so long as\nthe function always does return that type)\n\nYou may also wish to review certain skipped results: they may point\nto mistakes in the documentation - one example is methods that are\ndefined on a role instead of a class - it will show up as skips but\npoints to a need to move the documentation for that method.\n\n=end SYNOPSIS\n\nmy $error = \"To run check-signatures, please specify the path to the Rakudo git checkout with the RAKUDO_SRC environment variable\";\nmy $rakudo-src-dir = %*ENV<RAKUDO_SRC> // plan(:skip-all( $error ));\n\nwhen !$rakudo-src-dir.IO.d { plan(:skip-all( $error )) }\nwhen ?(run <git --version>, :out, :err).exitcode { plan(:skip-all( \"check-signatures requires git\"))}\nmy $doc-dir = $*CWD;\n\ngiven $*RAKU.compiler.verbose-config<Raku><version>.split('-') {\n    chdir $rakudo-src-dir;\n    when .elems == 1 {\n        my $checkout = run (|<git checkout>, |(\"tags/{ .[0] }\")), :out, :err;\n        my $checkout-error = $checkout.err.slurp(:close);\n        if $checkout.exitcode != 0 {\n            die \"Error checking out tag from source, $checkout-error\";\n        }\n    }\n    when .elems == 3 { run «git checkout { .[2].substr(1 ..*) }», :out, :err }\n}\n\nmy token signature { '('[ <-[()]>* <~~> <-[()]>* ]* ')' | '(' <-[()]>* ')' }\n\nif @doc-files.elems == 0 {\n    plan(:skip-all(\"No type documentation files specified\"));\n    exit;\n}\n\nplan +@doc-files;\nfor @doc-files -> $file {\n    when $file !~~ /'doc/Type/'[(\\w+)'/'?]+'.rakudoc'/ { skip \"'{$file.basename}' doesn't document a type\" }\n    my $type-name = S/'doc/Type/'[(\\w+)'/'?]+'.rakudoc'/$0.join('::')/ with $file;\n    my $type = ::($type-name);\n    CATCH { default {\n        my $name = $type-name // $file;\n        skip \"$name lacks required introspection\";\n    }}\n    TypeDocumentation.parse(\"$doc-dir/$file\".IO.slurp);\n\n    subtest \"check $type-name methods\", {\n        plan +$<method>;\n        for $<method> { given .<signature-line> -> $line {\n            use MONKEY-SEE-NO-EVAL;\n            my $method-name = \"$type-name\\.{$line<name>}\";\n            CATCH {\n                when X::AdHoc && .payload ~~ /'::?'/ { skip \"$method-name defined with compile-time variable\"; }\n                default { skip \"cannot check $method-name\"; }}\n\n            my $test-msg := \"$type-name\\.{$line<name>} invocant matches source\";\n            my @params = EVAL(\":{$line<signature>}\").params;\n\n            my $method = do given $line<multi> {\n                when !$type.^lookup(~$line<name>) { skip \"$method-name not found on $type-name\";\n                                                   next }\n                when .not { $type.^lookup(~$line<name>) };\n                given $type.^lookup(~$line<name>).candidates.grep({.package.^name eq $type-name}) {\n                    when .elems == 1 { .[0] }\n                    default          { skip \"cannot determine source for multi method $method-name\";\n                                       next }\n            }};\n            my $src-file := $rakudo-src-dir.IO.add($method.file.split('::')[1]);\n            my $src-line := slurp( $src-file ).lines[ $method.line - 1];\n\n            given $src-line ~~ /<signature>/ {\n                my $src-sig =  do {\n                    when Nil && $src-line ~~ /method/ { '()' }\n                    when Nil  { Nil }\n                    default   { $_ }\n                };\n                when $src-sig ~~ Nil {\n                    when @params[0] eqv Any { flunk($test-msg);\n                                              report-accessor-error($line<signature>, :$src-line)}\n                    unless ok(@params[0].invocant, $test-msg) { report-accessor-error($line<signature> :$src-line) }\n                }\n                when $src-sig ~~ /^'()'/ | /'(-->'/ { pass($test-msg)}\n                when EVAL(\":$_\").params[0].invocant {\n                    my $is-invocant = @params[0] ?? @params[0].invocant !! False;\n                    unless ok($is-invocant, $test-msg) {\n                        diag(\"documented method: {$line<signature>}\");\n                        diag(\"    source method: $_\");}\n                }\n                default { pass $test-msg }\n            };\n    }}\n}}\n\nsub report-accessor-error($sig, Str :$src-line) {\n    diag(\"auto-generated accessors must have definite invocants\");\n    diag($src-line);\n    diag(\"documented method: $sig\")\n}\n\nrun <git checkout ->, :out, :err;\n\ngrammar TypeDocumentation {\n    token TOP { [<method> || <other-line>]+ }\n\n    token method { ^^ '=head2 method' \\N* \\n\n                   \\n\n                   <signature-line>\n                 }\n    token other-line { ^^ \\N* \\n }\n\n    token signature-line { <.ws><multi>? <declarator> <.ws> <name> <signature> \\n}\n    token multi      {'multi' <.ws>}\n    token name       { <[-'\\w]>+}\n    token declarator { ['method' | 'sub'] }\n}\n"
  },
  {
    "path": "xt/rakuast-compare.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\nuse RakuDoc::Test::Files;\nuse File::Temp;\n\n=begin overview\n\nFor all raku docs, compare output from RAKUAST and old --doc ignoring whitespace diffs.\n\nTo see the changes between current and new rendering as a diff, run as:\n\n    RAKUDO_AST_DOCS=v xt/rakuast-compare.rakutest\n\nAnd optionally specify a single file to restrict the output.\n\nTo perform a strict check respecting whitespace:\n\n    RAKUDO_AST_WS=1 xt/rakuast-compare.rakutest\n\n=end overview\n\nmy @files = RakuDoc::Test::Files.pods;\nplan +@files;\n\nfor @files -> $file {\n\n    %*ENV<RAKUDO_RAKUAST>=\"\";\n    my $old = \"\";\n    my $job = Proc::Async.new($*EXECUTABLE-NAME, '--doc', $file);\n    $job.stdout.tap(-> $buf {$old ~= $buf});\n    $job.stderr.tap({;});\n\n    my $has-error = ! await $job.start;\n    if $has-error {\n       flunk \"Error occurred caching $file old school\";\n       next;\n    }\n\n    %*ENV<RAKUDO_RAKUAST>=\"1\";\n    my $new = \"\";\n    $job = Proc::Async.new($*EXECUTABLE-NAME, '--doc', $file);\n    $job.stdout.tap(-> $buf {$new ~= $buf});\n    $job.stderr.tap({;});\n\n    $has-error = ! await $job.start;\n    if $has-error {\n        flunk \"Error occurred caching $file new school\";\n        next;\n    }\n\n    unless %*ENV<RAKUDO_AST_WS> {\n        # Ignore space differences\n        $old ~~ s:g/ ' '+ / /;\n        $new ~~ s:g/ ' '+ / /;\n\n        # Ignore blank lines\n        $old ~~ s:g/ ^^ $$ . //;\n        $new ~~ s:g/ ^^ $$ . //;\n\n    }\n    ok $old eq $new, \"$file contents match\";\n    if %*ENV<RAKUDO_AST_DOCS>:exists && %*ENV<RAKUDO_AST_DOCS> eq \"v\" {\n        my ($old_fname, $old_io) = tempfile;\n        $old_io.spurt: $old, :close;\n        my ($new_fname, $new_io) = tempfile;\n        $new_io.spurt: $new, :close;\n        if %*ENV<RAKUDO_AST_WS> {\n            run('diff', '-u', $old_fname, $new_fname);\n        } else {\n            run('diff', '-u', '-w', $old_fname, $new_fname);\n        }\n    }\n}\n"
  },
  {
    "path": "xt/rakudoc-l.rakutest",
    "content": "#!/usr/bin/env raku\n\n=begin overview\n\nCheck any L<> references for validity. If C<%*ENV<NETWORK_TESTING>> is set,\nvalidate that external links are live.\n\n=end overview\n\nuse Test;\n\nuse RakuDoc::Test::Files;\nuse Pod::Convenience;\nuse Cro::HTTP::Client;\n\nmy @files = RakuDoc::Test::Files.pods;\n\nif @files {\n    plan +@files;\n} else {\n    plan :skip-all<No rakudoc files specified>\n}\n\nmy $ua = Cro::HTTP::Client.new;\n\nsub is-valid-display($content) {\n    if $content.starts-with('#') {\n        flunk \"$content starts with a #\";\n    }\n}\n\nmy %bad-links = BagHash.new;\nmy $network-testing = %*ENV<NETWORK_TESTING>:exists.so;\nmy %good-links;\n\nsub is-valid-link($links) {\n    for @$links -> $link {\n        if $link.starts-with('/') {\n            if $link.contains('.html') {\n                %bad-links{$link}++;\n                flunk \"$link contains .html\";\n            }\n            if $link eq \"/\" {\n                pass \"$link exists (generated)\";\n                return;\n            }\n            if $link ~~ / '/type/independent-routines' '#'? / {\n                pass \"$link exists (generated)\";\n                return;\n            }\n            if $link ~~ / '/index' '#'? / {\n                pass \"$link exists (generated)\";\n                return;\n            }\n            if $link ~~ / '/introduction' '#'? / {\n                pass \"$link exists (generated)\";\n                return;\n            }\n            if $link ~~ / '/reference' '#'? / {\n                pass \"$link exists (generated)\";\n                return;\n            }\n\n            # This may be overeager, is needed for Types\n            my $original = $link.subst('::','/', :g);\n\n            # We don't handle fragments yet\n            $original ~~ s/ '#' .* //;\n\n            # split into components\n            my @path = $original.split('/')[1..*];\n            if @path[0] eq 'routine' | 'syntax' {\n                # these are not primary sources, skip for now\n                # Should be caught on error-report in site build\n                diag \"skipping $original\";\n                next;\n            }\n\n            # Path elements in links should be lower case\n            my $local-path = @path[0];\n\n            if $local-path.fc ne $local-path {\n                %bad-links{$link}++;\n                flunk \"$link should be lower case\";\n                next;\n            }\n\n            # Folders are title-cased on disk\n            @path[0] = @path[0].tc;\n\n            # Look in doc/ folder for this rakudoc file.\n            @path.unshift: 'doc';\n            my $path = @path.join('/');\n\n            my $ok = ?($path.IO.d or ($path ~ '.rakudoc').IO.e);\n            ok $ok, \"$link exists (primary)\";\n            %bad-links{$link}++ unless $ok;\n        } elsif $link.starts-with: '#' {\n            next; # don't check in-page anchors\n        } elsif $link.starts-with: 'irc:' {\n            next; # don't vaidate IRC\n        } else {\n            my @valid-protocols = <http https>;\n            if $link.starts-with(any(@valid-protocols) ~ '://') {\n                next unless $network-testing;\n\n                # Skip known incorrect URLS that are just for examples\n                next if $link eq \"http://www.MegaGigaTeraPetaCorp.com/std/disclaimer.txt\";\n                # Skip known problematic URLs (403 via Cro, fine via browser)\n                next if $link eq \"https://dev.mysql.com/downloads/repo/apt/\";\n\n                # auto-pass if we already pulled this session\n                if %good-links{$link}:exists {\n                    pass \"HTTP KNOWN $link\";\n                    next;\n                }\n\n                my $response = await $ua.get: $link, user-agent => 'Raku Docs Validator';\n                CATCH {\n                    when X::Cro::HTTP2::GoAway {\n                        # race condition? try again.\n                        diag \"HTTP GoAway $link\";\n                        sleep 1;\n                        redo;\n                    }\n                    when X::Cro::HTTP::Error {\n                        if .response.status == 429 {\n                            diag \"HTTP 429 $link\";\n                            my $retry-after = max(min(.response.header('retry-after'),5),42);\n                            diag \"Retrying after $retry-after\";\n                            sleep $retry-after;\n                            redo;\n                        } else {\n                            %bad-links{$link}++;\n                            flunk \"HTTP {.response.status} $link\";\n                            next;\n                        }\n                    }\n                    default {\n                        if $_.message eq \"Stream reset by the server\" {\n                            diag \"HTTP Stream reset $link\";\n                            redo;\n                        }\n\n                        %bad-links{$link}++;\n                        flunk \"HTTP ({$_.message}): $link\";\n                        next;\n                    }\n                    next;\n                }\n                %good-links{$link}++;\n                pass \"HTTP {$response.status} $link\";\n                next;\n            }\n\n            # fallthrough\n            %bad-links{$link}++;\n            flunk(\"relative link or bad protocol: $link\");\n        }\n    }\n}\n\n\nsub walk-content($x) {\n    for $x.contents -> $contents {\n        next unless $contents;\n        for @$contents -> $item {\n            if $item ~~ Pod::FormattingCode and $item.type eq 'L' {\n                # L<X> has an empty meta but renders as if it were L<X|X>, explicitly set this\n                unless $item.meta {\n                    $item.meta = $item.contents.join;\n                    # Only check the # if there's no meta.\n                    is-valid-display($item.contents.join);\n                }\n                is-valid-link($item.meta);\n            } elsif $item !~~ Str {\n                walk-content($item);\n            }\n        }\n    }\n}\n\nfor @files -> $file {\n    my @chunks = extract-pod($file).contents;\n\n    # This emits pass or flunk for each local L<> found.\n    subtest $file => {\n        walk-content($_) for @chunks;\n    }\n}\n\ndiag \"Listing by link\" if %bad-links;\n\nfor %bad-links.keys.sort -> $k {\n    my $v = %bad-links{$k};\n    diag \"[$v] $k\";\n}\n"
  },
  {
    "path": "xt/rakudoc-types.rakutest",
    "content": "#!/usr/bin/env raku\n\n=begin overview\n\nWhen referring to items that are types, the required format is:\n\n   L<C<Thing>|/type/Thing>\n\nAny other formatting code that refers to a type will fail the test; any C<>\nthat isn't inside of an L<> will fail, and any L<> that doesn't have a C<>\nwill fail. Links may end with an optional #id.\n\nExceptions:\n\n=item Referring to a type on its own page should only use C<>.\n=item It's OK to refer to a routine page with the same name instead.\n\n=end overview\n\nuse Test;\n\nuse RakuDoc::Test::Files;\nuse Pod::Convenience;\n\nmy @files = RakuDoc::Test::Files.pods;\n\nif @files {\n    plan +@files;\n} else {\n    plan :skip-all<No rakudoc files specified>\n}\n\n# TODO: Renders #tags oddly.\nsub render-node($node) {\n    my $type = $node.contents.join('');\n    my $result = $node.type ~ '<' ~ $type;\n    if $node.type eq 'L' {\n        $result ~= '|' ~ $node.meta.join('');\n    }\n    $result ~= '>';\n\n    $result;\n}\n\n# given a slashy type, see if that file exists on disk\n# To work on case-insensitive file systems, we grep the dir listing\n# rather than check a preconstructed path.\n\nsub file-exists($type) {\n    next if $type.fc eq 'raku'|'perl'; # Too common\n\n    my @parts = $type.split('/');\n\n\n    my $path = \"doc/Type\".IO;\n    while @parts {\n       my $part = @parts.shift;\n       $part ~= '.rakudoc' unless @parts.elems;\n       return False unless $path.dir.grep(*.basename eq $part);\n       $path = $path.child($part);\n    }\n    return True;\n}\n\nsub is-valid-type($node, $parent, $file) {\n    # only care about I<>, C<>, L<>, etc.\n    return unless $node ~~ Pod::FormattingCode;\n    return if $node.type eq 'X'; # These are OK as is, and not user-visible\n\n    # Does this match a documented type?\n    my $type = $node.contents.join('');\n    my $type-slash = $type.subst('::', '/', :g);\n    my $type-colon = $type.subst('/', '::', :g);\n\n    return unless file-exists($type-slash);\n\n    if $file eq \"doc/Type/$type-slash.rakudoc\" {\n        # We are on the same page as this type. Don't link it, only C<> it.\n        if $node.type ne 'C' or $type ne $type-colon {\n            flunk \"{render-node($node)} should be C<$type-colon> - self reference\";\n        } elsif $parent ~~  Pod::FormattingCode {\n            flunk \"{$parent.type}<{render-node($node)}> should be C<$type> - bad parent FormattingCode - self reference\";\n        } else {\n            pass \"{render-node($node)} OK  - self reference\";\n        }\n        return;\n    }\n\n    # Might be nested but we only report on the innermost here.\n    if $node.type ne 'C' {\n        flunk \"{render-node($node)} should be L<C<$type>|/type/$type-colon>\";\n        return;\n    }\n\n    # Probably in a paragraph\n    if $parent === Nil or ! ($parent ~~  Pod::FormattingCode) {\n        flunk \"{render-node($node)} should be L<C<$type>|/type/$type-colon>\";\n        return;\n    }\n\n    # Ignore findings inside of an X<>\n    next if $parent.type eq 'X';\n\n    # Wrapped, but not in an L<>\n    if $parent.type ne 'L' {\n        flunk \"$parent.type<{render-node($node)}> should be L<C<$type>|/type/$type-colon> - bad parent FormattingCode\";\n        return;\n    }\n\n    my $meta = $parent.meta.join('');\n    if $meta eq \"/type/$type-colon\" or\n       $meta.starts-with: \"/type/{$type-colon}#\" {\n        # \\o/\n        pass \"L<{render-node($node)}|$meta>\";\n    } else {\n        if $meta.starts-with('/routine/') {\n            # Is this pointing to a routine page? /routine is generated, so we cannot verify\n            # the existence of an actual file; trust if present.\n            # Should be caught on error-report in site build\n            pass \"L<{render-node($node)}|$meta> - routine\";\n        } elsif $meta eq \"#method_$type\" {\n            pass \"L<{render-node($node)}|$meta> - in-document method link\";\n        } else {\n            # Wrapped in an L<> with wrong URL\n            flunk \"L<{render-node($node)}|$meta> should be L<C<$type>|/type/$type-colon> - bad link\";\n        }\n    }\n}\n\nsub walk-content($item, $parent, $file) {\n    is-valid-type($item, $parent, $file);\n\n    next unless $item.can('contents');\n    for @($item.contents) -> $child {\n        walk-content($child, $item, $file);\n    }\n}\n\n# Walk through pod on each file.\nfor @files -> $file {\n    my @chunks = extract-pod($file).contents;\n\n    # This emits pass or flunk for each local L<> found.\n    subtest $file => {\n        walk-content($_, Nil, $file) for @chunks;\n    }\n}\n"
  },
  {
    "path": "xt/search-categories.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\nuse File::Temp;\n\nuse Pod::Convenience;\nuse RakuDoc::Test::Files;\n\n=begin SYNOPSIS\n\nVerify that any X references in the documentation use one of the specific\nwhitelisted categories in this file. This helps the search function on the\nsite be cohesive and more useful for the end user.\n\n=end SYNOPSIS\n\n# Use list of allowed categories from documentations\nmy @categories = 'writing-docs/INDEXING.md'.IO.lines\\\n    .grep(*.starts-with('* `'))\\\n    .map({$_ ~~ / '* `' (<-[`]>*)/; ~$0})\\\n    .sort;\n\nplan +(my @files = RakuDoc::Test::Files.pods.grep({ not $_.contains('about')})) + 1;\n\nmy %*used-categories;\n\nfor @files -> $file {\n    subtest $file => {\n        my @examples = refs($file);\n        test-ref $_ for @examples;\n    }\n}\n\nif RakuDoc::Test::Files.all-files {\n    subtest \"Category usage\" => {\n        for @categories -> $category {\n            ok %*used-categories{$category}:exists, \"Category「$category」is used in documentation\";\n        }\n    }\n} else {\n    skip \"Can't check category usage when testing subset of files\", 1;\n}\n\nsub test-ref ($ref) {\n    my $contents = $ref<contents>.cache;\n    for $contents<> -> $item {\n        is $item.elems, 2, \"Correct dimension (2) for a search anchor '$contents.Str()' $ref<file>\";\n        next unless $item.elems == 2;\n        my $category = $item[0];\n        my $subject  = $item[1];\n        ok $category (elem) @categories, \"「$category」is a valid category\";\n        nok $subject.starts-with(' '), \"「$subject」should not start with a space\";\n        %*used-categories{$category}++;\n    }\n}\n\nsub refs (IO() $file) {\n    my @chunks = extract-pod($file).contents;\n    gather while @chunks {\n        my $chunk = @chunks.pop;\n        if $chunk ~~ Pod::FormattingCode && $chunk.type eq 'X' {\n            take %( contents => $chunk.meta.flat, :$file );\n        }\n        else {\n            @chunks.push(|$chunk.contents) if $chunk.^can('contents');\n        }\n    }\n}\n\nsub walk ($arg) {\n    given $arg {\n        when Pod::FormattingCode { walk $arg.contents }\n        when Str   { $arg }\n        when Array { $arg.map({walk $_}).join }\n    }\n}\n"
  },
  {
    "path": "xt/type-graph.rakutest",
    "content": "#!/usr/bin/env raku\n\nuse Test;\nuse Doc::TypeGraph;\n\nuse Telemetry; # pull in optional classes we can test\n\nmy $t = Doc::TypeGraph.new-from-file('type-graph.txt');\n\nfor $t.sorted -> $type {\n    next if $type.name.index('Metamodel').defined || $type.name eq 'PROCESS';\n    next if $type.packagetype eq 'role'|'module';\n    # these types does not support mro => whitelisted\n    next if $type.name eq any(<Failure MOP Routine::WrapHandle Encoding UInt>);\n    try {\n        my $expected = ~$type.mro;\n        my $got = ~::($type).^mro.map: *.^name;\n        is $got, $expected, $type;\n        CATCH {\n            default {\n                flunk \"Trouble with $type: $_\";\n            }\n        }\n    }\n}\n\ndone-testing;\n"
  }
]