## dist_cpan-LEMBARK-ProcStats.md
# NAME

ProcStats - dump rusage process statistics with optional label.

# SYNOPSIS

```
# display process stats provided by
# getrusage(2) & now() to stderr ($*ERR).
#
# Initial stats show all values as-is with an
# added "initial" and $*INIT-INSTANT.
#
# Successive calls print progressive stats
# for non-zero incremental differences with
# leading '+' to indicate differences.
#
# Final includes all values with totals from
# initial values and include a "Final" key
# with value of elapsed time from the program
# startup to the final sample.
#
# outputs are YAML array-of-hashes, with one
# document per print.
#
# see example/bare-for-loop

#!/usr/bin/env perl6
use v6.d;
use ProcStats;  # or ( :Print ) for print-stats.

print-stats :label( $*PROGRAM );

print-stats
for 1 .. 3;

print-stats( final => True );

# output #0 has all parameters without any differences
# (there is no prior sample to diff).
# successive stats w/o prior will show only outputs with
# differenes in stats other than user and wallclock time
# using a leading '+' for the offset values.
#
# if 'final' is used then all stats are output, even if
# they are zero, and Final => True is added to the output.
# (:final defaults to :first, :force).
#
# label is output if provided (e.g., :label($*PROGRAM) );

---
label    : ./bare-for-loop
output   : 0
sample   : 0
initial  : 1563047524.012407    # $*INIT-INSTANT
wtime    : 1563047524.627299    # now()
utime    : 0.269591
stime    : 0.038513
maxrss   : 105852
minflt   : 20822
majflt   : 0
inblock  : 0
oublock  : 8
---
output   : 1
sample   : 1
maxrss   : +760         # only stats with differnces
minflt   : +173         # are listed.
utime    : +0.018007    # utime and wtime will always grow,
wtime    : +0.008687    # returned with :force or other diff's.
---
<snip...>
---
output   : 4            # 4 == 4 => all samples were output
sample   : 4
inblock  : +0           # +0 => no change during execution
majflt   : +0
maxrss   : +1024        # >0 => growth compared to sample0
minflt   : +247
oublock  : +0
stime    : +0.000745    # system time during samples.
utime    : +0.038095    # user time during samples.
wtime    : +0.019526    # elapsed wallclock from sample0
final    : +0.804102    # elapsed wallclock from program init.

# Output is only provided if there are differences in
# the compared fields. If any of those are different
# then the wallclock, user, and system times are added
# the entire difference returned.
#
# :force & :first can be used with intermediate
# outputs to generate output for all fields or compute
# differenes with first sample.
#
# :final(True) defaults :force and :first to true.

print-stats :force;         # ouput zeros.
print-stats :first;         # compare to sample0.

print-stats :first :force;  # all stats compared to sample0.

# see example/rand-user-table

print-stats label => "$*PROGRAM";

for 1 .. 100
{
    (
        &user-add  => 0.10,
        &user-drop => 0.10,
        &user-op   => 0.80,
    ).Mix.roll( 1_000 )».()
    ;

    print-stats label => 'Keys: ' ~ %user-data.elems;
}

print-stats :final, label => 'Keys: ' ~ %user-data.elems;

# output

---
label    : exmaple/rand-user-table
output   : 0                        # first sample:
sample   : 0                        # output = sample = 0.
wtime    : 1563048388.1687117
utime    : 0.579475
stime    : 0
maxrss   : 116448
minflt   : 23573
majflt   : 0
inblock  : 0
oublock  : 8
---
label    : Keys: 19
output   : 1
sample   : 1
maxrss   : +3884
minflt   : +901
utime    : +0.100587
wtime    : +0.052823
---
<snip...>
---
label    : Keys: 60
output   : 14           # 1 .. 14 output have 1 .. 14
sample   : 14           # samples: something changed each time.
maxrss   : +264
minflt   : +24
utime    : +0.029787    # utime & wtime are alwyas output if
wtime    : +0.020622    # there are other differences.
---
label    : Keys: 117
output   : 15           # 15th output has 18th sample:
sample   : 18           # samples 15 .. 17 were unchanged.
minflt   : +27          # minflt increased 27 in sample 18.
utime    : +0.027277
wtime    : +0.022936
---
<snip...>

---
label    : Keys: 129
output   : 61           # 39 samples had no differences
sample   : 100
minflt   : +10          # minflt increased by 10.
utime    : +0.024304
wtime    : +0.024276
---
label    : Keys: 129
output   : 62           # 62 changes.
sample   : 101          # in 101 samples.
inblock  : +0           # +0 values never changed.
majflt   : +0
maxrss   : +9424
minflt   : +2323
oublock  : +0
stime    : +0
utime    : +2.361321
wtime    : +2.202044    # elapsed wallclock from first call.
final    : +0.804102    # sec from initial -> final wtime.

```

# DESCRIPTION

This module exports print-stats (via DEFAULT or :Print) or extract-stats & diff-stats (via :Extract). Together these give a simple interface for accessing process statistics via getrusage(2) on systems which support it.

## Subroutines

### Exported by default or with :Print.

* print-stats

Formats the result of calling diff-stats on extract-stats, passing through :force & :final.

### Exported with :Extract.

* extract-stats

Calls getrusage(2), removes the parameters not supported by Linux (see Procstats::IGNORE). getrusage returns user and system times as separate int's for seconds and microseconds. These are removed from the initial input, combined into a rational, and rounded to microseconds as "stime" & "utime". Additionally now() is rounded to microseconds and returned as "wtime".

* diff-stats

If :force is used then all non-ignored values are compared; if :first is used then differnces are compared with the initial sample not the prior one.

Note that :force & :first have no effect on the initial sample.

Normally compared incrmental keys are:

```
stime
maxrss
minflt majflt
inblock oublock

```

If at least one of these does not provide non-zero differences then nothing is printed. Using ":force" will cause diff-stats to always generate a list of differences and will always yield

## Notes

* Sample & Output

Comparing sample & output counts allows verifying average rate at which parameters change: output only increments when something changes, %sample increments with every call to extract-stats.

* Wallclock Time (wtime)

This is derived from Perl's now() result (rounded to microseconds). Combined with the program name ($\*PROGRAM), this makes a reasonable candiate key for tracking execution history over mulitple tests.

## Sample code.

* rand-user-table

This performs a set of random operations on a hash by adding keys, dropping keys, and incrementing the stored values.

It prints the stats every 1000 iterations of the trial:

```
for 1 .. 1000
{
    constant weighted_operations =
    (
        &user-add  => 0.10,
        &user-drop => 0.10,
        &user-op   => 0.80,
    ).Mix;

    weighted_operations.roll( 1_000 )».();

    print-stats label => 'Keys: ' ~ %user-data.elems;
}

```

The output illustrates adding progress information to the labels, and will [usually] show examples of the output count being lower than the sample count due to the compared statistics not changing.

Also note here that the final sample shows wallclock time less than user time: MOAR is threaded! Use wtime for elapsed:

stime will grow due to output from print-stats and overhead from calling getrusage(2). Where stime is very small it is probably due to overhead from ProcStats.

```
---
label    : Keys: 13

```

* Final : True output : 53 sample : 101 inblock : +0 majflt : +0 maxrss : +5768 minflt : +1467 oublock : +0 stime : +0.018914 utime : +2.24491 # 2.24 > 2.12 due to threading! wtime : +2.123665

# NOTES

* Linux-specific

This could easily be split into extract-stats with O/S-specific extractors and a top module with diff-stats and print-stats. If anyone has access to BSD, Windows, VMS, or OSX systems with Perl6 feel free to send me the information on how to extract the stats and I'll break this up into platform-specific extractors and the rest.

# SEE ALSO

* getrusage(2) getrusage(3p)

getrusage is POSIX (3p).

Thing is that Linux does not maintain values for all of the contents (see getrusage(2) for descriptions).

```
struct rusage
{
   struct timeval ru_utime; /* user CPU time used */
   struct timeval ru_stime; /* system CPU time used */
   long   ru_maxrss;        /* maximum resident set size */
 * long   ru_ixrss;         /* integral shared memory size */
 * long   ru_idrss;         /* integral unshared data size */
 * long   ru_isrss;         /* integral unshared stack size */
   long   ru_minflt;        /* page reclaims (soft page faults) */
   long   ru_majflt;        /* page faults (hard page faults) */
 * long   ru_nswap;         /* swaps */
   long   ru_inblock;       /* block input operations */
   long   ru_oublock;       /* block output operations */
 * long   ru_msgsnd;        /* IPC messages sent */
 * long   ru_msgrcv;        /* IPC messages received */
 * long   ru_nsignals;      /* signals received */
   long   ru_nvcsw;         /* voluntary context switches */
   long   ru_nivcsw;        /* involuntary context switches */
};

```

* timeval (3bsd)

Struct timeval is a pair of ints for seconds + microseconds which are dealt with by dividing the microseconcs and adding to get utime and stime in the reported stats.


## dist_github-alabamenhu-IntlPromptYesNo.md
> *Το «ναι» και το «όχι», αν και είναι οι πιο σύντομες από όλες τις λέξεις, χρειάζεται να τις σκεφθεί κανείς πολύ προηγουμένως.*
> — Πυθαγόρας

# Intl::Prompt::YesNo

A module to ask a user for a yes/no response in a localized command line interface.
To use:

```
use Intl::Prompt::YesNo

my $answer = prompt-yes-no 'Queres falar em português?', :language<pt>;
# Queres falar em português? [s/n]

if $answer {
  # they answered yes
} else {
  # they answered no
}

```

If the user responds in an affirmative manner, the sub `prompt-yes-no` will return `True`.
If they respond in a negative manner, it returns `False`.

The sub accepts a single positional argument, which is the message to display alongside the prompt.
It would be best to obtain such a string through a module like `Fluent`.
There are two named arguments available:

* **`:language`**
  The language should be a BCP-47 compliant language tag. It defaults to whatever `Intl::UserLanguage`'s `user-language` returns, so you don't know necessarily need to specify it.
* **`:long`**
  Many languages have multiple strings that are acceptable for the two responses.
  By default, the shortest ones are used (`y/n` in English, `s/n` for Portuguese).
  If you use `:long`, the longer ones are used (`yes/no`, or `sim/não` for Portuguese).
  In either case, all variants are accepted.

## Version history

* **v0.1**
  * Initial release

## License and Copyright

© 2020 Matthew Stephen Stuckwisch. Licensed under the Artistic License 2.0.
But as this is very simple, feel free to hack this code up and integrate it in your own code without need for attribution.


## dist_zef-raku-community-modules-ake.md
## ake [Tests on source](https://github.com/Raku/ake/actions/workflows/test.yaml)

