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

# NAME

Raku port of Perl's List::Util module 1.49

# SYNOPSIS

```
use List::Util <
  reduce any all none notall first

  max maxstr min minstr product sum sum0

  pairs unpairs pairkeys pairvalues pairfirst pairgrep pairmap

  shuffle uniq uniqnum uniqstr
>;

```

# DESCRIPTION

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

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

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

# Porting Caveats

Raku does not have the concept of `scalar` and `list` context. Usually, the effect of a scalar context can be achieved by prefixing `+` to the result, which would effectively return the number of elements in the result, which usually is the same as the scalar context of Raku of these functions.

Raku does not have a magic `$a` and `$b`. But they can be made to exist by specifying the correct signature to blocks, specifically "-> $a, $b". These have been used in all examples that needed them. Just using the signature auto-generating `$^a` and `$^b` would be more Raku like. But since we want to keep the documentation as close to the original as possible, it was decided to specifically specify the "-> $a, $b" signatures.

Raku also doesn't have a single `undef` value, but instead has `Type Objects`, which could be considered undef values, but with a type annotation.

Raku has real `Pair` objects, which in the Perl version are mimiced by blessed arrays that have a `.key` and `.value` methods. In the Raku version these are represented by a subclass of the `List` class, namely the `P5Pair`, which also provides a .key and a .value method.

Also note there are no special parsing rules with regards to blocks in Raku. So a comma is **always** required after having specified a block.

The following functions are actually built-ins in Raku.

```
reduce any all none first max min sum uniq

```

They mostly provide the same or similar semantics, but there may be subtle differences, so it was decided to not just use the built-ins. If these functions are imported from this library in a scope, they will used instead of the Raku builtins. The easiest way to use both the functions of this library and the raku builtins in the same scope, is to use the method syntax for the Raku versions.

```
{  # Note: imports in Raku are always lexically scoped
    use List::Util <max>;
    say max 1..10;    # Ported Perl version
    say (1..10).max;  # Raku version
}
say max 1..10;  # Raku version again

```

# LIST-REDUCTION FUNCTIONS

The following set of functions all reduce a list down to a single value.

## reduce

```
$result = reduce -> $a, $b { BLOCK }, @list;

```

Reduces `@list` by calling `BLOCK` multiple times, setting `$a` and `$b` each time. The first call will be with `$a` and `$b` set to the first two elements of the list, subsequent calls will be done by setting `$a` to the result of the previous call and `$b` to the next element in the list.

Returns the result of the last call to the `BLOCK`. If `@list` is empty then `Nil` is returned. If `@list` only contains one element then that element is returned and `BLOCK` is not executed.

The following examples all demonstrate how `reduce` could be used to implement the other list-reduction functions in this module. (They are not in fact implemented like this, but instead in a more efficient manner in individual C functions).

```
$foo = reduce -> $a, $b { defined($a)            ? $a :
                          $code->(local $_ = $b) ? $b :
                                            Nil } Nil, @list; # first

$foo = reduce -> $a, $b { $a > $b ?? $a !! $b } 1..10;       # max
$foo = reduce -> $a, $b { $a gt $b ?? $a !! $b } 'A'..'Z';   # maxstr
$foo = reduce -> $a, $b { $a < $b ?? $a !! $b } 1..10;       # min
$foo = reduce -> $a, $b { $a lt $b ?? $a !! $b } 'aa'..'zz'; # minstr
$foo = reduce -> $a, $b { $a + $b } 1 .. 10;                 # sum
$foo = reduce -> $a, $b { $a ~ $b } @bar;                    # concat

$foo = reduce -> $a, $b { $a || $b }   0, @bar;  # any
$foo = reduce -> $a, $b { $a && $b }   1, @bar;  # all
$foo = reduce -> $a, $b { $a && !$b }  1, @bar;  # none
$foo = reduce -> $a, $b { $a || !$b) } 0, @bar;  # notall
# Note that these implementations do not fully short-circuit

```

If your algorithm requires that `reduce` produce an identity value, then make sure that you always pass that identity value as the first argument to prevent `Nil` being returned

```
$foo = reduce -> $a, $b { $a + $b } 0, @values;  # sum with 0 identity value

```

The above example code blocks also suggest how to use `reduce` to build a more efficient combined version of one of these basic functions and a `map` block. For example, to find the total length of all the strings in a list, we could use

```
$total = sum map { .chars }, @strings;

```

However, this produces a list of temporary integer values as long as the original list of strings, only to reduce it down to a single value again. We can compute the same result more efficiently by using `reduce` with a code block that accumulates lengths by writing this instead as:

```
$total = reduce -> $a, $b { $a + $b.chars } 0, @strings;

```

The remaining list-reduction functions are all specialisations of this generic idea.

## any

```
my $bool = any { BLOCK }, @list;

```

Similar to `grep` in that it evaluates `BLOCK` setting `$_` to each element of `@list` in turn. `any` returns true if any element makes the `BLOCK` return a true value. If `BLOCK` never returns true or `@list` was empty then it returns false.

Many cases of using `grep` in a conditional can be written using `any` instead, as it can short-circuit after the first true result.

```
if( any { .chars > 10 }, @strings ) {
    # at least one string has more than 10 characters
}

```

## all

```
my $bool = all { BLOCK }, @list;

```

Similar to </any>, except that it requires all elements of the `@list` to make the `BLOCK` return true. If any element returns false, then it returns false. If the `BLOCK` never returns false or the `@list` was empty then it returns true.

## none

## notall

```
my $bool = none { BLOCK }, @list;

my $bool = notall { BLOCK }, @list;

```

Similar to </any> and </all>, but with the return sense inverted. `none` returns true only if no value in the `@list` causes the `BLOCK` to return true, and `notall` returns true only if not all of the values do.

## first

```
my $val = first { BLOCK }, @list;

```

Similar to `grep` in that it evaluates `BLOCK` setting `$_` to each element of `@list` in turn. `first` returns the first element where the result from `BLOCK` is a true value. If `BLOCK` never returns true or `@list` was empty then `Nil` is returned.

```
$foo = first { defined($_) }, @list;   # first defined value in @list
$foo = first { $_ > $value }, @list;   # first value in @list which
                                       # is greater than $value

```

## max

```
my $num = max @list;

```

Returns the entry in the list with the highest numerical value. If the list is empty then `Nil` is returned.

```
$foo = max 1..10;         # 10
$foo = max 3,9,12;        # 12
$foo = max @bar, @baz;    # whatever

```

## maxstr

```
my $str = maxstr @list;

```

Similar to </max>, but treats all the entries in the list as strings and returns the highest string as defined by the `gt` operator. If the list is empty then `Nil` is returned.

```
$foo = maxstr 'A'..'Z';         # 'Z'
$foo = maxstr "hello","world";  # "world"
$foo = maxstr @bar, @baz;       # whatever

```

## min

```
my $num = min @list;

```

Similar to </max> but returns the entry in the list with the lowest numerical value. If the list is empty then `Nil` is returned.

```
$foo = min 1..10;               # 1
$foo = min 3,9,12;              # 3
$foo = min @bar, @baz;          # whatever

```

## minstr

```
my $str = minstr @list;

```

Similar to </min>, but treats all the entries in the list as strings and returns the lowest string as defined by the `lt` operator. If the list is empty then `Nil` is returned.

```
$foo = minstr 'A'..'Z';         # 'A'
$foo = minstr "hello","world";  # "hello"
$foo = minstr @bar, @baz;       # whatever

```

## product

```
my $num = product @list;

```

Returns the numerical product of all the elements in `@list`. If `@list` is empty then `1` is returned.

```
$foo = product 1..10;           # 3628800
$foo = product 3,9,12;          # 324

```

## sum

```
my $num_or_nil = sum @list;

```

Returns the numerical sum of all the elements in `@list`. For backwards compatibility, if `@list` is empty then `Nil` is returned.

```
$foo = sum 1..10;               # 55
$foo = sum 3,9,12;              # 24
$foo = sum @bar, @baz;          # whatever

```

## sum0

```
my $num = sum0 @list;

```

Similar to </sum>, except this returns 0 when given an empty list, rather than `Nil`.

# KEY/VALUE PAIR LIST FUNCTIONS

The following set of functions, all inspired by List::Pairwise, consume an even-sized list of pairs. The pairs may be key/value associations from a hash, or just a list of values. The functions will all preserve the original ordering of the pairs, and will not be confused by multiple pairs having the same "key" value - nor even do they require that the first of each pair be a plain string.

**NOTE**: At the time of writing, the following `pair*` functions that take a block do not modify the value of `$_` within the block, and instead operate using the `$a` and `$b` globals instead. This has turned out to be a poor design, as it precludes the ability to provide a `pairsort` function. Better would be to pass pair-like objects as 2-element array references in `$_`, in a style similar to the return value of the `pairs` function. At some future version this behaviour may be added.

Until then, users are alerted **NOT** to rely on the value of `$_` remaining unmodified between the outside and the inside of the control block. In particular, the following example is **UNSAFE**:

```
my @kvlist = ...

foreach (qw( some keys here )) {
   my @items = pairgrep { $a eq $_ } @kvlist;
   ...
}

```

Instead, write this using a lexical variable:

```
foreach my $key (qw( some keys here )) {
   my @items = pairgrep { $a eq $key } @kvlist;
   ...
}

```

## pairs

```
my @pairs = pairs @kvlist;

```

A convenient shortcut to operating on even-sized lists of pairs, this function returns a list of `ARRAY` references, each containing two items from the given list. It is a more efficient version of

```
@pairs = pairmap { [ $a, $b ] }, @kvlist;

```

It is most convenient to use in a `foreach` loop, for example:

```
foreach my $pair ( pairs @kvlist ) {
   my ( $key, $value ) = @$pair;
   ...
}

```

The following code is equivalent:

```
foreach my $pair ( pairs @kvlist ) {
   my $key   = $pair.key;
   my $value = $pair.value;
   ...
}

```

## unpairs

```
my @kvlist = unpairs @pairs;

```

The inverse function to `pairs`; this function takes a list of `ARRAY` references containing two elements each, and returns a flattened list of the two values from each of the pairs, in order. This is notionally equivalent to

```
my @kvlist = map { @{$_}[0,1] } @pairs;

```

except that it is implemented more efficiently internally. Specifically, for any input item it will extract exactly two values for the output list; using `Nil` if the input array references are short.

Between `pairs` and `unpairs`, a higher-order list function can be used to operate on the pairs as single scalars; such as the following near-equivalents of the other `pair*` higher-order functions:

```
@kvlist = unpairs grep { FUNC }, pairs @kvlist;
# Like pairgrep, but takes $_ instead of $a and $b

@kvlist = unpairs map { FUNC }, pairs @kvlist;
# Like pairmap, but takes $_ instead of $a and $b

```

Finally, this technique can be used to implement a sort on a keyvalue pair list; e.g.:

```
@kvlist = unpairs sort -> $a, $b { $a.key cmp $b.key }, pairs @kvlist;

```

## pairkeys

```
my @keys = pairkeys @kvlist;

```

A convenient shortcut to operating on even-sized lists of pairs, this function returns a list of the the first values of each of the pairs in the given list. It is a more efficient version of

```
@keys = pairmap -> $a, $b { $a }, @kvlist;

```

## pairvalues

```
my @values = pairvalues @kvlist;

```

A convenient shortcut to operating on even-sized lists of pairs, this function returns a list of the the second values of each of the pairs in the given list. It is a more efficient version of

```
@values = pairmap -> $a, $b { $b }, @kvlist;

```

## pairgrep

```
my @kvlist = pairgrep -> $a, $b { BLOCK }, @kvlist;

my $count = pairgrep -> $a, $b { BLOCK }, @kvlist;

```

Similar to perl's `grep` keyword, but interprets the given list as an even-sized list of pairs. It invokes the `BLOCK` multiple times, with `$a` and `$b` set to successive pairs of values from the `@kvlist`.

Returns an even-sized list of those pairs for which the `BLOCK` returned true.

```
@subset = pairgrep -> $a, $b { $a =~ m/^[[:upper:]]+$/ }, @kvlist;

```

As with `grep` aliasing `$_` to list elements, `pairgrep` aliases `$a` and `$b` to elements of the given list.

## pairfirst

```
my ( $key, $val ) = pairfirst -> $a, $b { BLOCK }, @kvlist;

my $found = pairfirst -> $a, $b { BLOCK }, @kvlist;

```

Similar to the </first> function, but interprets the given list as an even-sized list of pairs. It invokes the `BLOCK` multiple times, with `$a` and `$b` set to successive pairs of values from the `@kvlist`.

Returns the first pair of values from the list for which the `BLOCK` returned true, or an empty list of no such pair was found.

```
( $key, $value ) = pairfirst -> $a, $b { $a =~ m/^[[:upper:]]+$/ }, @kvlist;

```

As with `grep` aliasing `$_` to list elements, `pairfirst` aliases `$a` and `$b` to elements of the given list.

## pairmap

```
my @list = pairmap -> $a, $b { BLOCK }, @kvlist;

my $count = pairmap -> $a, $b { BLOCK }, @kvlist;

```

Similar to perl's `map` keyword, but interprets the given list as an even-sized list of pairs. It invokes the `BLOCK` multiple times, with `$a` and `$b` set to successive pairs of values from the `@kvlist`.

Returns all the values returned by the `BLOCK`.

```
@result = pairmap -> $a, $b { "The key $a has value $b" }, @kvlist

```

As with `map` aliasing `$_` to list elements, `pairmap` aliases `$a` and `$b` to elements of the given list.

# OTHER FUNCTIONS

## shuffle

```
my @values = shuffle @values;

```

Returns the values of the input in a random order

```
@cards = shuffle 0..51;     # 0..51 in a random order

```

## uniq

```
my @subset = uniq @values;

```

Filters a list of values to remove subsequent duplicates, as judged by a DWIM-ish string equality. Preserves the order of unique elements, and retains the first value of any duplicate set.

Type objects are treated by this function as distinct from the empty string, and no warning will be produced. It is left as-is in the returned list. Subsequent identical type objects are still considered identical to the first, and will be removed.

## uniqnum

```
my @subset = uniqnum @values;

```

Filters a list of values to remove subsequent duplicates, as judged by a numerical equality test. Preserves the order of unique elements, and retains the first value of any duplicate set.

Note that type objects are treated much as other numerical operations treat it; it compares equal to zero but additionally produces a warning. In addition, a type object in the returned list is coerced into a numerical zero, so that the entire list of values returned by `uniqnum` are well-behaved as numbers.

Note also that multiple IEEE `NaN` values are treated as duplicates of each other, regardless of any differences in their payloads.

## uniqstr

```
my @subset = uniqstr @values;

```

Filters a list of values to remove subsequent duplicates, as judged by a string equality test. Preserves the order of unique elements, and retains the first value of any duplicate set.

Note that type objects are treated much as other string operations treat it; it compares equal to the empty string but additionally produces a warning. In addition, a type object in the returned list is coerced into an empty string, so that the entire list of values returned by `uniqstr` are well-behaved as Str.

# SEE ALSO

Scalar::Util, List::MoreUtils

# AUTHOR

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

Source can be located at: <https://github.com/lizmat/List-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 Graham Barr, subsequently maintained by Paul Evans.


## dist_cpan-TYIL-IO-Path-XDG.md
### sub xdg-config-dirs

```
sub xdg-config-dirs(
    Bool:D :$home = Bool::True
) returns Iterable

```

Retrieve the value of XDG\_CONFIG\_DIRS as a sequence of IO::Path objects. If this variable is not set, it will use the default value of /etc/xdg. These directories should be read in order to retrieve configuration files.

## class Bool:D :$home = Bool::True

When set to true, this sequence will start with the XDG\_CONFIG\_HOME value (or its default).

### sub xdg-config-home

```
sub xdg-config-home() returns IO::Path

```

Returns an IO::Path for $XDG\_CONFIG\_HOME, if it exists as environment variable. Otherwise, return the default value, $HOME/.config. This directory should contain user-specific configuration files.

### sub xdg-cache-home

```
sub xdg-cache-home() returns IO::Path

```

Returns an IO::Path for $XDG\_CACHE\_HOME, if it exists as environment variable. Otherwise, return the default value, $HOME/.cache. This directory should contain user-specific, non-essential (cached) data.

### sub xdg-data-dirs

```
sub xdg-data-dirs(
    Bool:D :$home = Bool::True
) returns Iterable

```

Retrieve the value of XDG\_DATA\_DIRS as a sequence of IO::Path objects. If this variable is not set, it will use the default values of /usr/local/share and /usr/share. These directories should be read in order to retrieve user specific data files.

## class Bool:D :$home = Bool::True

When set to true, this sequence will start with the XDG\_DATA\_HOME value (or its default).

### sub xdg-data-home

```
sub xdg-data-home() returns IO::Path

```

Returns an IO::Path for $XDG\_DATA\_HOME, if it exists as environment variable. Otherwise, return the default value, $HOME/.local/share. This directory should contain user-specific data files.

### sub xdg-runtime-dir

```
sub xdg-runtime-dir() returns IO::Path

```

Returns an IO::Path for $XDG\_RUNTIME\_DIR, if it exists as environment variable. Otherwise, return an IO::Path to a temporary directory. This directory should contain user-specific runtime files and other file objects.

# NAME

IO::Path::XDG

# AUTHOR

Patrick Spek [p.spek@tyil.work](mailto:p.spek@tyil.work)

# VERSION

0.2.0

# Synopsis

# Description

# Examples

# See also


## dist_zef-ssotka-IO-Archive.md
# NAME

IO::Archive - Adds libarchive capabilities to IO::Path objects

# SYNOPSIS

Note: Requires libarchive to be installed and in place raku can find it.

For MacOS try;
`brew install libarchive`

* You may need to manually copy or link `libarchive.13.dylib` to someplace like `/usr/local/lib`.

```
# Get a list of the files in the archive
my @files = "test-archive.tgz".IO.arch-list;

# Extract a specific file to a destination
"test-archive.tgz".IO.arch-extract( @files[2], $dest );

# extract the contents of a file in the archive to a string
my Str $str-buf = "test-archive.tgz".IO.arch-extract( @files[2] );

# extract the contents of a file in the archive to a Buf (for non-text files)
my Buf $buf = "test-archive.tgz".IO.arch-extract-buf( @files[3] );

# Extract all the files from the archive to a given destination
"test-archive.tgz".IO.arch-extract-all( $dest );

# Create an archive
"new-archive.tgz".IO.arch-create( @file-paths );

# Add or update a file to an archive
"new-archive.tgz".IO.arch-insert( $file );

# NOTE: arch-insert works more like a refresh. It will take the list of existing files, add the
# new file to the list, make sure all the files exist (throwing an error if not). Then
# remove the original archive file (new-archive.tgz) and recreate it containing the full list of files.

```

# DESCRIPTION

IO::Archive adds archive methods to the IO::Path class to create and extract from
archive files like tgz, zip, bzip and any other archive that is handled by libarchive.

# AUTHOR

Scott Sotka [ssotka@gmail.com](mailto:ssotka@gmail.com)

# COPYRIGHT AND LICENSE

Copyright 2024 Scott Sotka

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