`ake` is a make-a-like implemented in Raku. It was inspired by
[rake](https://github.com/ruby/rake).

### Installation

Ake is easily installable with [`zef`](https://github.com/ugexe/zef):

```
zef install ake

```

If you are using `rakubrew` in `shim` mode you will need to run
`rakubrew rehash` to make the `ake` executable available.

### Current status

Ake is fully-functional but may lack some advanced features. Feature
requests and PRs are welcome!

### Example

Create a file named `Akefile` with these contents:

```
task 'buy-food', {
    say 'Bought a salad.'
}

task 'shower', {
    say 'Showered.'
}

task 'morning' => <shower buy-food>;

task 'dinner' => <buy-food>, {
    say 'Yummy!'
}

```

Then you will be able to run `ake` from the same directory
(e.g. `ake morning`).

### License

Ake is available under Artistic License 2.0.


## paragraph.md
class RakuAST::Doc::Paragraph

Contains the information about a RakuDoc paragraph

```raku
class RakuAST::Doc::Paragraph { }
```

The `RakuAST::Doc::Paragraph` class contains the information about a logical paragraph in a `RakuDoc` block.

Support for [`RakuAST`](/type/RakuAST) functionality is available in language version `6.e+` and was added in Rakudo compiler release 2023.02. In earlier language versions it is only available when specifying:

```raku
use experimental :rakuast;
```

## [Object introspection](#class_RakuAST::Doc::Paragraph "go to top of document")[§](#Object_introspection "direct link")

`RakuAST::Doc::Paragraph` objects are typically created when parsing Raku Programming Language code that has `RakuDoc` markers in it. So most developers will only need to know how to introspect the objects created.

### [method atoms](#class_RakuAST::Doc::Paragraph "go to top of document")[§](#method_atoms "direct link")

```raku
.put for $paragraphs.atoms;
# Text before ␤B<and>␤ after markup␤

```

Returns the atoms of the paragraph. These are generally a mix of strings and [`RakuAST::Doc::Markup`](/type/RakuAST/Doc/Markup) objects.

### [method Str](#class_RakuAST::Doc::Paragraph "go to top of document")[§](#method_Str "direct link")

```raku
put $paragraph;  # Text before B<and> after markup␤␤

```

Returns the string for the paragraph, with any markup stringified.

### [method raku](#class_RakuAST::Doc::Paragraph "go to top of document")[§](#method_raku "direct link")

```raku
# method .gist falls back to .raku
say $block;  # RakuAST::Doc::Paragraph.new(...

```

Returns the string that is needed for the creation of the paragraph using [`RakuAST`](/type/RakuAST) calls.

# [Object creation](#class_RakuAST::Doc::Paragraph "go to top of document")[§](#Object_creation "direct link")

One seldom creates `RakuAST::Doc::Paragraph` objects directly. This documentation is intended for those few people who'd like to devise their own way of programmatically building a `RakuAST::Doc::Paragraph` object.

## [method new](#class_RakuAST::Doc::Paragraph "go to top of document")[§](#method_new "direct link")

```raku
method new(*@atoms)
```

The `new` method must be called to create a new `RakuAST::Doc::Paragraph` object. It takes any number of positional arguments as the atoms of the logical paragraph, where an atom is either a string or a [`RakuAST::Doc::Markup`](/type/RakuAST/Doc/Markup) object.

Typically a `RakuAST::Doc::Paragraph` object is only created if a logical paragraph has at least one markup object.

```raku
my $paragraph = RakuAST::Doc::Paragraph.new(
  "Text before ",
  RakuAST::Doc::Markup.new(:letter<B>, :atoms("and")),
  " after markup\n"
);

```

# [Object modification](#class_RakuAST::Doc::Paragraph "go to top of document")[§](#Object_modification "direct link")

## [method add-atom](#class_RakuAST::Doc::Paragraph "go to top of document")[§](#method_add-atom "direct link")

```raku
$paragraph.add-atom("baz\n");

```

Add an atom: should be a string, or a [`RakuAST::Doc::Markup`](/type/RakuAST/Doc/Markup) object.


## dist_github-moznion-Stream-Buffered.md
[![Build Status](https://travis-ci.org/moznion/p6-Stream-Buffered.svg?branch=master)](https://travis-ci.org/moznion/p6-Stream-Buffered)

# NAME

Stream::Buffered - Temporary buffer to save bytes

# SYNOPSIS

```
use Stream::Buffered;

my $buf = Stream::Buffered.new($length);

$buf.print("foo");
my Int $size = $buf.size;
my IO::Handle $io = $buf.rewind;

```

# DESCRIPTION

Stream::Buffered is a buffer class to store arbitrary length of byte strings and then get a seekable IO::Handle once everything is buffered. It uses Blob and temporary file to save the buffer depending on the length of the size.

This library is a perl6 port of [perl5's Stream::Buffered](https://metacpan.org/pod/Stream::Buffered).

# METHODS

## `new(Int $length, Int $maxMemoryBufferSize = 1024 * 1024) returns Stream::Buffered`

Creates instance.

When you specify negative value as `$maxMemoryBufferSize`, Stream::Buffered always uses Blob as buffer. Or when you specify 0 as `$maxMemoryBufferSize`, Stream::Buffered always uses temporary file as buffer.

If you pass 0 to the first argument, Stream::Buffered decides what kind of buffer type (Blob or temp file) to use automatically.

## `print(Stream::Buffered:D: *@text) returns Bool`

Append text to buffer.

## `size(Stream::Buffered:D:) returns Int`

Return the size of buffer.

## `rewind(Stream::Buffered:D:) returns IO::Handle`

Seek to the head of buffer and return buffer.

# SEE ALSO

* [perl5's Stream::Buffered](https://metacpan.org/pod/Stream::Buffered)

# AUTHOR

moznion [moznion@gmail.com](mailto:moznion@gmail.com)

# COPYRIGHT AND LICENSE

```
Copyright 2015 moznion

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.

```

And original perl5's Stream::Buffered is

```
The following copyright notice applies to all the files provided in
this distribution, including binary files, unless explicitly noted
otherwise.

Copyright 2009-2011 Tatsuhiko Miyagawa

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

```


## modules-extra.md
Module development utilities

What can help you write/test/improve your module(s)

Here is a list of modules that you can find in the Raku ecosystem which aim to make the experience of developing Raku modules more fun.

# [Module builder and authoring tools](#Module_development_utilities "go to top of document")[§](#Module_builder_and_authoring_tools "direct link")

Some modules and tools to help you with generating files that are part of a module distribution.

* [App::Mi6](https://raku.land/zef:skaji/App::Mi6) Minimal authoring tool for Raku
* [META6](https://raku.land/zef:jonathanstowe/META6) Do things with Raku `META` files
* [rakudoc](https://raku.land/cpan:SOFTMOTH/rakudoc) Generate documentation end-products

# [Tests](#Module_development_utilities "go to top of document")[§](#Tests "direct link")

Some tests of module quality.

* [Test::META](https://raku.land/zef:jonathanstowe/Test::META) Test your META6.json file
* [Test::Output](https://raku.land/zef:raku-community-modules/Test::Output) Test the output to STDOUT and STDERR your program generates
* [Test::Screen](https://raku.land/github:skids/Proc::Screen) Use **GNU screen** to test full screen VT applications
* [Test::When](https://raku.land/zef:raku-community-modules/Test::When) Control when your tests are run (author testing, online testing, etc.)

# [NativeCall](#Module_development_utilities "go to top of document")[§](#NativeCall "direct link")

Here some modules to help you work with NativeCall.

* [NativeHelpers::Array](https://raku.land/zef:jonathanstowe/NativeHelpers::Array) Provides routines to deal with CArray
* [App::GPTrixie](https://raku.land/github:Skarsnik/App::GPTrixie) Generate NativeCall code from C headers file
* [NativeCall::TypeDiag](https://raku.land/github:Skarsnik/NativeCall::TypeDiag) Provides routines to test your CStruct

# [Sample modules](#Module_development_utilities "go to top of document")[§](#Sample_modules "direct link")

Modules that exist only as minimalist examples, tests for installers, or skeletons.

* [Foo](https://raku.land/github:ugexe/Foo) A module with two distributions of different versions


## dist_zef-raku-community-modules-WWW-DuckDuckGo.md
[![Actions Status](https://github.com/raku-community-modules/WWW-DuckDuckGo/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/WWW-DuckDuckGo/actions) [![Actions Status](https://github.com/raku-community-modules/WWW-DuckDuckGo/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/WWW-DuckDuckGo/actions)

# NAME

WWW::DuckDuckGo - Bindings to DuckDuckGo search API

# SYNOPSIS

```
use WWW::DuckDuckGo;

my $duck = WWW::DuckDuckGo.new;
my $zeroclickinfo1 = $duck.zci('duck duck go');
my $zeroclickinfo2 = $duck.zci('one', 'another');

```

# DESCRIPTION

This class provides a way to get data from DuckDuckGo search service. The basic idea is to create a class instance that represents JSON answer from the server for every query.

This is a functional port of the Perl module of the same name, see [`WWW::DuckDuckGo`](https://metacpan.org/pod/WWW::DuckDuckGo).

# AUTHOR

Alexander Kiryuhin

# COPYRIGHT AND LICENSE

Copyright 2016 - 2021 Alexander Kiryuhin

Copyright 2024 Raku Community

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## dist_github-moznion-Backtrace-AsHTML.md
[![Build Status](https://travis-ci.org/moznion/p6-Backtrace-AsHTML.svg?branch=master)](https://travis-ci.org/moznion/p6-Backtrace-AsHTML)

# NAME

Backtrace::AsHTML - Displays back trace in HTML

# SYNOPSIS

```
use Backtrace::AsHTML;

my $trace = Backtrace.new;
my $html  = $trace.as-html;

```

# DESCRIPTION

Backtrace::AsHTML adds `as-html` method to <Backtrace> which displays the back trace in beautiful HTML, with code snippet context.

![](https://i.gyazo.com/6ac7f82ef6fb0a05d7de9a11dbdcaa0b.png)

This library is inspired by [Devel::StackTrace::AsHTML of perl5](https://metacpan.org/release/Devel-StackTrace-AsHTML) and much of code is taken from that.

# METHODS

* `as-html`

`as-html` shows the fully back trace in HTML.

This method will be added into <Backtrace> class automatically when used this.

# TODO

* show lexical variables for each frames (How?)
* show arguments for each frames? (How??)

# AUTHOR

moznion [moznion@gmail.com](mailto:moznion@gmail.com)

# COPYRIGHT AND LICENSE

```
Copyright 2015 moznion

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.

```

And license of the original perl5's Devel::StackTrace::AsHTML is

```
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

```


## dist_zef-kuerbis-Term-Choose-Util.md
# NAME

Term::Choose::Util - TUI-related functions for selecting directories, files, numbers and subsets of lists.

# DESCRIPTION

This module provides TUI-related functions for selecting directories, files, numbers and subsets of lists.

# CONSTRUCTOR

The constructor method `new` can be called with optional named arguments:

```
    my $new = Term::Choose::Util.new( :mouse( 1 ), ... )

```

# ROUTINES

Values in brackets are default values.

### Options available for all subroutines

* back

Customize the string of the menu entry "back".

Default: `BACK`

* clear-screen

If enabled, the screen is cleared before the output.

Values: [0],1.

* color

Enables the support for color and text formatting escape sequences.

Setting color to 1 enables the support for color and text formatting escape sequences except for the current selected element. If set to 2, also for the current selected element the color support is enabled (inverted colors).

Values: [0],1,2.

* confirm

Customize the string of the menu entry "confirm".

Default: `CONFIRM`.

* cs-label

The value of *cs-label* (current selection label) is a string which is placed in front of the current selection.

Defaults: `choose-directories`: 'Chosen Dirs: ', `choose-a-directory`: 'Directory: ', `choose-a-file`: 'File: '. For `choose-a-number`, `choose-a-subset` and `settings-menu` the default is undefined.

The current-selection output is placed between the info string and the prompt string.

* hide-cursor

Hide the cursor

Values: 0,[1].

* info

A string placed on top of of the output.

Default: undef

* margin

The option *margin* allows one to set a margin on all four sides.

*margin* expects a reference to an array with four elements in the following order:

* top margin (number of terminal lines)
* right margin (number of terminal columns)
* botton margin (number of terminal lines)
* left margin (number of terminal columns)

*margin* does not affect the *info* string. To add margins to the *info* string see *tabs-info*.

*margin* changes the default values of *tabs-prompt*.

Allowed values: 0 or greater. Elements beyond the fourth are ignored.

Default: undef

* mouse

Enable the mouse mode. An item can be chosen with the left mouse key, the right mouse key can be used instead of the SpaceBar key.

Values: [0],1.

* prompt

A string placed on top of the available choices.

If the *prompt* is set to the empty string, no prompt line is displayed.

Default: 'Your choice: '

* save-screen

0 - off (default)

1 - use the alternate screen

* tabs-info

The option *tabs-info* allows one to insert spaces at the beginning and the end of *info* lines.

*tabs-info* expects a reference to an array with one to three elements:

* the first element (initial tab) sets the number of spaces inserted at beginning of paragraphs
* the second element (subsequent tab) sets the number of spaces inserted at the beginning of all broken lines apart from the beginning of paragraphs
* the third element sets the number of spaces used as a right margin.

Allowed values: 0 or greater. Elements beyond the third are ignored.

default: If *margin* is set, the initial-tab and the subsequent-tab are set to left-*margin* and the right margin is set to right-*margin*. If *margin* is not defined, the default is undefined.

* tabs-prompt

The option *tabs-prompt* allows one to insert spaces at the beginning and the end of the current-selection and *prompt* lines.

*tabs-prompt* expects a reference to an array with one to three elements:

* the first element (initial tab) sets the number of spaces inserted at beginning of paragraphs
* the second element (subsequent tab) sets the number of spaces inserted at the beginning of all broken lines apart from the beginning of paragraphs
* the third element sets the number of spaces used as a right margin.

Allowed values: 0 or greater. Elements beyond the third are ignored.

default: If *margin* is set, the initial-tab and the subsequent-tab are set to left-*margin* and the right margin is set to right-*margin*. `choose-directories` and `choose-a-subset`: +2 for the subsequent-tab. Else the default is undefined.

## choose-a-directory

```
    my $chosen-directory = choose-a-directory( :1layout, ... )

```

With `choose-a-directory` the user can browse through the directory tree and choose a directory which is returned.

To move around in the directory tree:

* select a directory and press `Return` to enter in the selected directory.
* choose the "parent-dir" menu entry to move upwards.

To return the current working-directory as the chosen directory choose the "confirm" menu entry.

The "back" menu entry causes `choose-a-directory` to return nothing.

Following options can be set:

* alignment

Elements in columns are aligned to the left if set to 0, aligned to the right if set to 1 and centered if set to 2.

Values: [0],1,2.

* init-dir

Set the starting point directory. Defaults to the home directory (`$*HOME`).

* layout

See the option *layout* in [Term::Choose](https://github.com/kuerbis/Term-Choose-p6)

Values: 0,[1],2.

* order

If set to 1, the items are ordered vertically else they are ordered horizontally.

This option has no meaning if *layout* is set to 2.

Values: 0,[1].

* parent-dir

Customize the string of the menu entry "parent-dir".

Default: `..`

* show-hidden

If enabled, hidden directories are added to the available directories.

Values: 0,[1].

* [Options available for all subroutines](#Options available for all subroutines)

## choose-a-file

```
    my $chosen-file = choose-a-file( :1layout, ... )

```

Choose the file directory and then choose a file from the chosen directory. To return the chosen file select the "*confirm*" menu entry.

Options as in [choose-a-directory](#choose-a-directory) plus

* filter

If set, the value of this option is treated as a regex pattern.

Only files matching this pattern will be displayed.

The regex pattern is used as the value of `dir`s `:test` parameter.

* prompt2

While *prompt* is used in the directory menu, *prompt2* is the prompt in the menu where you select the file.

If *prompt2* is set to the empty string, no prompt line is displayed.

Default: value of *prompt*

## choose-directories

```
    my @chosen-directories = choose-directories( :1layout, ... )

```

`choose-directories` is similar to `choose-a-directory` but it is possible to return multiple directories.

Options as in [choose-a-directory](#choose-a-directory) plus

* prompt2

While *prompt* is used in the "Change Location" menu, *prompt2* is the prompt in the menu where you select the directories.

If *prompt2* is set to the empty string, no prompt line is displayed.

Default: value of *prompt*

## choose-a-number

```
    my $number = choose-a-number( 5, :cs-label<Testnumber>, ... );

```

This function lets you choose/compose a number (unsigned integer) which is then returned.

The fist argument is an integer and determines the range of the available numbers. For example setting the first argument to `4` would offer a range from `0` to `9999`. If not set, it defaults to `7`.

Options:

* default-number

Set a default number (unsigned integer in the range of the available numbers).

Default: undef

* small-first

Put the small number ranges on top.

* thousands-separator

Sets the thousands separator.

Default: `,`

* [Options available for all subroutines](#Options available for all subroutines)

## choose-a-subset

```
    my $subset = choose-a-subset( @available-items, :1layout, ... )

```

`choose-a-subset` lets you choose a subset from a list.

The subset is returned as an array.

The first argument is the list of choices.

Options:

* all-by-default

If enabled, all elements are selected if `CONFIRM` is chosen without any selected elements.

* alignment

Elements in columns are aligned to the left if set to 0, aligned to the right if set to 1 and centered if set to 2.

Values: [0],1,2.

* index

If true, the index positions in the available list of the made choices are returned.

Values: [0],1.

* keep-chosen

If enabled, the chosen items are not removed from the available choices.

Values: [0],1;

* layout

See the option *layout* in Term::Choose.

Values: 0,1,2,[3].

* mark

Expects as its value a reference to an array with indexes. Elements corresponding to these indexes are pre-selected when `choose-a-subset` is called.

* order

If set to 1, the items are ordered vertically else they are ordered horizontally.

This option has no meaning if *layout* is set to 3.

Values: 0,[1].

* prefix

*prefix* expects as its value a string. This string is put in front of the elements of the available list in the menu. The chosen elements are returned without this *prefix*.

Default: empty string.

* cs-begin

Info output: the *cs-begin* string is placed between the *cs-label* string and the chosen elements as soon as an element has been chosen.

Default: empty string

* cs-separator

Info output: *cs-separator* is placed between the chosen list elements.

Default: `,`

* cs-end

Info output: as soon as elements have been chosen the *cs-end* string is placed at the end of the chosen elements.

Default: empty string

* [Options available for all subroutines](#Options available for all subroutines)

To return the chosen subset select the "confirm" menu entry.

The "back" menu entry removes the last added chosen items. If the list of chosen items is empty, "back" causes `choose-a-subset` to return nothing.

## settings-menu

```
    my @menu = (
        ( 'enable-logging', "- Enable logging", ( 'NO', 'YES' )   ),
        ( 'case-sensitive', "- Case sensitive", ( 'NO', 'YES' )   ),
        ( 'attempts',       "- Attempts"      , ( '1', '2', '3' ) )
    );

    my %config = (
        'enable-logging' => 0,
        'case-sensitive' => 1,
        'attempts'       => 2
    );

    settings-menu( @menu, %config, :1mouse, ... );

```

The first argument is a list of lists. Each of the lists has three elements:

* The option name
* The prompt string
* A list of the available values for the option

The second argument is a hash:

* The hash keys are the option names
* The values are the indexes of the current value of the respective key/option. If an index is undefined or out of bonds, it is set to 0.

This hash is edited in place; the changes made by the user are saved in this hash.

Options:

* cs-begin

Info output: the *cs-begin* string is placed between the *cs-label* string and the key-value pairs.

Default: empty string

* cs-separator

Info output: *cs-separator* is placed between the key-value pairs.

Default: `,`

* cs-end

Info output: the *cs-end* string is placed at the end of the key-value pairs.

Default: empty string

* [Options available for all subroutines](#Options available for all subroutines)

The info output line is only shown if the option *cs-label* is set to a defined value.

When `settings-menu` is called, it displays for each list entry a row with the prompt string and the current value.

It is possible to scroll through the rows. If a row is selected, the set and displayed value changes to the next.After scrolling through the list once the cursor jumps back to the top row.

If the "back" menu entry is chosen, `settings-menu` does not apply the made changes and returns nothing. If the "confirm" menu entry is chosen, `settings-menu` applies the made changes in place to the passed configuration hash (second argument) and returns the number of made changes.

# REQUIREMENTS

Same requirements as Term::Choose.

# AUTHOR

Matthäus Kiem [cuer2s@gmail.com](mailto:cuer2s@gmail.com)

# CREDITS

Thanks to the people from [Perl-Community.de](http://www.perl-community.de), from [stackoverflow](http://stackoverflow.com) and from #perl6 on irc.freenode.net for the help.

# LICENSE AND COPYRIGHT

Copyright 2016-2024 Matthäus Kiem.

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## dist_zef-raku-community-modules-Test-Scheduler.md
[![Actions Status](https://github.com/raku-community-modules/Test-Scheduler/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Test-Scheduler/actions) [![Actions Status](https://github.com/raku-community-modules/Test-Scheduler/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Test-Scheduler/actions) [![Actions Status](https://github.com/raku-community-modules/Test-Scheduler/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Test-Scheduler/actions)

# NAME

Test::Scheduler - A Raku scheduler with virtualized time

# SYNOPSIS

```
use Test;
use Test::Scheduler;

sub timeout($source, $timeout) {
    supply {
        whenever $source -> $value {
            state $values++;
            emit $value;

            my $last-values = $values;
            whenever Promise.in($timeout) {
                if $last-values == $values {
                    die "Timed out";
                }
            }
        }
    }
}

{
    my $*SCHEDULER = Test::Scheduler.new;
    my $test-source = supply {
        for 1, 2, 5 {
            whenever Promise.in($_) {
                emit 'badger';
            }
        }
    }
    my $timed-out = timeout($test-source, 2);
    my @received;
    my $died = False;
    $timed-out.tap:
        { @received.push($_) },
        quit => { $died = True }

    is @received, [], 'No values yet';

    $*SCHEDULER.advance-by(1);
    is @received, ['badger'], 'one value after 1s';
    nok $died, 'No timeout yet';

    $*SCHEDULER.advance-by(1);
    is @received, ['badger', 'badger'], 'Two value after 2s';
    nok $died, 'No timeout yet';

    $*SCHEDULER.advance-by(1);
    is @received, ['badger', 'badger'], 'Still two value after 3s';
    nok $died, 'Still not timed out yet';

    $*SCHEDULER.advance-by(1);
    is @received, ['badger', 'badger'], 'Still two value after 4s';
    ok $died, 'And have timed out';
}

done-testing;

```

# DESCRIPTION

An implementation of the Raku `Scheduler` role that uses virtualized time. This allows for testing of code depending on constructs like `Promise.in(...)` and `Supply.interval(...)` more quickly and reliably than would be possible if real time were used.

# AUTHOR

Jonathan Worthington

# COPYRIGHT AND LICENSE

Copyright 2016 - 2024 Jonathan Worthington

Copyright 2024 Raku Community

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## trans.md
trans

Combined from primary sources listed below.

# [In Str](#___top "go to top of document")[§](#(Str)_method_trans "direct link")

See primary documentation
[in context](/type/Str#method_trans)
for **method trans**.

```raku
multi method trans(Str:D: Pair:D \what, *%n --> Str)
multi method trans(Str:D: *@changes, :complement(:$c), :squash(:$s), :delete(:$d) --> Str)
```

Replaces one or many characters with one or many characters. Ranges are supported, both for keys and values. Regexes work as keys. In case a list of keys and values is used, substrings can be replaced as well. When called with `:complement` anything but the matched value or range is replaced with a single value; with `:delete` the matched characters without corresponding replacement are removed. Combining `:complement` and `:delete` will remove anything but the matched values, *unless replacement characters have been specified*, in which case, `:delete` would be ignored. The adverb `:squash` will reduce repeated matched characters to a single character.

Example:

```raku
my $str = 'say $x<b> && $y<a>';
$str.=trans( '<' => '«' );
$str.=trans( '<' => '«', '>' => '»' );

$str.=trans( [ '<'   , '>'   , '&' ] =>
             [ '<', '>', '&' ]);

$str.=trans( ['a'..'y'] => ['A'..'z'] );

"abcdefghij".trans(/<[aeiou]> \w/ => '');                     # OUTPUT: «cdgh»

"a123b123c".trans(['a'..'z'] => 'x', :complement);            # OUTPUT: «axxxbxxxc»
"aaa1123bb123c".trans('a'..'z' => 'A'..'Z', :squash);         # OUTPUT: «A1123B123C»
"aaa1123bb123c".trans('a'..'z' => 'x', :complement, :squash); # OUTPUT: «aaaxbbxc»
```

In general, the strings will have the same length after the substitution:

```raku
say "a123b123c".trans('23' => '4');   # OUTPUT: «a144b144c␤»
say "a123b123c".trans('123' => 'þð'); # OUTPUT: «aþðþbþðþc␤»
```

`:squash` and `:delete` will have the same effect in this case making it a strict substitution:

```raku
say "a123b123c".trans('123' => 'þð', :squash); # OUTPUT: «aþðbþðc␤»
say "a123b123c".trans('123' => 'þð', :delete); # OUTPUT: «aþðbþðc␤»
```

`:delete` will also remove non-matched characters from the original string:

```raku
say "abc".trans("abc".comb => 1..2, :delete);  # OUTPUT: «12␤»
```

Please note that the behavior of the two versions of the multi method is slightly different. The first form will transpose only one character if the origin is also one character:

```raku
say "abcd".trans( "a" => "zz" );  # OUTPUT: «zbcd␤»
say "abcd".trans( "ba" => "yz" ); # OUTPUT: «zycd␤»

```

In the second case, behavior is as expected, since the origin is more than one char long. However, if the [`Pair`](/type/Pair) in the multi method does not have a `Str` as an origin or target, it is handled to the second multi method, and behavior changes:

```raku
say "abcd".trans: ["a"] => ["zz"]; # OUTPUT: «zzbcd␤»
```

In this case, neither origin nor target in the [`Pair`](/type/Pair) are `Str`; the method with the [`Pair`](/type/Pair) signature then calls the second, making this call above equivalent to `"abcd".trans: ["a"] => ["zz"],` (with the comma behind, making it a [`Positional`](/type/Positional), instead of a [`Pair`](/type/Pair)), resulting in the behavior shown as output.

# [In Cool](#___top "go to top of document")[§](#(Cool)_method_trans "direct link")

See primary documentation
[in context](/type/Cool#method_trans)
for **method trans**.

```raku
method trans(|)
```

Coerces the invocant to [`Str`](/type/Str) and calls [Str.trans](/type/Str#method_trans)


## dist_zef-lizmat-Time-localtime.md
[![Actions Status](https://github.com/lizmat/Time-localtime/workflows/test/badge.svg)](https://github.com/lizmat/Time-localtime/actions)

# NAME

Raku port of Perl's Time::localtime module

# SYNOPSIS

```
use Time::localtime;
printf "Year is %d\n", localtime.year + 1900;

$now = ctime();

use Time::localtime;
$date_string = ctime($file.IO.modified);

```

# DESCRIPTION

This module tries to mimic the behaviour of Perl's `Time::gmtime` module as closely as possible in the Raku Programming Language.

This module's default exports a `localtime` and `ctime` functions. The `localtime` function returns a "Time::localtime" object. This object has methods that return the similarly named structure field name from the C's tm structure from time.h; namely sec, min, hour, mday, mon, year, wday, yday, and isdst.

You may also import all the structure fields directly into your namespace as regular variables using the :FIELDS import tag. (Note that this still exports the functions.) Access these fields as variables named with a preceding tm\_. Thus, `$group_obj.year` corresponds to `$tm_year` if you import the fields.

The `ctime` function provides a way of getting at the scalar sense of the `localtime` function in Perl.

# PORTING CAVEATS

This module depends on the availability of POSIX semantics. This is generally not available on Windows, so this module will probably not work on Windows.

# AUTHOR

Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)

Source can be located at: <https://github.com/lizmat/Time-localtime> . Comments and Pull Requests are welcome.

# COPYRIGHT AND LICENSE

Copyright 2018, 2019, 2020, 2021 Elizabeth Mattijsen

Re-imagined from Perl as part of the CPAN Butterfly Plan.

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## dist_zef-knarkhov-Pheix.md
# Pheix dCMS implemented in Raku

**Pheix dCMS** is the [Raku](https://raku.org) driven decentralized Content Management System. It is extremely lightweight, flexible and customizable.

## Repository submodules

There are two external submodules in this repository.

1. `dcms-configuration`: <https://gitlab.com/pheix/dcms-configuration>
2. `dcms-resources`: <https://gitlab.com/pheix/dcms-resources>

These are mandatory for production-ready deployments and extended testing. Once you have cloned Pheix dCMS, run the command:

```
git submodule init && git submodule update --recursive --remote

```

## Installation guide

Check [Installation guide](https://gitlab.com/pheix/dcms-raku/-/wikis/installation-guide) section at our wiki for installation details, tips and tricks.

## API reference

Check [API reference — Pheix API](https://gitlab.com/pheix/dcms-raku/-/wikis/api-reference) section at our wiki for full API reference.

## Dependencies

Check the strict list of the [Pheix dCMS dependencies](https://gitlab.com/pheix/dcms-raku/wikis/module-dependencies) at our wiki.

## Borrowings

Pheix uses [CGI](https://github.com/viklund/november/blob/master/lib/November/CGI.pm) module from [November Wiki engine](https://github.com/viklund/november). Also the generic CGI tests are added to Pheix test bundle.

## License information

Pheix is free and open source software, so you can redistribute it and/or modify it under the terms of the [The Artistic License 2.0](https://opensource.org/licenses/Artistic-2.0).

## Changelog

All latest changes to this project are documented [at Pheix official website](https://pheix.org/changelog.txt).

## Author

Please contact me via [Matrix](https://matrix.to/#/@k.narkhov:matrix.org) or [LinkedIn](https://www.linkedin.com/in/knarkhov/). Your feedback is welcome at [narkhov.pro](https://narkhov.pro/contact-information.html).

## Donate

Pheix dCMS is an independent and self-funded project. All contributions and donations are greatly appreciated. Your support is important to me and inspires me to create new releases. Transfers in USDT, Ethereum, Bitcoin and TON are accepted. Please check the official [Donate](https://pheix.org/embedded/donate) page for details.


## fff.md
fff

Combined from primary sources listed below.

# [In Operators](#___top "go to top of document")[§](#(Operators)_infix_fff "direct link")

See primary documentation
[in context](/language/operators#infix_fff)
for **infix fff**.

```raku
sub infix:<fff>(Mu $a, Mu $b)
```

Performs a sed-like flipflop operation, wherein it returns `False` until the left argument smartmatches against `$_`, then returns `True` until the right argument smartmatches against `$_`.

Works similarly to [ff](/routine/ff), except that it only tries one argument per invocation. That is, if `$_` smartmatches the left argument, `fff` will **not** then try to match that same `$_` against the right argument.

```raku
for <AB C D B E F> {
    say $_ if /A/ fff /B/;         # OUTPUT: «AB␤C␤D␤B␤»
}
```

The non-sed-like flipflop (which after successfully matching the left argument against `$_` will try that same `$_` against the right argument and act accordingly). See [ff](/routine/ff).

This operator cannot be overloaded, as it's handled specially by the compiler.


## typesystem.md
## Chunk 1 of 2
Type system

Introduction to the type system of Raku

# [Definition of a Raku type](#Type_system "go to top of document")[§](#Definition_of_a_Raku_type "direct link")

A type defines a new object by creating a type object that provides an interface to create instances of objects or to check values against. Any type object is a subclass of [`Any`](/type/Any) or [`Mu`](/type/Mu). Introspection methods are provided via inheritance from those base classes and the introspection metamethods ([.^](/language/operators#methodop_.^)). A new type is introduced to the current scope by one of the following type declarators at compile time or with the [metaobject protocol](/language/mop) at runtime. All type names must be unique in their scope.

## [Default types](#Type_system "go to top of document")[§](#Default_types "direct link")

If no type is provided by the user Raku assumes the type to be [`Any`](/type/Any). This includes [containers](/language/containers), base-classes, [parameters](/language/signatures#Type_constraints) and return types.

```raku
my $a = 1;
$a = Nil;
say $a.^name;
# OUTPUT: «Any␤»

class C {};
say C.^parents(:all);
# OUTPUT: «((Any) (Mu))␤»
```

For containers the default type is [`Any`](/type/Any) but the default type constraint is [`Mu`](/type/Mu). Please note that binding replaces the container, not just the value. The type constraint may change in this case.

## [Type objects](#Type_system "go to top of document")[§](#Type_objects "direct link")

To test if an object is a type object, use [smartmatch](/language/operators#index-entry-smartmatch_operator) against a type constrained with a [type smiley](/language/signatures#Constraining_argument_definiteness) or [`.DEFINITE`](/language/mop#DEFINITE) method:

```raku
my $a = Int;
say $a ~~ Mu:U;
# OUTPUT: «True␤»
say not $a.DEFINITE;
# OUTPUT: «True␤»

```

`.DEFINITE` will return `True` if the invocant is an instance. If it returns `False`, then the invocant is a type object.

### [Undefinedness](#Type_system "go to top of document")[§](#Undefinedness "direct link")

Undefined objects maintain type information in Raku. Type objects are used to represent both undefinedness and the type of the undefined value. To provide a general undefined value use [`Any`](/type/Any). If differentiation from [`Any`](/type/Any), the default type for containers and arguments, is required use [`Mu`](/type/Mu).

Instances of objects created by [.CREATE](/type/Mu#method_CREATE) are by convention defined. The method [.defined](/type/Mu#routine_defined) will return `Bool::True` to indicate definedness. The exceptions to that rule are [`Nil`](/type/Nil) and [`Failure`](/type/Failure). Please note that any object is able to overload `.defined` and as such can carry additional information. Also, Raku makes a clear distinction between definedness and trueness. Many values are defined even though they carry the meaning of wrongness or emptiness. Such values are `0`, [Bool::False](/type/Bool), [()](/language/operators#term_(_)) (empty list) and [`NaN`](/type/Num#NaN).

Values can become undefined at runtime via [mixin](/language/operators#infix_but).

```raku
my Int $i = 1 but role :: { method defined { False } };
say $i // "undefined";
# OUTPUT: «undefined␤»
```

To test for definedness call `.defined`, use [//](/language/operators#infix_//), [with/without](/language/control#with_orwith_without) and [signatures](/language/signatures#Constraining_argument_definiteness).

### [Coercion](#Type_system "go to top of document")[§](#Coercion "direct link")

Turning one type into another is done with coercion methods that have the same name as the target type. This convention is made mandatory by [Signatures](/language/signatures#Coercion_type). The source type has to know how to turn itself into the target type. To allow built-in types to turn themselves into user defined types use [augment](/language/variables#The_augment_declarator) or the [MOP](/language/mop).

```raku
class C {
    has $.int;
    method this-is-c { put 'oi' x $!int ~ '‽' }
}

use MONKEY-TYPING;
augment class Int {
    method C { C.new(:int(self))}
}

my $i = 10;
$i.=C;
$i.this-is-c();
# OUTPUT: «oioioioioioioioioioi‽␤»
```

Raku provides methods defined in [`Cool`](/type/Cool) to convert to a target type before applying further operations. Most built-in types descend from [`Cool`](/type/Cool) and as such may provide implicit coercion that may be undesired. It is the responsibility of the user to care about trap-free usage of those methods.

```raku
my $whatever = "123.6";
say $whatever.round;
# OUTPUT: «124␤»
say <a b c d>.starts-with("ab");
# OUTPUT: «False␤»
```

# [Type declarators](#Type_system "go to top of document")[§](#Type_declarators "direct link")

Type declarators introduce a new type into the given scope. Nested scopes can be separated by `::`. New [packages](/language/packages) are created automatically if no such scope exists already.

```raku
class Foo::Bar::C {};
put Foo::Bar::.keys;
# OUTPUT: «C␤»
```

Forward declarations can be provided with a block containing only `...`, the ["stub" operator](/language/operators#listop_...). The compiler will check at the end of the current scope if the type is defined.

```raku
class C {...}
# many lines later
class C { has $.attr }
```

## [`class`](#Type_system "go to top of document")[§](#class "direct link")

The `class` declarator creates a compile time construct that is compiled into a type object. The latter is a simple Raku object and provides methods to construct instances by executing initializers and sub methods to fill all attributes declared in a class, and any parent class, with values. Initializers can be provided with the declaration of attributes or in constructors. It's the responsibility of the [`Metamodel::ClassHOW`](/type/Metamodel/ClassHOW) to know how to run them. This is the only magic part of building objects in Raku. The default parent type is [`Any`](/type/Any), which in turn inherits from [`Mu`](/type/Mu). The latter provides the default constructor `.new` which is named like this by convention. Aside from this, `.new` does not carry any special meaning nor is treated in any special way.

For more information how to use classes see the [Classes and objects](/language/classtut) tutorial.

### [Mixins](#Type_system "go to top of document")[§](#Mixins "direct link")

The type introduced by `class` can be extended with [infix:<but>](/language/operators#infix_but) at runtime. The original type is not modified, instead a new type object is returned and can be stored in a container that type checks successful against the original type or the role that is mixed in.

```raku
class A {}
role R { method m { say 'oi‽' } }
my R $A = A but R;
my $a1 = $A.new;
$a1.m;
say [$A ~~ R, $a1 ~~ R];
# OUTPUT: «oi‽␤[True True]␤»
```

### [Introspection](#Type_system "go to top of document")[§](#Introspection "direct link")

#### [Metaclass](#Type_system "go to top of document")[§](#Metaclass "direct link")

To test if a given type object is a class, test the metaobject method `.HOW` against [`Metamodel::ClassHOW`](/type/Metamodel/ClassHOW).

```raku
class C {};
say C.HOW ~~ Metamodel::ClassHOW;
# OUTPUT: «True␤»
```

### [Private attributes](#Type_system "go to top of document")[§](#Private_attributes "direct link")

Private [`Attribute`](/type/Attribute)s are addressed with any of the twigils `$!`, `@!` and `%!`. They do not have public accessor methods generated automatically. As such they can not be altered from outside the class they are defined in.

```raku
class C {
    has $!priv;
    submethod BUILD { $!priv = 42 }
};

say (.name, .package, .has_accessor) for C.new.^attributes;
# OUTPUT: «($!priv (C) False)␤»
```

### [Methods](#Type_system "go to top of document")[§](#Methods "direct link")

The `method` declarator defines objects of type [`Method`](/type/Method) and binds them to the provided name in the scope of a class. Methods in a class are `has` scoped by default. Methods that are `our` scoped are not added to the method cache by default and as such can not be called with the accessor sigil `$.`. Call them with their fully qualified name and the invocant as the first argument.

#### [Inheritance and multis](#Type_system "go to top of document")[§](#Inheritance_and_multis "direct link")

A normal method in a subclass does not compete with multis of a parent class.

```raku
class A {
    multi method m(Int $i){ say 'Int' }
    multi method m(int $i){ say 'int' }
}

class B is A {
    method m(Int $i){ say 'B::Int' }
}

my int $i;
B.new.m($i);
# OUTPUT: «B::Int␤»
```

#### [Only method](#Type_system "go to top of document")[§](#Only_method "direct link")

To explicitly state that a method is not a multi method use the `only` method declarator.

```raku
class C {
    only method m {};
    multi method m {};
};
# OUTPUT: «X::Comp::AdHoc: Cannot have a multi candidate for 'm' when an only method is also in the package 'C'␤»

```

#### [submethod BUILD](#Type_system "go to top of document")[§](#submethod_BUILD "direct link")

The [submethod](/type/Submethod) `BUILD` is (indirectly) called by [.bless](/type/Mu#method_bless). It is meant to set private and public attributes of a class and receives all named attributes passed into `.bless`. The default constructor [.new](/type/Mu#method_new) defined in [`Mu`](/type/Mu) is the method that invokes it. Given that public accessor methods are not available in `BUILD`, you must use private attribute notation instead.

```raku
class C {
    has $.attr;
    submethod BUILD (:$attr = 42) {
        $!attr = $attr
    };
    multi method new($positional) {
        self.bless(:attr($positional), |%_)
   }
};

C.new.say; C.new('answer').say;
# OUTPUT: «C.new(attr => 42)␤
#          C.new(attr => "answer")␤»
```

#### [Fallback method](#Type_system "go to top of document")[§](#Fallback_method "direct link")

A method with the special name `FALLBACK` will be called when other means to resolve the name produce no result. The first argument holds the name and all following arguments are forwarded from the original call. Multi methods and [sub-signatures](/language/signatures#Sub-signatures) are supported.

```raku
class Magic {
    method FALLBACK ($name, |c(Int, Str)) {
    put "$name called with parameters {c.raku}"  }
};
Magic.new.simsalabim(42, "answer");

# OUTPUT: «simsalabim called with parameters ⌈\(42, "answer")⌋␤»
```

#### [Reserved method names](#Type_system "go to top of document")[§](#Reserved_method_names "direct link")

Some built-in introspection methods are actually special syntax provided by the compiler, namely `WHAT`, `WHO`, `HOW` and `VAR`. Declaring methods with those names will silently fail. A dynamic call will work, what allows to call methods from foreign objects.

```raku
class A {
    method WHAT { "ain't gonna happen" }
};

say A.new.WHAT;    # OUTPUT: «(A)␤»
say A.new."WHAT"() # OUTPUT: «ain't gonna happen␤»

```

#### [Methods in package scope](#Type_system "go to top of document")[§](#Methods_in_package_scope "direct link")

Any `our` scoped method will be visible in the package scope of a class.

```raku
class C {
    our method packaged {};
    method loose {}
};
say C::.keys
# OUTPUT: «(&packaged)␤»
```

#### [Setting attributes with namesake variables and methods](#Type_system "go to top of document")[§](#Setting_attributes_with_namesake_variables_and_methods "direct link")

Instead of writing `attr => $attr` or `:attr($attr)`, you can save some typing if the variable (or method call) you're setting the attribute with shares the name with the attribute:

```raku
class A { has $.i = 42 };
class B {
    has $.i = "answer";
    method m() { A.new(:$.i) }
    #                  ^^^^  Instead of i => $.i or :i($.i)
};
my $a = B.new.m;
say $a.i; # OUTPUT: «answer␤»
```

Since `$.i` method call is named `i` and the attribute is also named `i`, Raku lets us shortcut. The same applies to `:$var`, `:$!private-attribute`, `:&attr-with-code-in-it`, and so on.

### [trait `is nodal`](#Type_system "go to top of document")[§](#trait_is_nodal "direct link")

Marks a [`List`](/type/List) method to indicate to hyperoperator to not descend into inner [`Iterable`](/type/Iterable)s to call this method. This trait generally isn't something end users would be using, unless they're subclassing or augmenting core [`List`](/type/List) type.

In order to demonstrate the difference consider the following examples, the first using a method (`elems`) that `is nodal` and the second using a method ([`Int`](/type/Int)) which is not nodal.

```raku
say ((1.0, "2", 3e0), [^4], '5')».elems; # OUTPUT: «(3, 4, 1)␤»
say ((1.0, "2", 3e0), [^4], '5')».Int    # OUTPUT: «((1 2 3) [0 1 2 3] 5)␤»
```

### [`handles`](#Type_system "go to top of document")[§](#trait_handles "direct link")

```raku
multi trait_mod:<handles>(Attribute:D $target, $thunk)
```

The [trait](/type/Sub#Traits) `handles` applied to an attribute of a class will delegate all calls to the provided method name to the method with the same name of the attribute. The object referenced by the attribute must be initialized. A type constraint for the object that the call is delegated to can be provided.

```raku
class A      { method m(){ 'A::m has been called.' } }
class B is A { method m(){ 'B::m has been called.' } }
class C {
    has A $.delegate handles 'm';
    method new($delegate){ self.bless(delegate => $delegate) }
};
say C.new(B.new).m(); # OUTPUT: «B::m has been called.␤»
```

Instead of a method name, a [`Pair`](/type/Pair) (for renaming), a list of names or [`Pair`](/type/Pair)s, a [`Regex`](/type/Regex) or a [`Whatever`](/type/Whatever) can be provided. In the latter case existing methods, both in the class itself and its inheritance chain, will take precedence. If even local `FALLBACK`s should be searched, use a [`HyperWhatever`](/type/HyperWhatever).

```raku
class A {
    method m1(){ 'A::m1 has been called.' }
    method m2(){ 'A::m2 has been called.' }
}

class C {
    has $.delegate handles <m1 m2> = A.new()
}
say C.new.m2; # OUTPUT: «A::m2 has been called.␤»

class D {
    has $.delegate handles /m\d/ = A.new()
}
say D.new.m1; # OUTPUT: «A::m1 has been called.␤»

class E {
    has $.delegate handles (em1 => 'm1') = A.new()
}
say E.new.em1; # OUTPUT: «A::m1 has been called.␤»

class F {
  # Delegates all methods from A
  has A $.delegate handles *;
}
say F.new.m1; # OUTPUT: «A::m1 has been called.␤»
say F.new.m2; # OUTPUT: «A::m2 has been called.␤»
```

### [trait `is`](#Type_system "go to top of document")[§](#trait_is "direct link")

```raku
multi trait_mod:<is>(Mu:U $child, Mu:U $parent)
```

The [trait](/type/Sub#Traits) `is` accepts a type object to be added as a parent class of a class in its definition. To allow multiple inheritance the trait can be applied more than once. Adding parents to a class will import their methods into the target class. If the same method name occurs in multiple parents, the first added parent will win.

If no `is` trait is provided the default of [`Any`](/type/Any) will be used as a parent class. This forces all Raku objects to have the same set of basic methods to provide an interface for introspection and coercion to basic types.

```raku
class A {
    multi method from-a(){ 'A::from-a' }
}
say A.new.^parents(:all).raku;
# OUTPUT: «(Any, Mu)␤»

class B {
    method from-b(){ 'B::from-b ' }
    multi method from-a(){ 'B::from-A' }
}

class C is A is B {}
say C.new.from-a();
# OUTPUT: «A::from-a␤»
```

### [`is rw`](#Type_system "go to top of document")[§](#trait_is_rw "direct link")

```raku
sub trait_mod:<is>(Mu:U $type, :$rw!)
```

The [trait](/type/Sub#Traits) `is rw` on a class will create writable accessor methods on all public attributes of that class.

```raku
class C is rw {
    has $.a;
};
my $c = C.new.a = 42;
say $c; # OUTPUT: «42␤»
```

### [trait `is required`](#Type_system "go to top of document")[§](#trait_is_required "direct link")

```raku
multi trait_mod:<is>(Attribute $attr, :$required!)
multi trait_mod:<is>(Parameter:D $param, :$required!)
```

Marks a class or roles attribute as required. If the attribute is not initialized at object construction time throws [`X::Attribute::Required`](/type/X/Attribute/Required).

```raku
class Correct {
    has $.attr is required;
}
say Correct.new(attr => 42);
# OUTPUT: «Correct.new(attr => 42)␤»

class C {
    has $.attr is required;
}
C.new;
CATCH { default { say .^name => .Str } }
# OUTPUT: «X::Attribute::Required => The attribute '$!attr' is required, but you did not provide a value for it.␤»
```

Note a class with a private attribute will give the same error:

```raku
class D {
    has $!attr is required;
}
D.new;
CATCH { default { say .^name => .Str } }
# OUTPUT: «X::Attribute::Required => The attribute '$!attr' is required, but you did not provide a value for it.␤»
```

You can provide a reason why it's required as an argument to `is required`

```raku
class Correct {
    has $.attr is required("it's so cool")
};
say Correct.new();
# OUTPUT: «The attribute '$!attr' is required because it's so cool,␤but you did not provide a value for it.␤»

```

### [trait `hides`](#Type_system "go to top of document")[§](#trait_hides "direct link")

The trait `hides` provides inheritance without being subject to [re-dispatching](/language/functions#Re-dispatching).

```raku
class A {
    method m { say 'i am hidden' }
}
class B hides A {
    method m { nextsame }
    method n { self.A::m }
};

B.new.m;  # No output
B.new.n;  # OUTPUT: «i am hidden␤»
```

The trait `is hidden` allows a class to hide itself from [re-dispatching](/language/functions#Re-dispatching).

```raku
class A is hidden {
    method m { say 'i am hidden' }
}
class B is A {
    method m { nextsame }
    method n { self.A::m }
}

B.new.m; # No output
B.new.n; # OUTPUT: «i am hidden␤»
```

Classes declared with `is hidden` also generate slightly different method signatures. To facilitate re-dispatch, typical methods are automatically provided with an extra `*%_` parameter that [captures extra named arguments](/type/Method#index-entry-*%___(extra_named_arguments)). Because classes declared with `is hidden` don't participate in re-dispatch, their methods don't receive this extra parameter.

### [trait `trusts`](#Type_system "go to top of document")[§](#trait_trusts "direct link")

To allow one class to access the private methods of another class use the trait `trusts`. A forward declaration of the trusted class may be required.

```raku
class B {...};
class A {
    trusts B;
    has $!foo;
    method !foo { return-rw $!foo }
    method raku { "A.new(foo => $!foo)" }
};
class B {
    has A $.a .= new;
    method change { $!a!A::foo = 42; self }
};
say B.new.change;
# OUTPUT: «B.new(a => A.new(foo => 42))␤»
```

### [Augmenting a class](#Type_system "go to top of document")[§](#Augmenting_a_class "direct link")

To add methods and attributes to a class at compile time use `augment` in front of a class definition fragment. The compiler will demand the pragmas `use MONKEY-TYPING` or `use MONKEY` early in the same scope. Please note that there may be performance implications, hence the pragmas.

```raku
use MONKEY; augment class Str {
    method mark(Any :$set){
        state $mark //= $set; $mark
    }
};
my $s = "42";
$s.mark(set => "answer");
say $s.mark
# OUTPUT: «answer␤»
```

There are few limitations of what can be done inside the class fragment. One of them is the redeclaration of a method or sub into a multi. Using added attributes is not implemented. Please note that adding a multi candidate that differs only in its named parameters will add that candidate behind the already defined one and as such it won't be picked by the dispatcher.

## [`role`](#Type_system "go to top of document")[§](#role "direct link")

Roles are class fragments, which allow the definition of interfaces that are shared by classes. The `role` declarator also introduces a type object that can be used for type checks. Roles can be mixed into classes and objects at runtime and compile time. The `role` declarator returns the created type object thus allowing the definition of anonymous roles and in-place mixins.

```raku
role Serialize {
    method to-string { self.Str }
    method to-number { self.Num }
}

class A does Serialize {}
class B does Serialize {}

my Serialize @list;
@list.push: A.new;
@list.push: B.new;

say @list».to-string;
# OUTPUT: «[A<57192848> B<57192880>]␤»
```

Use `...` as the only element of a method body to declare a method to be abstract. Any class getting such a method mixed in has to overload it. If the method is not overloaded before the end of the compilation unit [`X::Comp::AdHoc`](/type/X/Comp/AdHoc) will be thrown.

```raku
EVAL 'role R { method overload-this(){...} }; class A does R {}; ';
CATCH { default { say .^name, ' ', .Str } }
# OUTPUT: «X::Comp::AdHoc Method 'overload-this' must be implemented by A because it is required by roles: R.␤»
```

### [Auto-punning](#Type_system "go to top of document")[§](#Auto-punning "direct link")

A role can be used instead of a class to create objects. Since roles can't exist at runtime, a class of the same name is created that will type check successful against the role.

```raku
role R { method m { say 'oi‽' } };
R.new.^mro.say;
# OUTPUT: «((R) (Any) (Mu))␤»
say R.new.^mro[0].HOW.^name;
# OUTPUT: «Perl6::Metamodel::ClassHOW␤»
say R.new ~~ R;
# OUTPUT: «True␤»
```

### [trait `does`](#Type_system "go to top of document")[§](#trait_does "direct link")

The trait `does` can be applied to roles and classes providing compile time mixins. To refer to a role that is not defined yet, use a forward declaration. The type name of the class with mixed in roles does not reflect the mixin, a type check does. If methods are provided in more than one mixed in role, the method that is defined first takes precedence. A list of roles separated by comma can be provided. In this case conflicts will be reported at compile time.

```raku
role R2 {...};
role R1 does R2 {};
role R2 {};
class C does R1 {};

say [C ~~ R1, C ~~ R2];
# OUTPUT: «[True True]␤»
```

For runtime mixins see [but](/language/operators#infix_but) and [does](/language/operators#infix_does).

### [Parameterized](#Type_system "go to top of document")[§](#Parameterized "direct link")

Roles can be provided with parameters in-between `[]` behind a roles name. [Type captures](/language/signatures#Type_captures) are supported.

```raku
role R[$d] { has $.a = $d };
class C does R["default"] { };

my $c = C.new;
say $c;
# OUTPUT: «C.new(a => "default")␤»
```

Parameters can have type constraints, `where` clauses are not supported for types but can be implemented via [`subset`s](#subset).

```raku
class A {};
class B {};
subset A-or-B where * ~~ A|B;
role R[A-or-B ::T] {};
R[A.new].new;
```

Default parameters can be provided.

```raku
role R[$p = fail("Please provide a parameter to role R")] {};
my $i = 1 does R;
CATCH { default { say .^name, ': ', .Str} }
# OUTPUT: «X::AdHoc: Could not instantiate role 'R':␤Please provide a parameter to role R␤»
```

### [As type constraints](#Type_system "go to top of document")[§](#As_type_constraints "direct link")

Roles can be used as type constraints wherever a type is expected. If a role is mixed in with `does` or `but`, its type-object is added to the type-object list of the object in question. If a role is used instead of a class (using auto-punning), the auto-generated class' type-object, of the same name as the role, is added to the inheritance chain.

```raku
role Unitish[$unit = fail('Please provide a SI unit quantifier as a parameter to the role Unitish')] {
    has $.SI-unit-symbol = $unit;
    method gist {
        given self {
            # ...
            when * < 1 { return self * 1000 ~ 'm' ~ $.SI-unit-symbol }
            when * < 1000 { return self ~ $.SI-unit-symbol }
            when * < 1_000_000 { return self / 1_000 ~ 'k' ~ $.SI-unit-symbol }
            # ...
        }
    }
}

role SI-second   does Unitish[<s>] {}
role SI-meter    does Unitish[<m>] {}
role SI-kilogram does Unitish[<g>] {}

sub postfix:<s>(Numeric $num) { ($num) does SI-second }
sub postfix:<m>(Numeric $num) { ($num) does SI-meter }
sub postfix:<g>(Numeric $num) { ($num) does SI-kilogram }
sub postfix:<kg>(Numeric $num){ ($num * 1000) does SI-kilogram }

constant g = 9.806_65;

role SI-Newton does Unitish[<N>] {}

multi N(SI-kilogram $kg, SI-meter $m, SI-second $s --> SI-Newton ){ ($kg * ($m / $s²)) does SI-Newton }
multi N(SI-kilogram $kg --> SI-Newton)                            { ($kg * g) does SI-Newton }

say [75kg, N(75kg)];
# OUTPUT: «[75kg 735.49875kN]␤»
say [(75kg).^name, N(75kg).^name];
# OUTPUT: «[Int+{SI-kilogram} Rat+{SI-Newton}]␤»

```

## [`enum`](#Type_system "go to top of document")[§](#enum "direct link")

Enumerations provide constant key-value-pairs with an associated type. Any key is of that type and injected as a symbol into the current scope. If the symbol is used, it is treated as a constant expression and the symbol is replaced with the value of the enum-pair. Any Enumeration inherits methods from the role [`Enumeration`](/type/Enumeration). Complex expressions for generating key-value pairs are not supported. In general, an `enum` is a [`Map`](/type/Map) whose elements have the [`Enumeration`](/type/Enumeration) role mixed in; this role includes, for each element, an index which creates an order on the map.

Stringification of the symbol, which is done automatically in string context and is exactly equal to its name, which is also the key of the enum-pair.

```raku
enum Names ( name1 => 1, name2 => 2 );
say name1, ' ', name2; # OUTPUT: «name1 name2␤»
say name1.value, ' ', name2.value; # OUTPUT: «1 2␤»
```

Comparing symbols will use type information and the value of the enum-pair. As value types [`Num`](/type/Num) and [`Str`](/type/Str) are supported.

```raku
enum Names ( name1 => 1, name2 => 2 );
sub same(Names $a, Names $b){
   $a eqv $b
}

say same(name1, name1); # OUTPUT: «True␤»
say same(name1, name2); # OUTPUT: «False␤»
my $a = name1;
say $a ~~ Names; # OUTPUT: «True␤»
say $a.^name;    # OUTPUT: «Names␤»
```

All keys have to be of the same type.

```raku
enum Mass ( mg => 1/1000, g => 1/1, kg => 1000/1 );

say Mass.enums;
# OUTPUT: «Map.new((g => 1, kg => 1000, mg => 0.001))␤»
```

And you can use any kind of symbol:

```raku
enum Suit <♣ ♦ ♥ ♠>;
```

As long as you refer to that symbol using the full syntax:

```raku
say Suit::<♣>; # OUTPUT: «♣␤»
my $heart = '♥';
say Suit::«$heart»; # OUTPUT: «♥␤»

```

Attempting to access unicode enum keys without said syntax will result in an error:

```raku
say ♣ ; # OUTPUT: «(exit code 1) ===SORRY!===␤Argument to "say" seems to be malformed…

```

If no value is given [`Int`](/type/Int) will be assumed as the values type and incremented by one per key starting at zero. As enum key types [`Int`](/type/Int), [`Num`](/type/Num), [`Rat`](/type/Rat) and [`Str`](/type/Str) are supported.

```raku
enum Numbers <one two three four>;

say Numbers.enums;
# OUTPUT: «Map.new((four => 3, one => 0, three => 2, two => 1))␤»
```

A different starting value can be provided.

```raku
enum Numbers «:one(1) two three four»;

say Numbers.enums;
# OUTPUT: «Map.new((four => 4, one => 1, three => 3, two => 2))␤»
```

You can also do this with the **()** form of the initializer, but will need to quote keys that do not have a value:

```raku
enum Numbers (
  one => 1,
  'two',
  'three',
  'four'
);
```

Enums can also be anonymous, with the only difference with named `enum`s being that you cannot use it in [`Signature`](/type/Signature)s or to declare variables.

```raku
my $e = enum <one two three>;
say two;       # OUTPUT: «two␤»
say one.^name; # OUTPUT: «␤»
say $e.^name;  # OUTPUT: «Map␤»
```

There are various methods to get access to the keys and values of the symbols that have been defined. All of them turn the values into [`Str`](/type/Str), which may not be desirable. By treating the enum as a package, we can get a list of types for the keys.

```raku
enum E <one two>;
my @keys = E::.values;
say @keys.map: *.raku;
# OUTPUT: «(E::one E::two)␤» or «(E::two E::one)␤»
```

Note that, as the output above indicates, the iteration order of enums is not guaranteed. This is because the methods that "iterate over" an enum do not iterate *directly* on the enum (which, after all, is not iterable). Instead, these iteration methods create a [`Map`](/type/Map) with the same keys and values as the enum. Because [`Map`](/type/Map)s provide only unordered, iteration the iteration methods on an enum do as well. If you need to iterate an enum in order, you can sort on its `value`, for example with `E.enums.sort(*.value)`.

With the use of **()** parentheses, an enum can be defined using any arbitrary dynamically defined list. The list should consist of Pair objects:

For example, in file `config` we have:

｢text｣ without highlighting

```

```

a 1
b 2

```

```

We can create an enum using it with this code:

```raku
enum ConfigValues ('config'.IO.lines.map({ my ($key, $value) = $_.words


## typesystem.md
## Chunk 2 of 2
; $key => $value }));
say ConfigValues.enums;          # OUTPUT: «Map.new((a => 1, b => 2))␤»

```

Firstly, we read lines from `config` file, split every line using `words` method and return resulting pair for every line, thus creating a List of Pairs.

### [Typing Enums](#Type_system "go to top of document")[§](#Typing_Enums "direct link")

When declaring enums with an explicit scope, a type may be provided, which will be used to typecheck the enum's values:

```raku
my Str enum Foo (foo => 'foo');

```

All enum pairs are typed as [`Enumeration`](/type/Enumeration). In addition, when the enum values are typed as [`Numeric`](/type/Numeric), [`Stringy`](/type/Stringy), or a combination of these two types, enum pairs also do the `NumericEnumeration`, `StringyEnumeration`, and `NumericStringyEnumeration` roles respectively. These simply determine how enum pairs get stringified with the [`Str`](/type/Str) method.

Given that these types are roles, naturally you can provide your own roles when declaring an enum, which allows you to give them custom behavior and state. For example, to make it simpler to check if a number matches a flag in a bitmask enum, you could write a `BitmaskEnumeration` role with an `ACCEPTS` method to handle this via smartmatching:

```raku
role BitmaskEnumeration {
    multi method ACCEPTS(::?CLASS:D: Int:D $value --> Bool:D) {
        so $value +& self.value
    }
}

enum Flags does BitmaskEnumeration (
    FLAG_FOO => 0b001,
    FLAG_BAR => 0b010,
    FLAG_BAZ => 0b100,
);

say 0b111 ~~ FLAG_FOO & FLAG_BAR & FLAG_BAZ; # OUTPUT: «True␤»

```

### [Metaclass](#Type_system "go to top of document")[§](#Metaclass_0 "direct link")

To test if a given type object is an `enum`, test the metaobject method `.HOW` against [`Metamodel::EnumHOW`](/type/Metamodel/EnumHOW) or simply test against the [`Enumeration`](/type/Enumeration) role.

```raku
enum E(<a b c>);
say E.HOW ~~ Metamodel::EnumHOW; # OUTPUT: «True␤»
say E ~~ Enumeration;            # OUTPUT: «True␤»
```

### [Methods](#Type_system "go to top of document")[§](#Methods_0 "direct link")

See the [`Enumeration`](/type/Enumeration) role for available methods on enum types and enum-pairs.

### [Coercion](#Type_system "go to top of document")[§](#Coercion_0 "direct link")

If you want to coerce the value of an enum element to its proper enum object, use the coercer with the name of the enum:

```raku
my enum A (sun => 42, mon => 72);
A(72).pair.say;   # OUTPUT: «mon => 72␤»
A(1000).say; # OUTPUT: «(A)␤»
```

The last example shows what happens if there is no enum-pair that includes that as a value.

## [`module`](#Type_system "go to top of document")[§](#module "direct link")

Modules are usually one or more source files that expose Raku constructs, such as classes, roles, grammars, subroutines and variables. Modules are usually used for distributing Raku code as libraries which can be used in another Raku program.

For a full explanation see [Modules](/language/modules).

## [`package`](#Type_system "go to top of document")[§](#package "direct link")

Packages are nested namespaces of named program elements. Modules, classes and grammars are all types of package.

For a full explanation see [Packages](/language/packages).

## [`grammar`](#Type_system "go to top of document")[§](#grammar "direct link")

Grammars are a specific type of class intended for parsing text. Grammars are composed of rules, tokens and regexes which are actually methods, since grammars are classes.

For a full explanation see [Grammars](/language/grammars).

## [`subset`](#Type_system "go to top of document")[§](#subset "direct link")

A `subset` declares a new type that will re-dispatch to its base type. If a [`where`](/language/signatures#index-entry-where_clause) clause is supplied any assignment will be checked against the given code object.

```raku
subset Positive of Int where * > -1;
my Positive $i = 1;
$i = -42;
CATCH { default { put .^name,': ', .Str } }
# OUTPUT: «X::TypeCheck::Assignment: Type check failed in assignment to $i; expected Positive but got Int (-42)␤»
```

Subsets can be used in signatures, e.g. by typing the output:

```raku
subset Foo of List where (Int,Str);
sub a($a, $b, --> Foo) { $a, $b }
# Only a List with the first element being an Int and the second a Str will pass the type check.
a(1, "foo");  # passes
a("foo", 1);  # fails
```

If you skip the base type, it defaults to [`Any`](/type/Any). So the following two are equivalent:

```raku
subset A-or-B where * ~~ A | B

```

```raku
subset A-or-B of Any where * ~~ A | B

```

Subsets can be anonymous, allowing inline placements where a subset is required but a name is neither needed nor desirable.

```raku
my enum E1 <A B>;
my enum E2 <C D>;
sub g(@a where { .all ~~ subset :: where E1|E2 } ) {
    say @a
}
g([A, C]);
# OUTPUT: «[A C]␤»
```

Subsets can be used to check types dynamically, which can be useful in conjunction with [require](/language/modules#require).

```raku
require ::('YourModule');
subset C where ::('YourModule::C');

```

# [Versioning, authorship, and API version.](#Type_system "go to top of document")[§](#Versioning,_authorship,_and_API_version. "direct link")

When you declare a type you can pass it a version, author, and/or API number, all of which you can subsequently introspect. The versioning, authorship, and/or API number of a type can be applied via the adverbs `:ver<>`, `:auth<>`, and `:api<>` respectively. All of them take a string as argument; for `:ver` the string is converted to a [`Version`](/type/Version) object, and for `:api` the string is converted into an [allomorph](/language/glossary#Allomorph) [`IntStr`](/type/IntStr) object. `:auth` generally takes the form `hosting:ID`, as in `github:github-user` or `gitlab:gitlab-user`.

To query the version, author, and API version of a type use [`.^ver`](/type/Metamodel/Versioning#method_ver), [`.^auth`](/type/Metamodel/Versioning#method_auth), and [`.^api`](/type/Metamodel/Versioning#method_api) respectively, as illustrated down below by querying a `class`.

```raku
class C:ver<4.2.3>:auth<github:jane>:api<1> {}
say C.^ver;       # OUTPUT: «v4.2.3␤»
say C.^ver.parts; # OUTPUT: «(4 2 3)␤»
say C.^auth;      # OUTPUT: «github:jane␤»
say C.^api;       # OUTPUT: «1␤»
```

In a similar fashion, `role`s, `grammar`s, and `module`s can be queried about the aforementioned information.


## dist_cpan-JJATRIA-App-Lorea.md
# lorea

A command line utility to execute commands on filesystem changes.

The interface should be fairly familiar for users of [reflex](https://github.com/cespare/reflex). See
[the examples section](#examples) below for some possible ways to use it.

## Installation

```
$ zef install App::Lorea

```

## Usage

```
lorea [options] -- command [args]

```

## Options

```
    --all                    Include all normally ignored files
-c, --config     STRING      The path to a configuration file
    --help                   Display usage information
-R, --ignore     REGEX ...   A regular expression to ignore filenames
-r, --regex      REGEX ...   A regular expression to match filenames
-e, --sequential             Run commands sequentially from config file
-s, --start-service          Run command as a service
    --substitute STRING      Set the string to be used as placeholder
-v, --verbose                Print tracing information
    --version                Print the version of the command and compiler

```

Options marked with `...` can be provided multiple times.

Values marked as `REGEX` must be compilable as Raku [regular expressions](https://docs.raku.org/language/regexes).

## Overview

When `lorea` is run, it will monitor your current directory, and any
directories under it, for any file-system changes. When a file is changed
or added, it will be matched against the patterns you've specified (see
[below](#matching) for details about how the matching is done).

If the event matches, the command you've specified will be run, or
restarted if you enabled the `--start-service` flag.

If the command you've specified includes the `{}` string, this will be
replaced by the absolute path of the file that has changed. All instances
of this placeholder string will be replaced. If you need to use the `{}`
string for something else, you can specify a different placeholder string
with the `--substitute` option.

### Matching

Patterns to match can be specified to `lorea` with either `--regex` or
`--ignore`. Both of these options take Raku regular expressions, with the
difference that any match for the former will trigger an event, while every
match for the latter will eplicitly *not* trigger one.

Paths are normalised before being matched, and converted to paths relative
to the current directory without a leading `./`. Matching directories will
have a trailing slash (`/`).

If no pattern is specified, all file-system changes will match.

### Default ignores

By default, `lorea` ignores some common patterns to make it easier to use
in most cases.

* Files and directories with a leading dot (`.`), which are considered
  hidden in Unix-like systems.
* Common swap files, including those ending in `.swp`, `.swx`, and `~`.

The `--all` option disables these defaults. This flag will take effect if
set either at the top level, or in any of the watchers specified in the
configuration file (see below).

You can see the global ignores by setting the `--verbose` option.

## Configuration

The `--config` option can be used to specify a configuration to use to start
several watchers at the same time. The behaviour of these watchers can be
set independently.

The format of this file is intentionally very limited. A valid file will look
something like this:

```
# Rebuild SCSS when it changes
-r '\.scss$' -- \
   sh -c 'sass {} `basename {} .scss`.css'

# Restart server when ruby code changes
-s -r '\.rb$' -- \
    ./bin/run_server.sh

```

Each line will be interpreted as the parameters to a separate invokation of
`lorea`. Lines must not include the executable name (that will be filled in
internally). The parameters to a single invokation can be broken into multiple
lines if they end with a trailing backslash (`\`).

Empty lines, and lines begininng with a hash (`#`) will be ignored.

With the exception of `--help` , `--sequential, and` --config`itself, all options are valid within a configuration file. If the`--config`option is set, the only other flags that are allowed at the top level are`--verbose`and`--sequential`.

### Sequential execution

When using a config file to run multiple simultaneous commands, each of them
will be started asynchronously whenever posible. This means that, while there
will only be one instance of a particular command, two different commands may
overlap. This is usually what you want.

As a concrete example, consider this config file:

```
-- sh -c 'for i in `seq 1 5`; do sleep 0.1; echo first; done'
-- sh -c 'for i in `seq 1 5`; do sleep 0.1; echo second; done'

```

When this runs, you might see something like this:

```
second
first
second
first
first
second
second
first
second
first

```

Note that, since both commands started at the same time, the output of both is
interleaved. If this is not what you want, you can ensure only one command runs
at a time with the `--sequential` flag used at the top-level (it is not allowed
in config files). In this case, the output might instead look like this:

```
second
second
second
second
second
first
first
first
first
first

```

Note in this case that even when using `--sequential` there is no guarantee
that the commands will be executed in the order they appear in the config
file.

## Batching

Part of what `lorea` does is apply some heuristics to batch together file
changes. There are many reasons that files change on disk, and these changes
frequently come in large bursts. For instance, when you save a file in your
editor, it probably makes a tempfile and then copies it over the target,
leading to several different changes. A more dramatic example will happen
when you do a source-control checkout, in which case there is no limit to
the number of files that might change at once.

If `lorea` did not batch these changes, this could lead to your computer
slowing down to a crawl, or the whole process crashing.

There are two modes to batch these changes.

If your command is marked as a service, or has no placeholders in it, then
`lorea` assumes that individual changes are not as important as the fact that
*a change took place*. In this case changes will be collected, and a single
command execution will trigger once a short amount of time has passed
between them.

Otherwise, changes will be collected using the same logic as above, but
*every unique file change* will trigger a separate execution of your command.

## Examples

Every time a `.raku` or `.rakumod` file changes, print a string with the
name of the modified file:

```
lorea --regex '\.raku(mod)?$' -- echo "Change in {}"

```

or the same thing, but taking advantage of Raku's [regular expressions](https://docs.raku.org/language/regexes):

```
lorea --regex '".raku" [mod]? $' -- echo "Change in {}"

```


## dist_zef-lizmat-Sub-Util.md
[![Actions Status](https://github.com/lizmat/Sub-Util/workflows/test/badge.svg)](https://github.com/lizmat/Sub-Util/actions)

# NAME

Raku port of Perl's Sub::Util module 1.55

# SYNOPSIS

```
use Sub::Util <subname set_subname>

```

# DESCRIPTION

This module tries to mimic the behaviour of Perl's `Sub::Util` module as closely as possible in the Raku Programming Language.

`Sub::Util` contains a selection of subroutines that people have expressed would be nice to have in the perl core, but the usage would not really be high enough to warrant the use of a keyword, and the size would be so small that being individual extensions would be wasteful.

By default `Sub::Util` does not export any subroutines.

## subname

```
my $name = subname( $callable );

```

Returns the name of the given Callable, if it has one. Normal named subs will give a fully-qualified name consisting of the package and the localname separated by `::`. Anonymous Callables will give `__ANON__` as the localname. If a name has been set using `set_subname`, this name will be returned instead.

*Users of Sub::Name beware*: This function is **not** the same as `Sub::Name::subname`; it returns the existing name of the sub rather than changing it. To set or change a name, see instead `set_subname`.

## set\_subname

```
my $callable = set_subname $name, $callable;

```

Sets the name of the function given by the Callable. Returns the Callable itself. If the `$name` is unqualified, the package of the caller is used to qualify it.

This is useful for applying names to anonymous Callables so that stack traces and similar situations, to give a useful name rather than having the default. Note that this name is only used for this situation; the `set_subname` will not install it into the symbol table; you will have to do that yourself if required.

However, since the name is not used by perl except as the return value of `caller`, for stack traces or similar, there is no actual requirement that the name be syntactically valid as a perl function name. This could be used to attach extra information that could be useful in debugging stack traces.

This function was copied from `Sub::Name::subname` and renamed to the naming convention of this module.

# FUNCTIONS NOT PORTED

It did not make sense to port the following functions to Raku, as they pertain to specific Pumpkin Perl internals.

```
prototype set_prototype

```

Attempting to import these functions will result in a compilation error with hopefully targeted feedback. Attempt to call these functions using the fully qualified name (e.g. `Sub::Util::set_prototype($a)`) will result in a run time error with the same feedback.

# SEE ALSO

Sub::Name

# AUTHOR

Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)

Source can be located at: <https://github.com/lizmat/Sub-Util> . Comments and Pull Requests are welcome.

# COPYRIGHT AND LICENSE

Copyright 2018, 2019, 2020, 2021 Elizabeth Mattijsen

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.

Re-imagined from the Perl version as part of the CPAN Butterfly Plan. Perl version originally developed by Paul Evans.


## dist_zef-lizmat-P5getservbyname.md
[![Actions Status](https://github.com/lizmat/P5getservbyname/workflows/test/badge.svg)](https://github.com/lizmat/P5getservbyname/actions)

# NAME

Raku port of Perl's getservbyname() and associated built-ins

# SYNOPSIS

```
use P5getservbyname;
# exports getservbyname, getservbyport, getservent, setservent, endservent

say getservbyport(Scalar, 25, "tcp");   # "smtp"

my @result_byname = getservbyname("smtp");

my @result_byport = getservbyport(|@result_byname[3,4]);

```

# DESCRIPTION

This module tries to mimic the behaviour of Perl's `getservbyname` and associated built-ins as closely as possible in the Raku Programming Language.

It exports by default:

```
endservent getservbyname getservbyport getservent setservent

```

# ORIGINAL PERL 5 DOCUMENTATION

```
getservbyname NAME,PROTO
getservbyport PORT,PROTO
getservent
setservent STAYOPEN
endservent
        These routines are the same as their counterparts in the system C
        library. In list context, the return values from the various get
        routines are as follows:

         # 0        1          2           3         4
         ( $name,   $aliases,  $port,      $proto    ) = getserv*

        (If the entry doesn't exist you get an empty list.)

        In scalar context, you get the name, unless the function was a
        lookup by name, in which case you get the other thing, whatever it
        is. (If the entry doesn't exist you get the undefined value.)

```

# PORTING CAVEATS

This module depends on the availability of POSIX semantics. This is generally not available on Windows, so this module will probably not work on Windows.

# AUTHOR

Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)

If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me!

Source can be located at: <https://github.com/lizmat/P5getservbyname> . Comments and Pull Requests are welcome.

# COPYRIGHT AND LICENSE

Copyright 2018, 2019, 2020, 2021, 2023 Elizabeth Mattijsen

Re-imagined from Perl as part of the CPAN Butterfly Plan.

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## dist_zef-antononcube-DateTime-Grammar.md
# DateTime::Grammar Raku package

## Introduction

This Raku package provides grammar (role) and interpreters for parsing
[datetime specifications](https://docs.raku.org/type/DateTime).

Most of the code is from [FS1]. The original code of the file
["Parse.rakumod"](https://github.com/sergot/datetime-parse/blob/master/lib/DateTime/Parse.rakumod)
(from [FS1]) was separated into the files
["Grammarish.rakumod"](./lib/DateTime/Grammarish.rakumod)
and
["Actions/Raku.rakumod"](./lib/DateTime/Actions/Raku.rakumod).

The code in
["Grammar.rakumod"](./lib/DateTime/Grammar.rakumod)
provides the "top-level" functions:

* `datetime-parse`
* `datetime-subparse`
* `datetime-interpret`

**Remark:** The code `DateTime::Parse.new` can be replaced with `datetime-interpret`.
Compare the test files of this repository that have names starting with "01-" with the corresponding files in [FS1].

---

## Installation

From Zef ecosystem:

```
zef install DateTime::Grammar

```

From GitHub:

```
zef install https://github.com/antononcube/Raku-DateTime-Grammar.git

```

---

## Usage examples

Interpret a full blown datetime spec:

```
use DateTime::Grammar;
my $rfc1123 = datetime-interpret('Sun, 06 Nov 1994 08:49:37 GMT');
$rfc1123.raku

```

```
# DateTime.new(1994,11,6,8,49,37)

```

Just the date:

```
$rfc1123.Date;

```

```
# 1994-11-06

```

7th day of week:

```
datetime-interpret('Sun', :rule<wkday>) + 1;

```

```
# 7

```

With the adverb `extended` we can control whether the datetime specs can be just dates.
Here are examples:

```
datetime-interpret('1/23/1089'):extended;

```

```
# 1089-01-23T00:00:00Z

```

```
datetime-interpret('1/23/1089'):!extended;

```

```
# (Any)

```

---

## Using the role in "external" grammars

Here is how the role "Grammarish" of "DateTime::Grammar" can be used in "higher order" grammars:

```
my grammar DateTimeInterval
    does DateTime::Grammarish {

    rule TOP($*extended) { 'from' <from=.datetime-param-spec> 'to' <to=.datetime-param-spec> }
};

DateTimeInterval.parse('from 2022-12-02 to Oct 4 2023', args => (True,))

```

```
# ｢from 2022-12-02 to Oct 4 2023｣
#  from => ｢2022-12-02｣
#   date-spec => ｢2022-12-02｣
#    date5 => ｢2022-12-02｣
#     year => ｢2022｣
#     month => ｢12｣
#     day => ｢02｣
#  to => ｢Oct 4 2023｣
#   date-spec => ｢Oct 4 2023｣
#    date8 => ｢Oct 4 2023｣
#     month => ｢Oct｣
#      month-short-name => ｢Oct｣
#     day => ｢4｣
#     year => ｢2023｣

```

The parameter `$*extended` can be eliminated by using `<datetime-spec>` instead of `<datetime-param-spec>`:

```
my grammar DateTimeInterval2
    does DateTime::Grammarish {

    rule TOP { 'from' <from=.datetime-spec> 'to' <to=.datetime-spec> }
};

DateTimeInterval2.parse('from 2022-12-02 to Oct 4 2023')

```

```
# ｢from 2022-12-02 to Oct 4 2023｣
#  from => ｢2022-12-02｣
#   date-spec => ｢2022-12-02｣
#    date5 => ｢2022-12-02｣
#     year => ｢2022｣
#     month => ｢12｣
#     day => ｢02｣
#  to => ｢Oct 4 2023｣
#   date-spec => ｢Oct 4 2023｣
#    date8 => ｢Oct 4 2023｣
#     month => ｢Oct｣
#      month-short-name => ｢Oct｣
#     day => ｢4｣
#     year => ｢2023｣

```

---

## CLI

The package provides a Command Line Interface (CLI) script. Here is its usage message:

```
datetime-interpretation --help

```

```
# Usage:
#   datetime-interpretation <spec> [-t|--target=<Str>] -- Interpret datetime spec.
#   datetime-interpretation [<words> ...] [-t|--target=<Str>] -- Interpret datetime spec obtained by a sequence of strings.
#   datetime-interpretation [-t|--target=<Str>] -- Interpret datetime spec from pipeline input
#
#     <spec>               Datetime specification.
#     -t|--target=<Str>    Interpretation target. [default: 'Raku']
#     [<words> ...]        Datetime specification.

```

---

## References

[FPS1] Filip Sergot,
[DateTime::Parse Raku package](https://github.com/sergot/datetime-parse),
(2017-2022),
[GitHub/sergot](https://github.com/sergot).


## is-20rw.md
is rw

Combined from primary sources listed below.

# [In Type system](#___top "go to top of document")[§](#(Type_system)_trait_is_rw "direct link")

See primary documentation
[in context](/language/typesystem#trait_is_rw)
for **trait is rw**.

```raku
sub trait_mod:<is>(Mu:U $type, :$rw!)
```

The [trait](/type/Sub#Traits) `is rw` on a class will create writable accessor methods on all public attributes of that class.

```raku
class C is rw {
    has $.a;
};
my $c = C.new.a = 42;
say $c; # OUTPUT: «42␤»
```

# [In Routine](#___top "go to top of document")[§](#(Routine)_trait_is_rw "direct link")

See primary documentation
[in context](/type/Routine#trait_is_rw)
for **trait is rw**.

```raku
multi trait_mod:<is>(Routine $r, :$rw!)
```

When a routine is modified with this trait, its return value will be writable. This is useful when returning variables or writable elements of hashes or arrays, for example:

```raku
sub walk(\thing, *@keys) is rw {
    my $current := thing;
    for @keys -> $k {
        if $k ~~ Int {
            $current := $current[$k];
        }
        else {
            $current := $current{$k};
        }
    }
    $current;
}

my %hash;
walk(%hash, 'some', 'key', 1, 2) = 'autovivified';

say %hash.raku;

```

produces

```raku
("some" => {"key" => [Any, [Any, Any, "autovivified"]]}).hash

```

Note that `return` marks return values as read only; if you need an early exit from an `is rw` routine, you have to use `return-rw` instead.