## dist_cpan-TITSUKI-Algorithm-Manacher.md
[![Build Status](https://travis-ci.org/titsuki/p6-Algorithm-Manacher.svg?branch=master)](https://travis-ci.org/titsuki/p6-Algorithm-Manacher)

# NAME

Algorithm::Manacher - a perl6 implementation of the extended Manacher's Algorithm for solving longest palindromic substring(i.e. palindrome) problem

# SYNOPSIS

```
use Algorithm::Manacher;

# "たけやぶやけた" is one of the most famous palindromes in Japan.
# It means "The bamboo grove was destroyed by a fire." in English.
my $manacher = Algorithm::Manacher.new(text => "たけやぶやけた");
$manacher.is-palindrome(); # True
$manacher.find-longest-palindrome(); # {"たけやぶやけた" => [0]};
$manacher.find-all-palindrome(); # {"た" => [0, 6], "け" => [1, 5], "や" => [2, 4], "たけやぶやけた" => [0]}

```

# DESCRIPTION

Algorithm::Manacher is a perl6 implementation of the extended Manacher's Algorithm for solving longest palindromic substring problem. A palindrome is a sequence which can be read same from left to right and right to left. In the original Manacher's paper [0], his algorithm has some limitations(e.g. couldn't handle a text of even length). Therefore this module employs the extended Manacher's Algorithm in [1], it enables to handle a text of both even and odd length, and compute all palindromes in a given text.

## CONSTRUCTOR

```
my $manacher = Algorithm::Manacher.new(text => $text);

```

## METHODS

### find-all-palindrome

```
Algorithm::Manacher.new(text => "たけやぶやけた").find-all-palindrome(); # {"た" => [0, 6], "け" => [1, 5], "や" => [2, 4], "たけやぶやけた" => [0]}

```

Finds all palindromes in a text and returns a hash containing key/value pairs, where key is a palindromic substring and value is an array of its starting positions. If there are multiple palindromes that share the same point of symmetry, it remains the longest one.

### is-palindrome

```
Algorithm::Manacher.new(text => "たけやぶやけた").is-palindrome(); # True
Algorithm::Manacher.new(text => "たけやぶやけたわ").is-palindrome(); # False
Algorithm::Manacher.new(text => "Perl6").is-palindrome(); # False

```

Returns whether a given text is a palindrome or not.

### find-longest-palindrome

```
Algorithm::Manacher.new(text => "たけやぶやけた").find-longest-palindrome(); # {"たけやぶやけた" => [0]};
Algorithm::Manacher.new(text => "たけやぶやけた。、だんしがしんだ").find-longest-palindrome(), {"たけやぶやけた" => [0], "だんしがしんだ" => [9]};

```

Returns the longest palindrome. If there are many candidates, it returns all of them.

# AUTHOR

titsuki [titsuki@cpan.org](mailto:titsuki@cpan.org)

# COPYRIGHT AND LICENSE

Copyright 2016 titsuki

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

This algorithm is from

* [0] Manacher, Glenn. "A New Linear-Time``On-Line''Algorithm for Finding the Smallest Initial Palindrome of a String." Journal of the ACM (JACM) 22.3 (1975): 346-351.
* [1] Tomohiro, I., et al. "Counting and verifying maximal palindromes." String Processing and Information Retrieval. Springer Berlin Heidelberg, 2010.


## dist_zef-jjatria-Cookie-Jar.md
# NAME

Cookie::Jar - A minimalist HTTP cookie jar

# SYNOPSIS

```
use Cookie::Jar;

my $cookies = Cookie::Jar.new;

$cookies.add: 'https://example.com', 'foo=123; Domain=example.com';
$cookies.add: 'https://example.com', 'bar=234';

say "{ .name } -> { .value }" for $cookies.get: 'GET', 'https://example.com';
# OUTPUT:
# foo -> 123
# bar -> 234

# The 'bar' cookie does not apply to this subdomain
say $cookies.header: 'GET', 'https://www.example.com';
# OUTPUT:
# foo=123

# Cookies can persist on filesystem
my $other = $jar.save('cookie.jar').load('cookie.jar');

```

# DESCRIPTION

This is a minimal class to manage HTTP cookies. It can be used together with
a HTTP client class like [HTTP::Tiny](https://raku.land/zef:jjatria/HTTP::Tiny) to manage cookies received in HTTP
responses and determine the cookies that apply on new requests.

Unlike other alternatives available at the time of writing, user agents
desiring to integrate with this class do not need to use a specific class
to represent the request, the response, or the cookie: all that is required
is the request URL and the headers received from the server.

The operations on this library should be thread-safe.

# METHODS

Some of the methods below take a request URL parameter. In compliance with
[RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265), these are all canonicalised to their ASCII "punycode"
representation before processing.

Likewise, the methods in this class that return cookies (like [get](#get) and
[dump](#dump) described below) return a read-only opaque cookie object with
the following available methods:

### The Cookie Object

**creation-time**

A DateTime marking the moment the cookie was created. This could be before
the jar was created if the cookie was loaded from external storage with
[load](#load). This attribute is internal, and does not conflict with an
extension of the same name.

**domain**

Returns a Str with the cookie's domain. If the cookie did not have a domain
initially, this will be the domain the cookie was received from.

**expired**

Returns a Bool that will be true if the cookie is persistent and its
expiration date is in the past. It can optionally take a DateTime object to be
used instead of the current timestamp.

**expires**

Returns a DateTime with the cookie's expiration time. This might be a type
object if the cookie is not persistent.

**host-only**

Returns a Bool specifying whether the cookie should apply to domains other
than the one in its "domain" attribute. This attribute can also be called as
`hostonly`.

**http-only**

Returns a Bool specifying whether this cookie should be included in non-HTTP
requests (this is of little use for Raku user-agents). This attribute can
also be called as `httponly`.

**last-access-time**

Returns a DateTime specifying when the cookie was last matched for a given
URL (using the [get](#get) or [header](#header) methods). This attribute is
internal, and does not conflict with an extension of the same name.

**name**

Returns a Str with the cookie name. This attribute is internal, and does not
conflict with an extension of the same name.

**path**

Returns a Str with the path the cookie applies to.

**persistent**

Returns a Bool which will be true if the cookie has a defined expiration date.

**secure**

Returns a Bool specifying whether this cookie should be sent over non-secure
channels. Cookies with this attribute set to a true value will only be matched
for HTTPS requests.

**value**

Returns a Str with the value of the cookie. No effort is made by Cookie::Jar to
parse or otherwise decode this value. This attribute is internal, and does not
conflict with an extension of the same name.

**get**

Takes a key that will be matched case-insensitively to a cookie attribute.
The key can be any of the ones mentioned above, or the name of any of the
cookie's extensions. If the cookie does not have an attribute with that
name this method will return False. Otherwise, the value of the attribute
will be returned, or True if the attribute has no value. If the cookie was
set with an attribute with the same name as one of the fields described as
"internal" above (eg. 'creation-time' and 'last-access-time', etc), using
that key with this method will return the extension.

### new

```
method new () returns Cookie::Jar

```

Creates a new Cookie::Jar object. The constructor takes no parameters.

To construct a Cookie::Jar with cookies that have been saved on a previous
session (with the [save](#save) method), see the [load](#load) method below.

### add

```
method add (
    Str:D $url,
    Str:D $cookie-string,
) returns Bool

```

Add a new cookie to the internal storage.

This method takes a URL and a `Set-Cookie` header string (received from making
a request to that URL) and adds the cookie to the jar. If the cookie is
expired, any matching cookie is deleted as described in [RFC 6265 § 4.1.2](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.2).

If the [PublicSuffix](https://raku.land/zef:jjatria/PublicSuffix) module is available, it will be used to validate cookie
domains and reject [supercookies](https://en.wikipedia.org/wiki/HTTP_cookie#Supercookie).

Returns True if the cookie was successfully added, or False otherwise.

### dump

```
method dump () returns Hash

```

This method offers some introspection by returns a Hash representation of the
internal storage used by the jar.

The data structure store cookies indexed by nested domain, path, and cookie
name keys, as in the following example:

```
{
    'example.com' => {
        '/path' => {
            'SID' => ..., # see below for details on cookie values
        }
    },
}

```

Cookies in this structure (the parts represented by the ellipsis) will be
returned as an internal read-only Cookie object. For details on this Cookie
object, see [above](#the-cookie-object).

### get

```
method get (
    Str:D $method,
    Str:D $url,
) returns List

```

Takes a request method and URL and returns a (possibly empty) list of cookies
that would apply to a request made to that URL, as described in
[RFC 6265 § 5.4](https://datatracker.ietf.org/doc/html/rfc6265#section-5.4). The order of the cookies in the list follows the same order
they would take in a `Cookie` header sent with that request, as per the
document above.

The method must be one of `CONNECT`, `DELETE`, `GET`, `HEAD`, `OPTIONS`,
`PATCH`, `POST`, `PUT`, or `TRACE`, and will be matched case-sensitively, as
per HTTP/1.1 specification.

Elements in the list will be internal read-only Cookie objects. For details on
this Cookie object, see [above](#the-cookie-object).

### header

```
method header (
    Str:D $method,
    Str:D $url,
) returns Str

```

Takes a request method and URL and returns a (possibly empty) string suitable
to be used as the `Cookie` header sent to a request made to that URL. The
order of the cookies in the string follows the order described in
[RFC 6265 § 5.4](https://datatracker.ietf.org/doc/html/rfc6265#section-5.4).

The method must be one of `CONNECT`, `DELETE`, `GET`, `HEAD`, `OPTIONS`,
`PATCH`, `POST`, `PUT`, or `TRACE`, and will be matched case-sensitively, as
per HTTP/1.1 specification.

This method calls [get](#get) internally.

### clear

```
multi method clear ( ) returns Cookie::Jar

multi method clear (
    Str $url,
       *@names,
) returns Cookie::Jar

```

Clear the internal storage of the jar.

When called with no arguments, all values will be deleted.

This method can alternatively be called with a URL and a possibly empty list
of cookie names. In this case cookies that would match a request made to that
URL (as per the same rules used by the [get](#get) method), and possibly one
of the names provided, then those matching cookies will be deleted.

### save

```
method save (
    IO()    $path,
    Bool() :$netscape,
    Bool() :$all,
) returns Cookie::Jar

```

Save the internal storage into a cookie file. This file will is suitable to be
read with the [load](#load) method below. Only persistent cookies will be saved,
unless the `:all` flag is set to a true value.

By default, the file will be written using an internal format used by
Cookie::Jar. If the `:netscape` flag is set to a true value, the file will
instead use the [Netscape HTTP Cookie File](https://curl.haxx.se/docs/http-cookies.html) format, compatible with those
created by `libcurl`.

This method returns the calling object.

### load

```
method load (
    IO()    $path,
    Bool() :$netscape,
) returns Cookie::Jar

```

Load cookies from a cookie file, like that generated with [save](#save).

If called on an existing instance, the internal storage will be cleared before
reading the input file. This method can also be called on a Cookie::Jar type
object to be used as a constructor.

In both cases, this method will return a Cookie::Jar object with the cookies
loaded from the read file.

By default, the file is assumed to use the internal Cookie::Jar format.
If the file is found to have a [Netscape HTTP Cookie File](https://curl.haxx.se/docs/http-cookies.html) header instead
(like the one generated by `libcurl`), the file will be parsed as such.
Setting the `:netscape` flag to a true value enforces this, such that
providing a file missing this header is an error.

# LIMITATIONS

Cookie::Jar aims to be *conditionally compliant* with the HTTP State
Management Mechanism [RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265).

It aims to meet all "MUST" requirements of the specification, but only some of
the "SHOULD" requirements.

Some particular limitations of note include:

* Cookie::Jar does no support features that were obsoleted by [RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265).
  This includes the `Cookie2` and `Set-Cookie2` headers, `.local` suffixes,
  etc.
* Since [RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265) is the only current specification of HTTP cookie
  behaviour, Cookie::Jar does *not* support features that are not described
  in it. This includes features like SameSite.

# SEE ALSO

### Other cookie jars

#### Cro::HTTP::Client::CookieJar

Shipped as part of [Cro::HTTP](https://raku.land/cpan:JNTHN/Cro::HTTP) and is used by that client. The client cannot
be configured to use another cookie jar.

#### HTTP::Cookies

Shipped as part of [HTTP::UserAgent](https://raku.land/github:sergot/HTTP::UserAgent) and is used by that client. The client
cannot be configured to use another cookie jar.

### Additional Features

#### [Cookie::Baker](https://raku.land/github:tokuhirom/Cookie::Baker)

Cookie::Baker provides two functions, one of which, `bake-cookie`, can be
used to convert a Hash into a string that can be used as a `Cookie` header.
This can be used together with the [add](#add) method to add a cookie from a
set of key-value pairs.

#### [PublicSuffix](https://raku.land/zef:jjatria/PublicSuffix)

If this distribution is installed, Cookie::Jar will use it to verify cookie
domains against the list of public suffixes, as described in step 5 of
[RFC 6265 § 5.3](https://datatracker.ietf.org/doc/html/rfc6265#section-5.3). This should help avoid [supercookies](https://en.wikipedia.org/wiki/HTTP_cookie#Supercookie).

# AUTHOR

José Joaquín Atria [jjatria@cpan.org](mailto:jjatria@cpan.org)

# ACKNOWLEDGEMENTS

Other than the cookie jars mentioned above, the code and API in this
distribution takes inspiration from a number of similar Perl libraries.
In particular:

* [HTTP::CookieJar](https://metacpan.org/pod/HTTP::CookieJar)
* [HTTP::Cookies](https://metacpan.org/pod/HTTP::Cookies)
* [Mojo::UserAgent::CookieJar](https://metacpan.org/pod/Mojo::UserAgent::CookieJar)

This module owes a debt of gratitude to their authors and those who have
contributed to them, and to their choice to make their code and work publicly
available.

# COPYRIGHT AND LICENSE

Copyright 2022 José Joaquín Atria

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


## dist_zef-samy-Archive-Ar.md
# NAME

Archive::Ar - Unix ar archive interface

# SYNOPSIS

```
use Archive::Ar;

my $ar = Archive::Ar.new;

$ar.read: '/path/to/ar';

my $data = $ar.files<filename>.data;

$ar.add_data: 'new-entry', $data;

$ar.add_file: '/path/to/file', :to('new-entry2');

$ar.files<filename>.mode = 0o644;
$ar.files<filename>.uid = +$*USER;
$ar.files<filename>.gid = +$*GROUP;

my @files = $ar.file_list;

$ar.write: '/path/to/output/ar';

```

# DESCRIPTION

Archive::Ar is a Raku module for reading and writing Unix `ar(1)` archives, an archive format most commonly associated with static library archives and Debian `.deb` packages. This module supports common, GNU, and BSD ar archives.

This module is a port of a Perl module of the same name, with some minor improvements and additions.

This module works best on Unix-like systems. It does support Windows systems, albeit with less functionality.

## class Archive::Ar

### Attributes

#### type

```
has ArType $.type is rw

```

The type of ar archive the object represents. See the `ArType` documentation below for more info.

#### chmod

```
has Bool $.chmod is rw

```

`Bool` determining whether to automatically change extracted files' mode to `0644`. If `False`, extracted files will retain the mode specified by the file's archive entry. This attribute is meaningless on Windows systems.

#### chown

```
has Bool $.chown is rw

```

`Bool` determining whether to automatically change extracted files' uid and gid to the running user's. If `False`, extracted files will retain the uid and gid specified by the file's archive entry. This attribute is meaningless on Windows systems.

#### files

```
has %.files is Hash::Ordered is rw

```

Ordered hash mapping archive entry names to their respective `Archive::Ar::Record` object. Even though it is marked `rw`, you should avoid making changes directly to the hash structure itself if you can avoid it. However, you are encouraged to make changes to the hash's record objects themselves.

View the documentation for the `Archive::Ar::Record` class for documentation on what you can do with these record objects.

### Methods

#### new

```
method new(
	$ar?,
	ArType :$type,
	Bool   :$chmod,
	Bool   :$chown,
)

```

Returns an `Archive::Ar` object.

`$ar` is the path to a pre-existing ar archive to read data from via `read()`. If not specified, `new()` will create an empty archive object.

`$type` allows you to specify the type of archive to create. If not specified, `new()` will either try to determine the archive type automatically if given `$ar`, otherwise it will default to `AR_COMMON`. View the documentation for `ArType` for more information on the various archive types.

`$chmod` determines the default value for the `chmod` attribute. Defaults to `True` on non-Windows systems, and `False` on Windows systems (as it is meaningless).

`$chown` determines the default value for the `chown` attribute. Defaults to `True` on non-Windows systems, and `False` on Windows systems (as it is meaningless).

#### clear

```
method clear()

```

Empties out the `files` hash.

Returns the empty `files` hash.

#### read

```
method read($ar)

```

Empties out current archive data and reads new data from `$ar`. The data will be used to fill the `files` hash. `read` will also try to determine the archive type from `$ar` and set `type` accordingly.

Returns the number of file entries read.

#### file\_list

```
method file_list()

```

Returns a list of file entries currently in archive.

#### has

```
method has($file)

```

Returns `True` if `$file` is present in the archive, `False` if not. Equivalent to `self.files{$file}:exists`.

#### add\_data

```
multi method add_data(
	$file,
	Str $data,
	Instant :$modified,
	Int     :$uid,
	Int     :$gid,
	Int     :$mode,
)

multi method add_data(
	$file,
	$data,
	Instant :$modified,
	Int     :$uid,
	Int     :$gid,
	Int     :$mode,
)

```

Creates a new file entry containing `$data`. If `$data` is a string, `add_data()` will automatically encode it to binary data. Otherwise, `add_data()` will try to create a `buf8` object from `$data` and add that as `$file`'s contents.

`$modified` is an `Instant` object representing the file's modification time. If not specified, defaults to the value of `now`.

`$uid` is the uid to store `$file` under. Defaults to the value of `+$*USER` on Unix-like systems, and `0` on Windows systems.

`$gid` is the gid to store `$file` under. Defaults to the value of `+$*GROUP` on Unix-like systems, and `0` on Windows systems.

`$mode` is the mode to store `$file` as. Defaults to `0o100644`.

Returns the newly created record object.

#### add\_file

```
method add_file(
	$file,
	Str     :$to,
	Instant :$modified,
	Int     :$uid,
	Int     :$gid,
	Int     :$mode,
)

```

Creates a new file entry containing the contents of `$file`.

`$to` is the entry to add the file as. If not specified, defaults to the basename of `$file`.

`$modified` is an `Instant` object representing the file's modification time. If not specified, defaults to the modified time of `$file`.

`$uid` is the uid to store the file under. Defaults to `$file`'s uid on Unix-like systems, and `0` on Windows systems.

`$gid` is the gid to store the file under. Defaults to `$file`'s gid on Unix-like systems, and `0` on Windows systems.

`$mode` is the mode to store `$file` as. Defaults to `$file`'s mode on Unix-like systems, and `0o100644` on Windows systems.

Returns the newly created record object.

#### extract\_file

```
method extract_file(
	$rec,
	$to,
	Int :$uid,
	Int :$gid,
	Int :$mode,
)

```

Extracts archive entry `$rec` to file `$to`.

`$uid` is the uid to create the file under. If not specified, defaults to either the value of `+$*USER` if the `chown` attribute is set to `True`, or the uid specified by the file's archive entry otherwise. This option is meaningless on Windows systems.

`$gid` is the gid to create the file under. If not specified, defaults to either the value of `+$*GROUP` if the `chown` attribute is set to `True`, or the gid specified by the file's archive entry otherwise. This option is meaningless on Windows systems.

`$mode` is the mode to use for the created file. If not specified, defaults to either the default file creation mode if the `chmod` attribute is set to `True`, or the mode specified by the file's archive entry otherwise. This option is meaningless on Windows systems.

Returns the `IO` object of the extracted file.

#### extract

```
method extract($to)

```

Extracts all of the archive's files to the directory `$to`. If `$to` does not exist, `extract()` will try to create it.

Returns an array of the `IO` objects of the extracted files.

#### rename

```
method rename(
	$file,
	$new
)

```

Renames archive entry `$file` to `$new`.

Returns the renamed entry record.

#### remove

```
multi method remove()

multi method remove(
	*@recs
)

```

When ran with no arguments, does the same thing as `clear()`.

When given arguments, removes the specified files from the archive.

Returns the number of records removed.

#### write

```
multi method write()

multi method write(
	$to,
	Bool :$symbol-table
)

```

When ran with no arguments, returns a `Buf` object of the binary data it would write.

When ran with `$to`, writes archive to `$to`. Returns the `IO` object of the newly written archive.

`$symbol-table` is a `Bool` determining whether to generate a symbol table for the written file. This option requires the `ranlib` utility to be installed on your system. Defaults to `False`.

## class Archive::Ar::Record

### Attributes

#### modified

```
has Instant $.modified is rw

```

`Instant` object representing the file's modification time. It is important to note that because Raku offers no way of updating file modification times, extracted files will not have the same modification time as the one listed in its record object.

#### uid

```
has Int $.uid is rw

```

The file's uid.

#### gid

```
has Int $.gid is rw

```

The file's gid.

#### mode

```
has Int $.mode is rw

```

The file's mode.

#### data

```
has buf8 $.data is rw

```

Binary buffer of the file's contents.

### Methods

#### new

```
method new(
	Instant :$modified,
	Int     :$uid,
	Int     :$gid,
	Int     :$mode,
	buf8    :$data,
)

```

Returns a new `Archive::Ar::Record` object.

#### size

```
method size()

```

Returns the size of the file's contents.

## enum ArType

```
enum ArType <
	AR_COMMON
	AR_BSD
	AR_GNU
>

```

Enumeration representing the various ar archive types this module supports.

`AR_COMMON` is the common ar archive type that should be supported by most ar implementations. Common archives do not support filenames longer than 16 characters.

`AR_BSD` is the ar archive type used by various BSD ar implementations. BSD archives are capable of supporting filenames longer than 16 characters.

`AR_GNU` is the ar archive type used by the GNU ar implementation. GNU archives are capable of supporting filenames longer than 16 characters.

# RESTRICTIONS

Archive::Ar has limitted support for handling ar symbol tables. When reading from pre-existing ar files, Archive::Ar ignores the symbol table if present. When writing, the `:symbol-table` option can be specified to create a symbol table, although Archive::Ar delegates the task to `ranlib`, it doesn't do it itself.

Archive::Ar stores everything in memory, so beware.

Archive::Ar is incapable (as of right now) of recreating files with their archived modification times.

# AUTHOR

Written by Samuel Young, <samyoung12788@gmail.com>. The original Perl module was written by Jay Bonci (<jaybonci@cpan.org>) and John Bazik (<jbazik@cpan.org>).

The source for this module can be found on its [Codeberg page](https://codeberg.org/1-1sam/Archive-Ar). Comments and pull requests are welcome.

# COPYRIGHT

Copyright 2025, Samuel Young

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

# SEE ALSO

ar(1), ranlib(1)


## dist_cpan-FRITH-Math-Libgsl-MovingWindow.md
[![Actions Status](https://github.com/frithnanth/raku-Math-Libgsl-MovingWindow/workflows/test/badge.svg)](https://github.com/frithnanth/raku-Math-Libgsl-MovingWindow/actions) [![Build Status](https://travis-ci.org/frithnanth/raku-Math-Libgsl-MovingWindow.svg?branch=master)](https://travis-ci.org/frithnanth/raku-Math-Libgsl-MovingWindow)

![Moving mean, minimum and maximum](examples/01-movingwindow.svg)

# NAME

Math::Libgsl::MovingWindow - An interface to libgsl, the Gnu Scientific Library - Moving Window Statistics

# SYNOPSIS

```
use Math::Libgsl::Vector;
use Math::Libgsl::MovingWindow;

my Math::Libgsl::Vector $x .= new: 1000;
$x.scanf('data.dat');
my Math::Libgsl::MovingWindow $mw .= new: :10samples;
my Math::Libgsl::Vector $res = $mw.mean($x);
$res[^$res.vector.size]».put;

```

# DESCRIPTION

Math::Libgsl::MovingWindow is an interface to the Moving Window Statistics functions of libgsl, the Gnu Scientific Library.

This class creates a window around a sample which is used to calculate various local statistical properties of an input data stream. The window is then slid forward by one sample to process the next data point and so on.

### new(Int :$samples!)

### new(Int :$before!, Int :$after!)

The constructor accepts one or two named arguments. If just the **samples** argument is provided then a workspace is allocated for computing symmetric, centered moving statistics with the specified window length. When both **sbefore** and **after** arguments are provided then the window has **before** samples before the current sample and **after** samples after.

In all the following methods the user must specify how to construct the windows near the end points. Every method allows for a **$endtype** argument, which defaults to **GSL\_MOVSTAT\_END\_PADZERO**. The symbolic names for this argument are listed in the Math::Libgsl::Constants module as follows:

* **GSL\_MOVSTAT\_END\_PADZERO**: inserts zeros into the window near the signal end points
* **GSL\_MOVSTAT\_END\_PADVALUE**: pads the window with the first and last sample in the input signal
* **GSL\_MOVSTAT\_END\_TRUNCATE**: no padding is performed: the windows are truncated as the end points are approached

### mean(Math::Libgsl::Vector $x!, Int :$endtype? = GSL\_MOVSTAT\_END\_PADZERO, Bool :$inplace? --> Math::Libgsl::Vector)

This method computes the moving window mean of the input vector **$x**, returning a Math::Libgsl::Vector of the same length as the input one. The **$endtype** is optional and defaults to GSL\_MOVSTAT\_END\_PADZERO. The boolean named argument **:$inplace** directs the method to compute the mean in-place. If an error occurs during the computation this method returns a failure object.

### variance(Math::Libgsl::Vector $x, Int :$endtype? = GSL\_MOVSTAT\_END\_PADZERO, Bool :$inplace? --> Math::Libgsl::Vector)

This method computes the moving variance of the input vector **$x**, returning a Math::Libgsl::Vector of the same length as the input one. The **$endtype** is optional and defaults to GSL\_MOVSTAT\_END\_PADZERO. The boolean named argument **:$inplace** directs the method to compute the variance in-place. If an error occurs during the computation this method returns a failure object.

### sd(Math::Libgsl::Vector $x, Int :$endtype? = GSL\_MOVSTAT\_END\_PADZERO, Bool :$inplace? --> Math::Libgsl::Vector)

This method computes the moving standard deviation of the input vector **$x**, returning a Math::Libgsl::Vector of the same length as the input one. The **$endtype** is optional and defaults to GSL\_MOVSTAT\_END\_PADZERO. The boolean named argument **:$inplace** directs the method to compute the standard deviation in-place. If an error occurs during the computation this method returns a failure object.

### min(Math::Libgsl::Vector $x, Int :$endtype? = GSL\_MOVSTAT\_END\_PADZERO, Bool :$inplace? --> Math::Libgsl::Vector)

This method computes the moving minimum of the input vector **$x**, returning a Math::Libgsl::Vector of the same length as the input one. The **$endtype** is optional and defaults to GSL\_MOVSTAT\_END\_PADZERO. The boolean named argument **:$inplace** directs the method to compute the minimum in-place. If an error occurs during the computation this method returns a failure object.

### max(Math::Libgsl::Vector $x, Int :$endtype? = GSL\_MOVSTAT\_END\_PADZERO, Bool :$inplace? --> Math::Libgsl::Vector)

This method computes the moving maximum of the input vector **$x**, returning a Math::Libgsl::Vector of the same length as the input one. The **$endtype** is optional and defaults to GSL\_MOVSTAT\_END\_PADZERO. The boolean named argument **:$inplace** directs the method to compute the maximum in-place. If an error occurs during the computation this method returns a failure object.

### minmax(Math::Libgsl::Vector $x, Int :$endtype? = GSL\_MOVSTAT\_END\_PADZERO --> List)

This method computes the moving minimum and maximum of the input vector **$x**, returning a List of two Math::Libgsl::Vector objects of the same length as the input one. The **$endtype** is optional and defaults to GSL\_MOVSTAT\_END\_PADZERO. If an error occurs during the computation this method returns a failure object.

### sum(Math::Libgsl::Vector $x, Int :$endtype? = GSL\_MOVSTAT\_END\_PADZERO, Bool :$inplace? --> Math::Libgsl::Vector)

This method computes the moving sum of the input vector **$x**, returning a Math::Libgsl::Vector of the same length as the input one. The **$endtype** is optional and defaults to GSL\_MOVSTAT\_END\_PADZERO. The boolean named argument **:$inplace** directs the method to compute the sum in-place. If an error occurs during the computation this method returns a failure object.

### median(Math::Libgsl::Vector $x, Int :$endtype? = GSL\_MOVSTAT\_END\_PADZERO, Bool :$inplace? --> Math::Libgsl::Vector)

This method computes the moving median of the input vector **$x**, returning a Math::Libgsl::Vector of the same length as the input one. The **$endtype** is optional and defaults to GSL\_MOVSTAT\_END\_PADZERO. The boolean named argument **:$inplace** directs the method to compute the median in-place. If an error occurs during the computation this method returns a failure object.

### mad0(Math::Libgsl::Vector $x, Int :$endtype? = GSL\_MOVSTAT\_END\_PADZERO --> List)

### mad(Math::Libgsl::Vector $x, Int :$endtype? = GSL\_MOVSTAT\_END\_PADZERO --> List)

This method computes the moving Median Absolute Deviation (MAD) of the input vector **$x**, returning a List of two Math::Libgsl::Vector objects of the same length as the input one: the median and the MAD. The **$endtype** is optional and defaults to GSL\_MOVSTAT\_END\_PADZERO. If an error occurs during the computation this method returns a failure object. The mad0 method does not include the scale factor of 1.4826.

### qqr(Math::Libgsl::Vector $x, Num() $quantile, Int :$endtype? = GSL\_MOVSTAT\_END\_PADZERO --> Math::Libgsl::Vector)

This method computes the moving q-quantile range (QQR) of the input vector **$x**, returning a Math::Libgsl::Vector of the same length as the input one. The **$quantile** argument must be between 0 and 0.5. The **$endtype** is optional and defaults to GSL\_MOVSTAT\_END\_PADZERO. If an error occurs during the computation this method returns a failure object.

### Sn(Math::Libgsl::Vector $x, Int :$endtype? = GSL\_MOVSTAT\_END\_PADZERO --> Math::Libgsl::Vector)

This method computes the moving Sₙ statistics of the input vector **$x**, returning a Math::Libgsl::Vector of the same length as the input one. The **$endtype** is optional and defaults to GSL\_MOVSTAT\_END\_PADZERO. If an error occurs during the computation this method returns a failure object.

### Qn(Math::Libgsl::Vector $x, Int :$endtype? = GSL\_MOVSTAT\_END\_PADZERO --> Math::Libgsl::Vector)

This method computes the moving Qₙ statistics of the input vector **$x**, returning a Math::Libgsl::Vector of the same length as the input one. The **$endtype** is optional and defaults to GSL\_MOVSTAT\_END\_PADZERO. If an error occurs during the computation this method returns a failure object.

# C Library Documentation

For more details on libgsl see <https://www.gnu.org/software/gsl/>. The excellent C Library manual is available here <https://www.gnu.org/software/gsl/doc/html/index.html>, or here <https://www.gnu.org/software/gsl/doc/latex/gsl-ref.pdf> in PDF format.

# Prerequisites

This module requires the libgsl library to be installed. Please follow the instructions below based on your platform:

## Debian Linux and Ubuntu 20.04

```
sudo apt install libgsl23 libgsl-dev libgslcblas0

```

That command will install libgslcblas0 as well, since it's used by the GSL.

## Ubuntu 18.04

libgsl23 and libgslcblas0 have a missing symbol on Ubuntu 18.04. I solved the issue installing the Debian Buster version of those three libraries:

* <http://http.us.debian.org/debian/pool/main/g/gsl/libgslcblas0_2.5+dfsg-6_amd64.deb>
* <http://http.us.debian.org/debian/pool/main/g/gsl/libgsl23_2.5+dfsg-6_amd64.deb>
* <http://http.us.debian.org/debian/pool/main/g/gsl/libgsl-dev_2.5+dfsg-6_amd64.deb>

# Installation

To install it using zef (a module management tool):

```
$ zef install Math::Libgsl::MovingWindow

```

# AUTHOR

Fernando Santagata [nando.santagata@gmail.com](mailto:nando.santagata@gmail.com)

# COPYRIGHT AND LICENSE

Copyright 2020 Fernando Santagata

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


## version.md
class Version

Module version descriptor

```raku
class Version { }
```

Version objects identify version of software components (and potentially other entities). Raku uses them internally for versioning modules.

A version consists of several parts, which are visually represented by joining them with a dot. A version part is usually an integer, a string like `alpha`, or a [`Whatever`](/type/Whatever)-star `*`. The latter is used to indicate that any version part is acceptable in another version that is compared to the current one.

```raku
say v1.0.1 ~~ v1.*;     # OUTPUT: «True␤»
say v1.0.1 ~~ v1.*.1;   # OUTPUT: «True␤»
```

The first part of version literals contains `v` and a number; this might be followed by alphanumeric and [`Whatever`](/type/Whatever) parts and trailed by `+`. Multiple parts are separate with a dot `.`. A trailing `+` indicates that higher versions are OK in comparisons:

```raku
say v1.2 ~~ v1.0;                 # OUTPUT: «False␤»
say v1.2 ~~ v1.0+;                # OUTPUT: «True␤»
say v0.and.anything.else ~~ v0+;  # OUTPUT: «True␤»
```

In comparisons, order matters, and every part is compared in turn.

```raku
say v1.2 cmp v2.1;      # OUTPUT: «Less␤»
```

The `+` suffix is always taken into account in comparisons:

```raku
say v1.0.1+ <=> v1.0.1; # OUTPUT: «More␤»
```

And `*` ([`Whatever`](/type/Whatever)) is too, and considered always `Less` than whatever digit is in the corresponding part, even if `*` is trailed by `+`:

```raku
say v1.* <=> v1.0;      # OUTPUT: «Less␤»
say v1.* <= v1.0;       # OUTPUT: «True␤»
say v1.*+ <= v1.0;      # OUTPUT: «True␤»
```

Please note that method calls, including pseudo methods like `WHAT`, require version literals either to be enclosed with parentheses or use some other method to separate them from the dot that denotes a method call, like in these examples:

```raku
say (v0.and.some.*.stuff).parts;  # OUTPUT: «(0 and some * stuff)␤»
say v0.and.some.*.stuff .parts;   # OUTPUT: «(0 and some * stuff)␤»
```

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

## [method new](#class_Version "go to top of document")[§](#method_new "direct link")

```raku
method new(Str:D $s)
```

Creates a `Version` from a string `$s`. The string is combed for the numeric, alphabetic, and wildcard components of the version object. Any characters other than alphanumerics and asterisks are assumed to be equivalent to a dot. A dot is also assumed between any adjacent numeric and alphabetic characters.

## [method parts](#class_Version "go to top of document")[§](#method_parts "direct link")

```raku
method parts(Version:D: --> List:D)
```

Returns the list of parts that make up this `Version` object

```raku
my $v1 = v1.0.1;
my $v2 = v1.0.1+;
say $v1.parts;                                    # OUTPUT: «(1 0 1)␤»
say $v2.parts;                                    # OUTPUT: «(1 0 1)␤»
```

The `+` suffix is not considered a *part* of the `Version` object, and thus not returned by this method, as shown above in the `$v2` variable.

## [method plus](#class_Version "go to top of document")[§](#method_plus "direct link")

```raku
method plus(Version:D: --> Bool:D)
```

Returns `True` if comparisons against this version allow larger versions too.

```raku
my $v1 = v1.0.1;
my $v2 = v1.0.1+;
say $v1.plus;                                     # OUTPUT: «False␤»
say $v2.plus;                                     # OUTPUT: «True␤»
```

## [method Str](#class_Version "go to top of document")[§](#method_Str "direct link")

```raku
method Str(Version:D: --> Str:D)
```

Returns a string representation of the invocant.

```raku
my $v1 = v1.0.1;
my $v2 = Version.new('1.0.1');
say $v1.Str;                                      # OUTPUT: «1.0.1␤»
say $v2.Str;                                      # OUTPUT: «1.0.1␤»
```

## [method gist](#class_Version "go to top of document")[§](#method_gist "direct link")

```raku
method gist(Version:D: --> Str:D)
```

Returns a string representation of the invocant, just like [`Str`](#method_Str), prepended with a lowercase `v`.

```raku
my $v1 = v1.0.1;
my $v2 = Version.new('1.0.1');
say $v1.gist;                                      # OUTPUT: «v1.0.1␤»
say $v2.gist;                                      # OUTPUT: «v1.0.1␤»
```

## [method Capture](#class_Version "go to top of document")[§](#method_Capture "direct link")

```raku
method Capture()
```

Throws [`X::Cannot::Capture`](/type/X/Cannot/Capture).

# [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link")

Type relations for `Version`

raku-type-graph

Version
Version

Any
Any

Version->Any

Mu
Mu

Any->Mu

[Expand chart above](/assets/typegraphs/Version.svg)


## subscripts.md
## Chunk 1 of 2
Subscripts

Accessing data structure elements by index or key

One often needs to refer to a specific element (or slice of elements) from a collection or data structure. Borrowing from mathematical notation where the components of a vector *v* would be referred to as *v₁, v₂, v₃*, this concept is called "subscripting" (or "indexing") in Raku.

# [Basics](#Subscripts "go to top of document")[§](#Basics "direct link")

Raku provides two universal subscripting interfaces:

|  | elements are identified by | interface name | supported by |
| --- | --- | --- | --- |
| [ ] | zero-based indices | Positional | Array, List, Buf, Match, ... |
| { } | string or object keys | Associative | Hash, Bag, Mix, Match, ... |

## [`Positional`](/type/Positional) subscripting[§](#Positional_subscripting "direct link")

[`Positional`](/type/Positional) subscripting (via [`postcircumfix [ ]`](/language/operators#postcircumfix_[_])) addresses elements of an ordered collection by their position. Index 0 refers to the first element, index 1 to the second, and so on:

```raku
my @chores = "buy groceries", "feed dog", "wash car";
say @chores[0];  # OUTPUT: «buy groceries␤»
say @chores[1];  # OUTPUT: «feed dog␤»
say @chores[2];  # OUTPUT: «wash car␤»
```

Note that Rakudo's implementation of subscripting allows only 63 bits on 64 bit builds. See [Stack Overflow](https://stackoverflow.com/questions/61031107/do-array-indices-need-to-be-native-ints/61031617#61031617). If larger subscripts are required, one may use [Array::Sparse](https://raku.land/zef:lizmat/Array::Sparse) or alternatively, use a [`Hash`](/type/Hash) with [`Associative`](/type/Associative) subscripting (see below).

## [`Associative`](/type/Associative) subscripting[§](#Associative_subscripting "direct link")

[`Associative`](/type/Associative) subscripting (via [`postcircumfix { }`](/language/operators#postcircumfix_{_})), does not require the collection to keep its elements in any particular order - instead, it uses a unique key to address each value. The nature of the keys depends on the collection in question: For example a standard [`Hash`](/type/Hash) uses string keys, whereas a [`Mix`](/type/Mix) allows arbitrary objects as keys, etc.:

```raku
my %grade = Zoe => "C", Ben => "B+";
say %grade{"Zoe"};  # OUTPUT: «C␤»
say %grade{"Ben"};  # OUTPUT: «B+␤»

my $stats = ( Date.today => 4.18, Date.new(2015,  4,  5) => 17.253 ).Mix;
say $stats{ Date.new(2015, 4, 4) + 1 };  # OUTPUT: «17.253␤»
```

For passing single-word string keys to `{ }`, you can also use the [angle bracketed word quoting constructs](/language/quoting#Word_quoting:_qw) as if they were postcircumfix operators:

```raku
my %grade = Zoe => "C", Ben => "B+";
say %grade<Zoe>;    # OUTPUT: «C␤»
say %grade<Ben>;    # OUTPUT: «B+␤»
```

This is really just syntactic sugar that gets turned into the corresponding `{ }` form at compile-time:

```raku
%hash<foo bar>;       # same as %hash{ <foo bar> }
%hash«foo "$var"»;    # same as %hash{ «foo "$var"» }
%hash<<foo "$var">>;  # same as %hash{ <<foo "$var">> }

```

You may have noted above that we avoided having to quote `Zoe` by using the `=>` operator, but that same operator did not just put invisible quotes around `Date.new(2015, 4, 5)`, and we were able to find the same element using `$stats{ Date.new(2015, 4, 4) + 1 }`. This is because `=>` only puts invisible quotes around single words, and by "word" we mean an identifier/name. The `=>` operator is there to prevent us from accidentally calling functions or using constants with that name.

Hash subscripts do not do the same thing as `=>`. The default [`Hash`](/type/Hash) has been made to behave the way new users have come to expect from using other languages, and for general ease of use. On a default [`Hash`](/type/Hash), subscripts coerce keys into strings, as long as those keys produce something [`Cool`](/type/Cool). You can use `.raku` on a collection to be sure whether the keys are strings or objects:

```raku
( 1  => 1 ).raku.say;            # OUTPUT: «1 => 1␤»
my %h; %h{1}   = 1; say %h.raku; # OUTPUT: «{ "1" => 1 }␤»
( 1/2 => 1 ).raku.say;           # OUTPUT: «0.5 => 1␤»
my %h; %h{1/2} = 1; say %h.raku; # OUTPUT: «{ "0.5" => 1 }␤»
( pi => 1 ).raku.say;            # OUTPUT: «:pi(1)␤»
my %h; %h{pi}  = 1; say %h.raku; # OUTPUT: «{ "3.14159265358979" => 1 }␤»
```

While the invisible quotes around single names is built into `=>`, string conversion is not built into the curly braces: it is a behavior of the default [`Hash`](/type/Hash). Not all types of hashes or collections do so:

```raku
my %h := MixHash.new;
%h{pi} = 1; %h.raku.say;         # OUTPUT: «(3.14159265358979e0=>1).MixHash␤»

```

(Any name that `=>` would convert to a string can also be used to build a pair using "adverbial notation" and will appear that way when viewed through `.raku`, which is why we see `:pi(1)` above.)

## [Applying subscripts](#Subscripts "go to top of document")[§](#Applying_subscripts "direct link")

Subscripts can be applied to any expression that returns a subscriptable object, not just to variables:

```raku
say "__Hello__".match(/__(.*)__/)[0];   # OUTPUT: «｢Hello｣␤»
say "__Hello__".match(/__(.*)__/).[0];  # same, in method notation
```

Positional and associative subscripting are not mutually exclusive - for example, [`Match`](/type/Match) objects support both (each accessing a different set of data). Also, to make list processing more convenient, class [`Any`](/type/Any) provides a fallback implementation for positional subscripts which simply treats the invocant as a list of one element. (But there's no such fallback for associative subscripts, so they throw a runtime error when applied to an object that does not implement support for them.)

```raku
say 42[0];    # OUTPUT: «42␤»
say 42<foo>;  # ERROR: Type Int does not support associative indexing.

```

# [Nonexistent elements](#Subscripts "go to top of document")[§](#Nonexistent_elements "direct link")

What happens when a *nonexistent* element is addressed by a subscript is up to the collection type in question. Standard [`Array`](/type/Array) and [`Hash`](/type/Hash) collections return the type object of their [value type constraint](/routine/of) (which, by default, is [`Any`](/type/Any)) unless the collection has been declared with the [`is default`](/type/Variable#trait_is_default) trait in which case the returned value will be whatever the programmer declared it to be:

```raku
# no default values specified
my @array1;     say @array1[10];                   # OUTPUT: «(Any)␤»
my Int @array2; say @array2[10];                   # OUTPUT: «(Int)␤»

my %hash1;      say %hash1<foo>;                   # OUTPUT: «(Any)␤»
my Int %hash2;  say %hash2<foo>;                   # OUTPUT: «(Int)␤»

# default values specified
my @array3 is default('--');     say @array3[10];  # OUTPUT: «--␤»
my Int @array4 is default(17);   say @array4[10];  # OUTPUT: «17␤»

my %hash3 is default('Empty');   say %hash3<foo>;  # OUTPUT: «Empty␤»
my Int %hash4 is default(4711);  say %hash4<foo>;  # OUTPUT: «4711␤»
```

However, other types of collections may react differently to subscripts that address nonexistent elements:

```raku
say (0, 10, 20)[3];           # OUTPUT: «Nil␤»
say bag(<a a b b b>)<c>;      # OUTPUT: «0␤»
say array[uint8].new(1, 2)[2] # OUTPUT: «0␤»
```

To silently skip nonexistent elements in a subscripting operation, see [Truncating slices](#Truncating_slices) and the [`:v`](#:v) adverb.

# [From the end](#Subscripts "go to top of document")[§](#From_the_end "direct link")

Positional indices are counted from the start of the collection, but there's also a notation for addressing elements by their position relative to the end: `*-1` refers to the last element, `*-2` to the second-to-last element, and so on. From version 6.d, `*-0` refers to the element just beyond the last one

```raku
my @alphabet = 'A' .. 'Z';
say @alphabet[*-1];  # OUTPUT: «Z␤»
say @alphabet[*-2];  # OUTPUT: «Y␤»
say @alphabet[*-3];  # OUTPUT: «X␤»
@alphabet[*-0] = 'þ';
say @alphabet;
#  OUTPUT: «[A B C D E F G H I J K L M N O P Q R S T U V W X Y Z þ]␤»
```

**Note**: The asterisk, which is actually a [`Whatever`](/type/Whatever), is important. Passing a bare negative integer (e.g. `@alphabet[-1]`) like you would do in many other programming languages, throws an error in Raku.

What actually happens here, is that an expression like `*-1` declares a code object via [`Whatever`](/type/Whatever)-priming - and the `[ ]` subscript reacts to being given a code object as an index, by calling it with the length of the collection as argument and using the result value as the actual index. In other words, `@alphabet[*-1]` becomes `@alphabet[@alphabet.elems - 1]`.

This means that you can use arbitrary expressions which depend on the size of the collection:

```raku
say @array[* div 2];  # select the middlemost element
say @array[$i % *];   # wrap around a given index ("modular arithmetic")
say @array[ -> $size { $i % $size } ];  # same as previous

```

# [Slices](#Subscripts "go to top of document")[§](#Slices "direct link")

When multiple elements of a collection need to be accessed, there's a shortcut to doing multiple separate subscripting operations: Simply specify a *list* of indices/keys in the subscript, to get back a *list* of elements - also called a "slice" - in the same order.

For positional slices, you can mix normal indices with [from-the-end](#From_the_end) ones:

```raku
my @alphabet = 'a' .. 'z';
say @alphabet[15, 4, *-9, 11].raku;  # OUTPUT: «("p", "e", "r", "l")␤»
```

In the `*-number` construct above, `*` indicates the end of the array as explained above in the [From the end](#From_the_end) section. So if you want to take the last N elements of the array, you will have to create a [`Range`](/type/Range) that includes it.

```raku
(5802..5830).map( {.chr} )[*-10..*-5] # OUTPUT:  «(ᚽ ᚾ ᚿ ᛀ ᛁ ᛂ)␤»
```

Using `*` as the last element of the range will, effectively, return the last elements of the collection.

For associative slices, the angle brackets form often comes in handy:

```raku
my %color = kiwi => "green", banana => "yellow", cherry => "red";
say %color{"cherry", "kiwi"};  # OUTPUT: «(red green)␤»
say %color<cherry kiwi>;       # OUTPUT: «(red green)␤»
say %color{*};                 # OUTPUT: «(red yellow green)␤»
```

Be aware that slices are controlled by the *type* of what is passed to ([one dimension of](#Multiple_dimensions)) the subscript, not its length. In particular the *type* can be any of the following:

* a lazy Iterable, that [truncates](#Truncating_slices) in [ ]
* accordingly, an infinite Range will truncate, but a finite one produces a normal slice
* '\*' (whatever-star), that returns the full slice (as if all keys/indices were specified)
* '\*\*' (hyperwhatever-star), that returns the full slice (as if all keys/indices were specified), with any lists flattened recursively (since Rakudo Release 2024.08)
* any other object, that provides a single-element access rather than a slice
* Callable, whatever is returned by the callable (this can lead to recursion)
* empty, the full slice known as [Zen slice](#Zen_slices)
* any iterable different from the above ones, normal slice

The notable difference between `*` and Zen slice (empty) is that the [`Whatever`](/type/Whatever) star will cause full [reification](/language/glossary#Reify) or itemization, while Zen slice won't. Both versions also [de-cont](https://perl6advent.wordpress.com/2017/12/02/perl-6-sigils-variables-and-containers/#decont).

So even a one-element list returns a slice, whereas a bare scalar value doesn't:

```raku
say @alphabet[2,];        # OUTPUT: «(c)␤»
say @alphabet[2,].^name;  # OUTPUT: «List␤»

say @alphabet[2];         # OUTPUT: «c␤»
say @alphabet[2].^name;   # OUTPUT: «Str␤»

```

(The angle bracket form for associative subscripts works out because [word quoting](/language/quoting#Word_quoting:_qw) conveniently returns a [`Str`](/type/Str) in case of a single word, but a [`List`](/type/List) in case of multiple words.)

In fact, the list structure of ([the current dimension of](#Multiple_dimensions)) the subscript is preserved across the slice operation (but the kind of Iterable is not – the result is always just lists.)

```raku
say @alphabet[0, (1..2, (3,))];       # OUTPUT: «(a ((b c) (d)))␤»
say @alphabet[0, (1..2, [3,])];       # OUTPUT: «(a ((b c) (d)))␤»
say @alphabet[flat 0, (1..2, (3,))];  # OUTPUT: «(a b c d)␤»
say flat @alphabet[0, (1..2, (3,))];  # OUTPUT: «(a b c d)␤»

```

## [Truncating slices](#Subscripts "go to top of document")[§](#Truncating_slices "direct link")

Referring to nonexistent elements in a slice subscript causes the output [`List`](/type/List) to contain undefined values (or [whatever else](#Nonexistent_elements) the collection in question chooses to return for nonexistent elements):

```raku
my  @letters = <a b c d e f>;
say @letters[3..7];  # OUTPUT: «(d e f (Any) (Any))␤»

```

This behavior, while at first glance may seem unintuitive, is desirable in instances when you want to assign a value at an index in which a value does not currently exist.

```raku
my  @letters;
say @letters; # OUTPUT: «[]␤»

@letters[^10] = 'a'..'z';
say @letters; # OUTPUT: «[a b c d e f g h i j]␤»

```

If you want the resulting slice to only include existing elements, you can silently skip the non-existent elements using the [`:v`](#:v) adverb.

```raku
my  @letters = <a b c d e f>;
say @letters[3..7]:v;  # OUTPUT: «(d e f)␤»

```

The behavior when indexing a collection via [lazy](/language/list#Lazy_lists) subscripts is different than when indexing with their eager counterparts. When accessing via a lazy subscript, the resulting slice will be truncated.

```raku
say @letters[lazy 3..7]; # OUTPUT: «(d e f)␤»
say @letters[     3..*]; # OUTPUT: «(d e f)␤»

```

This behavior exists as a precaution to prevent runaway generation of massive, potentially infinite [`List`](/type/List)s and the out-of-memory issues that occur as a result.

## [Zen slices](#Subscripts "go to top of document")[§](#Zen_slices "direct link")

If you put the subscript operator behind an object without specifying any indices/keys at all, it simply returns the subscripted object itself. Since it is empty but returns everything, it is known as a *Zen slice*.

Zen slicing is different from passing a [`Whatever`](/type/Whatever)-star (which, like a normal slice, always returns a List of elements no matter the type of the original object) or an empty list (which returns an empty slice):

```raku
my %bag := (orange => 1, apple => 3).Bag;
say %bag<>;    # OUTPUT: «Bag(apple(3) orange)␤»
say %bag{};    # OUTPUT: «Bag(apple(3) orange)␤»
say %bag{*};   # OUTPUT: «(1 3)␤»
say %bag{()};  # OUTPUT: «()␤»
```

Zen slicing does not [reify](/language/glossary#Reify) or [cache](/routine/cache) (not even [`Seq`](/type/Seq)s) and merely returns the invocant. It is usually used to [interpolate](/language/quoting#Interpolation:_qq) entire arrays / hashes into strings or to [decont](/language/glossary#decont).

```raku
my @words = "cruel", "world";
say "Hello, @words[]!";  # OUTPUT: «Hello, cruel world!␤»

my $list = <a b c>;
.say for $list;   # OUTPUT: «(a b c)␤»
.say for $list<>; # OUTPUT: «a␤b␤c␤»
.say for $list[]; # OUTPUT: «a␤b␤c␤»

my @fib = 1,1, * + * … *;
say @fib[];                 # OUTPUT: «[...]␤»
```

# [Multiple dimensions](#Subscripts "go to top of document")[§](#Multiple_dimensions "direct link")

Dimensions in subscripts are separated by a semicolon, allowing to mix lists of elements and dimensions.

```raku
my @twodim = (<a b c>, (1, 2, 3));
say @twodim;
# OUTPUT: «[(a b c) (1 2 3)]␤»

say @twodim[0,1;1]; # 2nd element of both lists
# OUTPUT: «(b 2)␤»

my %pantheon = %('Baldr' => 'consort' => 'Nanna' ,
                 'Bragi' => 'consort' => 'Iðunn' ,
                 'Nótt'  => 'consort' => 'Dellingr' );
say %pantheon{'Bragi','Nótt';'consort'}; # 'consort' value for both keys
# OUTPUT: «(Iðunn Dellingr)␤»
```

Multidimensional subscripts can be used to flatten nested lists when combined with [`Whatever`](/type/Whatever).

```raku
my @toomany = [[<a b>], [1, 2]];
say @toomany;
# OUTPUT: «[[a b] [1 2]]␤»

say @toomany[*;*];
# OUTPUT: «(a b 1 2)␤»
```

You can use as many *flattening semicolons* as you want; there will be, at most, as many nesting levels flattened as the number of semicolons:

```raku
say [[1,2,[3,4]],[4,5]][*;*];     # OUTPUT: «(1 2 [3 4] 4 5)␤»
say [[1,2,[3,4]],[4,5]][*;*;*;*]; # OUTPUT: «(1 2 3 4 4 5)␤»
```

In the first example, with one [`Whatever`](/type/Whatever) less than the number of levels, the deepest one will not be flattened; in the second case it is, since it's greater than the number of levels.

You can use [`Whatever`](/type/Whatever) to select ranges or "rows" in multidimensional subscripts.

```raku
my @a = [[1,2], [3,4]];
say @a[*;1]; # 2nd element of each sub list
# OUTPUT: «(2 4)␤»
my @a = (<1 c 6>, <2 a 4>, <5 b 3>);
say @a.sort( { $_[1] } ); # sort by 2nd column
# OUTPUT: «((2 a 4) (5 b 3) (1 c 6))␤»
```

# [Modifying elements](#Subscripts "go to top of document")[§](#Modifying_elements "direct link")

# [Autovivification](#Subscripts "go to top of document")[§](#Autovivification "direct link")

Subscripts participate in "autovivification", i.e. the process by which arrays and hashes automatically spring into existence when needed, so that you can build nested data structures without having to pre-declare the collection type at each level:

```raku
my $beatles;

$beatles{"White Album"}[0] = "Back in the U.S.S.R.";  # autovivification!

say $beatles.raku;  # OUTPUT: «${"White Album" => $["Back in the U.S.S.R."]}␤»

```

`$beatles` started out undefined, but became a [`Hash`](/type/Hash) object because it was subscripted with `{ }` in the assignment. Similarly, `$beatles{"White Album"}` became an [`Array`](/type/Array) object due to being subscripted with `[ ]` in the assignment.

Note that the subscripting itself does not cause autovivification: It only happens when the result of the subscripting chain is *assigned* to (or otherwise mutated).

# [Binding](#Subscripts "go to top of document")[§](#Binding "direct link")

A subscripting expression may also be used as the left-hand-side of a binding statement. If supported by the subscripted collection's type, this replaces whatever value container would be naturally found at that "slot" of the collection, with the specified container.

The built-in [`Array`](/type/Array) and [`Hash`](/type/Hash) types support this in order to allow building complex linked data structures:

```raku
my @a = 10, 11, 12, 13;
my $x = 1;

@a[2] := $x;  # Bound! (@a[2] and $x refer to the same container now.)

$x++; @a[2]++;

say @a;  # OUTPUT: «[10 11 3 13]␤»
say $x;  # OUTPUT: «3␤»
```

This can be specially useful when lazy data structures are part of a bigger one.

```raku
my @fib = 1,1, * + * … ∞;
my @lucas = 1,3, * + * … ∞;
my %sequences;
%sequences<f> := @fib;
%sequences<l> := @lucas;
for %sequences.keys -> $s {
    for ^10 -> $n {
        say %sequences{$s}[100+$n*10]/%sequences{$s}[101+$n*10];
    }
}
# OUTPUT: 0.6180339887498949 times 20.

```

In this case, hash keys are bound to lazily generated sequences. The fact that they are bound means that whatever state has been computed is shared by the hash value and the sequence it's bound to, making computations of subsequent elements faster.

See [method `BIND-POS`](#method_BIND-POS) and [method `BIND-KEY`](#method_BIND-KEY) for the underlying mechanism.

# [Adverbs](#Subscripts "go to top of document")[§](#Adverbs "direct link")

The return value and possible side-effect of a subscripting operation can be controlled using adverbs; these are defined on the relevant subscript [operators](/language/operators#Method_postfix_precedence).

Beware of the relatively loose precedence of operator adverbs, which may require you to add parentheses in compound expressions:

```raku
if $foo || %hash<key>:exists { ... }    # WRONG, tries to adverb the || op

```

```raku
if $foo || (%hash<key>:exists) { ... }  # correct
if $foo or %hash<key>:exists { ... }    # also correct

```

The supported adverbs are:

## [`:exists`](#Subscripts "go to top of document")[§](#:exists "direct link")

Returns whether or not the requested element exists, instead of returning the element's actual value. This can be used to distinguish between elements with an undefined value, and elements that aren't part of the collection at all:

```raku
my @foo = Any, 10;
say @foo[0].defined;    # OUTPUT: «False␤»
say @foo[0]:exists;     # OUTPUT: «True␤»
say @foo[2]:exists;     # OUTPUT: «False␤»
say @foo[0, 2]:exists;  # OUTPUT: «(True False)␤»

my %fruit = apple => Any, orange => 10;
say %fruit<apple>.defined;       # OUTPUT: «False␤»
say %fruit<apple>:exists;        # OUTPUT: «True␤»
say %fruit<banana>:exists;       # OUTPUT: «False␤»
say %fruit<apple banana>:exists; # OUTPUT: «(True False)␤»
```

May also be negated to test for non-existence:

```raku
say %fruit<apple banana>:!exists; # OUTPUT: «(False True)␤»

```

To check if *all* elements of a slice exist, use an [all](/routine/all) junction:

```raku
if all %fruit<apple orange banana>:exists { ... }

```

It can be used on multi-dimensional arrays and hashes:

```raku
my @multi-dim = 1, [2, 3, [4, 5]];
say @multi-dim[1;2;0]:exists;                # OUTPUT: «True␤»
say @multi-dim[1;2;5]:exists;                # OUTPUT: «False␤»

my %multi-dim = 1 => { foo => { 3 => 42 } };
say %multi-dim{1;'foo';3}:exists;            # OUTPUT: «True␤»
say %multi-dim{1;'bar';3}:exists;            # OUTPUT: «False␤»
```

`:exists` can be combined with the [`:delete`](#:delete) and [`:p`](#:p)/[`:kv`](#:kv) adverbs - in which case the behavior is determined by those adverbs, except that any returned element *value* is replaced with the corresponding [`Bool`](/type/Bool) indicating element *existence*.

See [method `EXISTS-POS`](#method_EXISTS-POS) and [method `EXISTS-KEY`](#method_EXISTS-KEY) for the underlying mechanism.

## [`:delete`](#Subscripts "go to top of document")[§](#:delete "direct link")

Delete the element from the collection or, if supported by the collection, creates a hole at the given index, in addition to returning its value.

```raku
my @tens = 0, 10, 20, 30;
say @tens[3]:delete;     # OUTPUT: «30␤»
say @tens;               # OUTPUT: «[0 10 20]␤»

my %fruit = apple => 5, orange => 10, banana => 4, peach => 17;
say %fruit<apple>:delete;         # OUTPUT: «5␤»
say %fruit<peach orange>:delete;  # OUTPUT: «(17 10)␤»
say %fruit;                       # OUTPUT: «{banana => 4}␤»
```

Note that assigning [`Nil`](/type/Nil) will revert the container at the given index to its default value. It will not create a hole. The created holes can be tested for with `:exists` but iteration will not skip them and produce undefined values instead.

```raku
my @a = 1, 2, 3;
@a[1]:delete;
say @a[1]:exists;
# OUTPUT: «False␤»
.say for @a;
# OUTPUT: «1␤(Any)␤3␤»
```

With the negated form of the adverb, the element is not actually deleted. This means you can pass a flag to make it conditional:

```raku
say %fruit<apple> :delete($flag);  # deletes the element only if $flag is
                                   # true, but always returns the value.

```

It can be combined with the [`:exists`](#:exists) and [`:p`](#:p)/[`:kv`](#:kv)/[`:k`](#:k)/[`:v`](#:v) adverbs - in which case the return value will be determined by those adverbs, but the element will at the same time also be deleted.

See [method `DELETE-POS`](#method_DELETE-POS) and [method `DELETE-KEY`](#method_DELETE-KEY) for the underlying mechanism.

You can use also these adverbs on associative type objects, but it will actually do nothing; it will also return [`Nil`](/type/Nil)

```raku
say Hash<foo>:delete; # OUTPUT: «Nil␤»

```

The adverb can be used on lazy arrays too:

```raku
my @lazy-array = lazy 1, 11, 121 ... 10**100;
@lazy-array[2**24]:delete;

```

## [`:p`](#Subscripts "go to top of document")[§](#:p "direct link")

Return both the index/key and the value of the element, in the form of a [`Pair`](/type/Pair), and silently skip nonexistent elements:

```raku
my  @tens = 0, 10, 20, 30;
say @tens[1]:p;        # OUTPUT: «1 => 10␤»
say @tens[0, 4, 2]:p;  # OUTPUT: «(0 => 0 2 => 20)␤»

my  %month = Jan => 1, Feb => 2, Mar => 3;
say %month<Feb>:p;          # OUTPUT: «Feb => 2␤»
say %month<Jan Foo Mar>:p;  # OUTPUT: «(Jan => 1 Mar => 3)␤»
```

If you *don't* want to skip nonexistent elements, use the negated form:

```raku
say %month<Jan Foo Mar>:!p;  # OUTPUT: «(Jan => 1 Foo => (Any) Mar => 3)␤»

```

It can be combined with the [`:exists`](#:exists) and [`:delete`](#:delete) adverbs.

See also the [pairs](/routine/pairs) routine.

## [`:kv`](#Subscripts "go to top of document")[§](#:kv "direct link")

Return both the index/key and the value of the element, in the form of a [`List`](/type/List), and silently skip nonexistent elements. When used on a [slice](#Slices), the return value is a single flat list of interleaved keys and values:

```raku
my  @tens = 0, 10, 20, 30;
say @tens[1]:kv;        # OUTPUT: «(1 10)␤»
say @tens[0, 4, 2]:kv;  # OUTPUT: «(0 0 2 20)␤»

my  %month = Jan => 1, Feb => 2, Mar => 3;
say %month<Feb>:kv;          # OUTPUT: «(Feb 2)␤»
say %month<Jan Foo Mar>:kv;  # OUTPUT: «(Jan 1 Mar 3)␤»
```

If you *don't* want to skip nonexistent elements, use the negated form:

```raku
say %month<Jan Foo Mar>:!kv;  # OUTPUT: «(Jan 1 Foo (Any) Mar 3)␤»

```

This adverb is commonly used to iterate over slices:

```raku
for %month<Feb Mar>:kv -> $month, $i {
    say "$month had {Date.new(2015, $i, 1).days-in-month} days in 2015"
}

```

It can be combined with the [`:exists`](#:exists) and [`:delete`](#:delete) adverbs.

See also the [kv](/routine/kv) routine.

## [`:k`](#Subscripts "go to top of document")[§](#:k "direct link")

Return only the index/key of the element, rather than its value, and silently skip nonexistent elements:

```raku
my @tens = 0, 10, 20, 30;
say @tens[1]:k;        # OUTPUT: «1␤»
say @tens[0, 4, 2]:k;  # OUTPUT: «(0 2)␤»

my %month