## dist_cpan-HANENKAMP-DOM-Tiny.md
# NAME

DOM::Tiny - A lightweight, self-contained DOM parser/manipulator

# SYNOPSIS

```
use DOM::Tiny;

# Parse
my $dom = DOM::Tiny.parse('<div><p id="a">Test</p><p id="b">123</p></div>');

# Find
say $dom.at('#b').text;
say $dom.find('p').map(*.text).join("\n");
say $dom.find('[id]').map(*.attr('id')).join("\n");

# Iterate
$dom.find('p[id]').reverse.map({ .<id>.say });

# Loop
for $dom.find('p[id]') -> $e {
    say $e<id>, ':', $e.text;
}

# Modify
$dom.find('div p')[*-1].append('<p id="c">456</p>');
$dom.find(':not(p)').map(*.strip);

# Render
say "$dom";

```

# DESCRIPTION

DOM::Tiny is a smallish, relaxed pure-Perl HTML/XML DOM parser. It is relatively robust owing mostly to the enormous test suite inherited from its progenitor. The HTML/XML parsing is very forgiving and the CSS parser supports a reasonable subset of CSS3 for selecting elements in the DOM tree.

This module started as a port of Mojo::DOM58 from Perl 5, but maintaining compatibility with that library is not a major aim of this project. In fact, features of Perl 6 render certain aspects of Mojo::DOM58 completely redundant. For example, the collection system that provides custom features such as `map`, `each`, `reduce`, etc. are completely unnecessary in Perl 6. The built-in syntax is as simple or simpler to use and safer in every case.

# NODES AND ELEMENTS

When we parse an HTML/XML fragment, it gets turned into a tree of nodes.

```
<!DOCTYPE html>
<html>
<head><title>Hello</title></head>
<body>World!</body>
</html>

```

There are currently the following different kinds of nodes: Root, Text, Tag, Raw, PI, Doctype, Comment, and CDATA. These can also be grouped into the following roles: DocumentNode (anything but Root), Node (all kinds), HasChildren (Root and Tag), and TextNode (includes Text, CDATA, and Raw).

```
Root
|- Doctype (html)
+- Tag (html)
   |- Tag (head)
   |  +- Tag (title)
   |     +- Text (Hello)
   +- Tag (body)
      +- Text (World!)

```

While all node types are represented as DOM::Tiny objects, some methods like `attr` and `namespace` only apply to elements.

Under normal circumstances you will probably never need to use these objects directly, but they are available in case you have some special need.

These objects are all defined in the DOM::Tiny::HTML namespace. If you want to import the short names, they are exported by default by that compilation unit:

```
{
    use DOM::Tiny;
    my $t = DOM::Tiny::HTML::Text.new(:text<Hello>);
}

{
    use DOM::Tiny;
    use DOM::Tiny::HTML;
    my $t = Text.new(:text<Hello>);
}

```

# CASE SENSITIVITY

DOM::Tiny defaults to HTML semantics. That means all tags and attribute names are automatically lowercased at parse time. Selectors will, therefore, need to be lowercase to match anything as matching is still case-sensitive.

```
# HTML semantics
my $dom = DOM::Tiny.parse('<P ID="greeting">Hi!</P>');
say $dom.at('p[id]').text;

```

If an XML declaration is found at the start of the snippet to parse, the parser will automatically switch into XML mode and everything becomes case-sensitive.

```
# XML semantics
my $dom = DOM::Tiny.parse('<?xml version="1.0"?><P ID="greeting">Hi!</P>');
say $dom.at('P[ID]').text;

```

XML detection can also be disabled or forced by explicitly setting the `:xml` flag as needed.

```
# Force XML semantics
my $dom = DOM::Tiny.parse('<P ID="greeting">Hi!</P>', :xml);
say $dom.at('P[ID]').text;

# Force HTML semantics
$dom = DOM::Tiny.parse('<P ID="greeting">Hi!</P>', :!xml);
say $dom.at('p[id]').text;

```

# SELECTORS

DOM::Tiny uses a CSS selector engine found in DOM::Tiny::CSS. We try to support all all CSS selectors that make sense for a standalone parser.

Any element.

```
my $all = $dom.find('*');

```

## E

An element of type E.

```
my $title = $dom.at('title');

```

## E[foo]

An E element with a foo attribute.

```
my $links = $dom.find('a[href]');

```

## E[foo="bar"]

An E element whose foo attribute value is exactly equal to bar.

```
my $case_sensitive = $dom.find('input[type="hidden"]');
my $case_sensitive = $dom.find('input[type=hidden]');

```

## E[foo="bar" i]

An E element whose foo attribute value is exactly equal to any case-permutation of bar.

```
my $case_insensitive = $dom.find('input[type="hidden" i]');
my $case_insensitive = $dom.find('input[type=hidden i]');
my $case_insensitive = $dom.find('input[class~="foo" i]');

```

This selector is part of Selectors Level 4. The "i" modifier may be added to any attribute selector to make what is normally an exact match to one that matches any case-permutation.

## E[foo~="bar"]

An E element whose foo attribute value is a list of whitespace-separated values, one of which is exactly equal to bar.

```
my $foo = $dom.find('input[class~="foo"]');
my $foo = $dom.find('input[class~=foo]');

```

## E[foo^="bar"]

An E element whose foo attribute value begins exactly with the string bar.

```
my $begins_with = $dom.find('input[name^="f"]');
my $begins_with = $dom.find('input[name^=f]');

```

## E[foo$="bar"]

An E element whose foo attribute value ends exactly with the string bar.

```
my $ends_with = $dom.find('input[name$="o"]');
my $ends_with = $dom.find('input[name$=o]');

```

## E[foo\*="bar"]

An E element whose foo attribute value contains the substring bar.

```
my $contains = $dom.find('input[name*="fo"]');
my $contains = $dom.find('input[name*=fo]');

```

## E:root

An E element, root of the document.

```
my $root = $dom.at(':root');

```

## E:nth-child(n)

An E element, the n-th child of its parent.

```
my $third = $dom.find('div:nth-child(3)');
my $odd   = $dom.find('div:nth-child(odd)');
my $even  = $dom.find('div:nth-child(even)');
my $top3  = $dom.find('div:nth-child(-n+3)');

```

## E:nth-last-child(n)

An E element, the n-th child of its parent, but counting backwards from the end.

```
my $third    = $dom.find('div:nth-last-child(3)');
my $odd      = $dom.find('div:nth-last-child(odd)');
my $even     = $dom.find('div:nth-last-child(even)');
my $bottom3  = $dom.find('div:nth-last-child(-n+3)');

```

## E:nth-of-type(n)

An E element, the n-th sibling of its type.

```
my $third = $dom.find('div:nth-of-type(3)');
my $odd   = $dom.find('div:nth-of-type(odd)');
my $even  = $dom.find('div:nth-of-type(even)');
my $top3  = $dom.find('div:nth-of-type(-n+3)');

```

## E:nth-last-of-type(n)

An E element, the n-th sibling of its type, counting backwards from the end.

```
my $third    = $dom.find('div:nth-last-of-type(3)');
my $odd      = $dom.find('div:nth-last-of-type(odd)');
my $even     = $dom.find('div:nth-last-of-type(even)');
my $bottom3  = $dom.find('div:nth-last-of-type(-n+3)');

```

## E:first-child

An E element, first child of its parent.

```
my $first = $dom.find('div p:first-child');

```

## E:last-child

An E element, last child of its parent.

```
my $last = $dom.find('div p:last-child');

```

## E:first-of-type

An E element, first sibling of its type.

```
my $first = $dom.find('div p:first-of-type');

```

## E:last-of-type

An E element, last sibling of its type.

```
my $last = $dom.find('div p:last-of-type');

```

## E:only-child

An E element, only child of its parent.

```
my $lonely = $dom.find('div p:only-child');

```

## E:only-of-type

An E element, only sibling of its type.

```
my $lonely = $dom.find('div p:only-of-type');

```

## E:empty

An E element that has no children (including text nodes, meaning the element does not even contain whitespace).

```
my $empty = $dom.find(':empty');

```

## E:checked

A user interface element E which is checked (for instance a radio-button or checkbox).

```
my $input = $dom.find(':checked');

```

## E.warning

An E element whose class is "warning".

```
my $warning = $dom.find('div.warning');

```

## E#myid

An E element with an "id" attribute equal to "myid". Basically, a shorthand for `E[id=foo]`.

```
my $foo = $dom.at('div#foo');

```

## E:not(s)

An E element that does not match simple selector s.

```
my $others = $dom.find('div p:not(:first-child)');

```

## E F

An F element descendant of an E element.

```
my $headlines = $dom.find('div h1');

```

## E > F

An F element child of an E element.

```
my $headlines = $dom.find('html > body > div > h1');

```

## E + F

An F element immediately preceded by an E element.

```
my $second = $dom.find('h1 + h2');

```

## E ~ F

An F element preceded by an E element.

```
my $second = $dom.find('h1 ~ h2');

```

## E, F, G

Elements of type E, F and G.

```
my $headlines = $dom.find('h1, h2, h3');

```

## E[foo=bar][bar=baz]

An E element whose attributes match all following attribute selectors.

```
my $links = $dom.find('a[foo^=b][foo$=ar]');

```

# OPERATORS AND COERCIONS

You can use array subscripts and hash subscripts with DOM::Tiny. Using this class as an array or hash, though, is not recommended as several of the standard methods for these do not work as expected.

## Array

You may use array subscripts as a shortcut for calling `children`:

```
my $third-child = $dom[2];

```

## Hash

You may use hash subscripts as a shortcut for calling `attr`:

```
my $id = $dom<id>;

```

## Str

If you convert the DOM::Tiny object to a string using `Str`, `~`, or putting it in a string, it will render the markup.

```
my $html = "$dom";

```

# METHODS

## Construction, Parsing, and Rendering

### method new

```
method new(DOM::Tiny:U: Bool :$xml) returns DOM::Tiny:D

```

Constructs a DOM::Tiny object with an empty DOM tree. Setting the optional `$xml` flag guarantees XML mode. Setting it to a false guarantees HTML mode. If it is unset, DOM::Tiny will select a mode based upon the parsed text, defaulting to HTML.

### method deep-clone

```
method deep-clone(DOM::Tiny:D:) returns DOM::Tiny:D

```

Returns a deep-cloned copy of the current DOM::Tiny object and its children. Any change to the origin will not impact the copy and vice versa.

### method parse

```
method parse(DOM::Tiny:U: Str $ml, Bool :$xml) returns DOM::Tiny:D
method parse(DOM::Tiny:D: Str $ml, Bool :$xml) returns DOM::Tiny:D

```

Parses the given string, `$ml`, as HTML or XML based upon the `$xml` flag or autodetection if the flag is not given. If called on an existing DOM::Tiny object, the newly parsed tree will replace the previous tree.

### method render

```
method render(DOM::Tiny:D:) returns Str:D

```

This renders the current node and all its content back to a string and returns it. The format of the markup is determined by the current `xml` setting.

### method Str

```
method Str(DOM::Tiny:D:) returns Str:D

```

This is a synonym for `render`.

### method xml

```
method xml(DOM::Tiny:D:) is rw returns Bool:D

```

This is the boolean flag determining how the node was parsed and how it will be rendered.

## Finding and Filtering Nodes

### method at

```
method at(DOM::Tiny:D: Str:D $selector) returns DOM::Tiny

```

Given a CSS selector, this will return the first node matching that selector or Nil.

### method find

```
method find(DOM::Tiny:D: Str:D $selector)

```

Returns all nodes matching the given CSS `$selector` within the current node.

### method matches

```
method matches(DOM::Tiny:D: Str:D $selector) returns Bool:D

```

Returns `True` if the current node matches the given `$selector` or `False` otherwise.

## Tag Details

### postcircumfix:<{}>

```
method postcircumfix:<{}>(DOM::Tiny:D: Str:D $k) is rw

```

You may use the `.{}` operator as a shortcut for calling the `attr` method and getting attributes on a tag. You may also use the `:exists` and `:delete` adverbs.

### method hash

```
method hash(DOM::Tiny:D:) returns Hash

```

This is a synonym for `attr`, when it is called with no arguments.

### method all-text

```
method all-text(DOM::Tiny:D: Bool :$trim = False) returns Str

```

Pulls the text from all nodes under the current item in the DOM tree and returns it as a string. This is identical to calling `text` with the `:recurse` flag set to `True`. The `:trim` flag may be set to true, which will cause all trimmable space to be clipped from the returned text (i.e., text not in an RCDATA tag like `title` or `textarea` and not in a `pre` tag).

### method attr

```
multi method attr(DOM::Tiny:D:) returns Hash:D
multi method attr(DOM::Tiny:D: Str:D $name) returns Str
multi method attr(DOM::Tiny:D: Str:D $name, Str() $value) returns DOM::Tiny:D
multi method attr(DOM::Tiny:D: Str:D $name, Nil) returns DOM::Tiny:D
multi method attr(DOM::Tiny:D: *%values) returns DOM::Tiny:D

```

The `attr` multi-method provides a getter/setter for attributes on the current tag. If the current node is not a tag, this is basically a no-op and will silently do nothing.

With no arguments, the method returns the attributes of the tag as a <Hash>.

With a single string argument, it returns the value of the named attribute or Nil.

With two string arguments, it will set the value of the named attribute and return the current node.

With a string argument and a `Nil`, it will delete the attribute and return the current node.

Given one or more named arguments, the named values will be set to the given values and the current node will be returned.

### method content

```
multi method content(DOM::Tiny:D:) returns Str:D
multi method content(DOM::Tiny:D: DOM::Tiny:D $tree) returns DOM::Tiny:D
multi method content(DOM::Tiny:D: Str() $ml, Bool :$xml = $!xml) returns DOM::Tiny:D

```

This multi-method works with the content of the node, something like `innerHTML` in the standard DOM.

Given no arguments, it returns the markup within the element rendered to a string. If the node is empty or has no markup, it will return an empty string.

Given a DOM::Tiny, the tree within that object will replace the content of the current node. If the current node cannot have children, then this is a no-op and will silently do nothing. This returns the current node.

Given a string, the string will be parsed into HTML or XML (based upon the value of the `:xml` named argument, which defaults to the setting for the current node), and the generated node tree will be used to replace the content of the current node. The current node is returned.

### method namespace

```
method namespace(DOM::Tiny:D:) returns Str

```

Returns the namespace URI of the current tag or Str if it has no namespace.

Returns Nil in all other cases (i.e., the current node is not a tag).

### method tag

```
multi method tag(DOM::Tiny:D:) returns Str
multi method tag(DOM::Tiny:D: Str:D $tag) returns DOM::Tiny:D

```

If the current node is a tag, both versions of this multi-method are no-ops that silently do nothing.

If no arguments are passed, the name of the tag is returned.

If a single string is passed, the name of the tag is changed to the given string and the current node is returned.

### method text

```
method text(DOM::Tiny:D: Bool :$trim = False, Bool :$recurse = False) returns Str

```

This returns the text content of the current node. For a text node, this returns the text of the node itself. For a tag or the root, this will return the text of all of the immediate text node children of the current node concatenated together.

If the argument named `:recurse` is passed, this method will return the text of all descendants rather than just the immediate children. This is the same as calling `all-text`.

If the argument named `:trim` is passed, this method will compress all breaking space into single spaces while concatenating all the text together.

### method type

```
method type(DOM::Tiny:D:) returns Node:U

```

This method returns the type of node that is wrapped within the current DOM::Tiny object. This will be one of the following types:

Root The root node of the tree.

Tag Markup tag nodes within the tree.

Text A regular text node.

CDATA A CDATA text node.

Comment A comment node.

Doctype A DOCTYPE tag element.

PI An XML processing instruction. This is also used to represent the XML declaration even though it is technically not a PI.

Raw A special raw text node, used to represent the text inside of script and style tags.

In addition to these types, you may also want to make use of the following roles, which help group the node types together:

Node All nodes, including the root implement this role.

DocumentNode All nodes that have a parent have this role, i.e., all but the root.

HasChildren Only the nodes that have children have this role, so just Tag and Root.

TextNode All nodes that contain text have this role. This includes Text, CDATA, and Raw.

Each of these classes and roles are exported by `DOM::Tiny` by default. If you prevent these from being exported, you will need to use their full name, which are each prefixed with `DOM::Tiny::HTML::`. For example, `Tag` has the full name `DOM::Tiny::HTML::Tag` and `TextNode` as the full name `DOM::Tiny::HTML::TextNode`.

### method val

```
method val(DOM::Tiny:D) returns Str

```

Returns the value of the tag. Returns `Nil` if the current tag has no notion of value or if the current node is not a tag.

Value is computed as follows, based on the tag name:

* * **option**: If the option tag has a `value` attribute, that is the option's value. Otherwise, the option's text is used.
* * **input**: The `value` attribute is used.
* * **button**: The `value` attribute is used.
* * **textarea**: The text content of the tag is used as the value.
* * **select**: The value of the currently selected option is used. If no option is marked as selected, the select tag has no value. If the select tag has the `multiple` attribute set, then this returns all the selected values.
* * Anything else will return `Nil` for the value.

## Tree Navigation

### method postcircumfix:<[]>

```
method postcircumfix:<[]>(DOM::Tiny:D: Int:D $i) is rw

```

The `.[]` can be used in place of `child-nodes` to retrieve children of the current root or tag from the DOM. The `:exists` and `:delete` adverbs also work.

### method list

```
method list(DOM::Tiny:D:) returns List

```

This is a synonym for `child-nodes`.

### method ancestors

```
method ancestors(DOM::Tiny:D: Str $selector?) returns Seq

```

Returns a sequence of ancestors to the current object as `DOM::Tiny` objects. This will return an empty sequence for the root or any node that no longer has a parent (such as may be the case for a recently removed node).

### method child-nodes

```
method child-nodes(DOM::Tiny:D: Bool :$tags-only = False)

```

If the current node has children (i.e., a tag or root), this method returns all of the children. If the `:tags-only` flag is set, it returns only the children that are tags.

If the current node has no children or is not able to have children, an empty list will be returned.

### method children

```
method children(DOM::Tiny:D: Str $selector?)

```

If the current node has children, this method returns only the tags that are children of the current node. The `$selector` may be set to a CSS selector to filter the children returned. Only those matching the selector will be returned.

If the current node has no children or is not able to have children, an empty list will be returned.

### method descendant-nodes

```
method descendant-nodes(DOM::Tiny:D:)

```

Returns all the descendants of the current node or an empty list if none or the node cannot have descendants. They are returned in depth-first order.

### method following

```
method following(DOM::Tiny:D: Str $selector?)

```

Returns all sibling tags of the current node that come after the current node.

### method following-nodes

```
method following-nodes(DOM::Tiny:D:)

```

Returns all sibling nodes of the current node that come after the current node.

### method next

```
method next(DOM::Tiny:D:) returns DOM::Tiny

```

Returns the next sibling tag of the current node. If there is no such sibling, it returns `Nil`.

### method next-node

```
method next-node(DOM::Tiny:D:) returns DOM::Tiny

```

Returns the next sibling node of the current node. If there is no such sibling, it returns `Nil`.

### method parent

```
method parent(DOM::Tiny:D:) returns DOM::Tiny

```

Returns the parent of the current node. If the current node is the root, this method returns `Nil` instead.

### method preceding

```
method preceding(DOM::Tiny:D: Str $selector?)

```

Retursn all siblings of the current node that are tags that come before the current node. A `$selector` may be given to filter the returned tags.

### method preceding-nodes

```
method preceding-nodes(DOM::Tiny:D:)

```

Returns all siblings nodes of the current node that precede the current node.

### method previous

```
method previous(DOM::Tiny:D:) returns DOM::Tiny

```

Returns the previous sibling tag of the current node. If there is no such sibling, it returns `Nil`.

### method previous-node

```
method previous-node(DOM::Tiny:D:) returns DOM::Tiny

```

Returns the previous sibling node of the current node. If there is no such sibling, it returns `Nil`.

### method root

```
method root(DOM::Tiny:D:) returns DOM::Tiny:D

```

Returns the root node of the tree.

## Tree Modification

### method append

```
method append(DOM::Tiny:D: Str() $ml, Bool :$xml = $!xml) returns DOM::Tiny:D

```

Appends the given markup content immediately after the current node. The `:xml` flag may be set to determine whether the given markup should be parsed as XML or HTML (with the default being whatever the current document is being treated as).

If the current node is the root (i.e., `$dom.type ~~ Root`), this operation is a no-op. It will silently do nothing.

Returns the current node.

### method append-content

```
method append-content(DOM::Tiny:D: Str() $ml, Bool :$xml = $!xml) returns DOM::Tiny:D

```

If this is the root or a tag (i.e., `$dom.type ~~ Root|Tag`), the given markup will be parsed and appended to the end of the root's or tag's children. If this is a text node (i.e., `$dom.type ~~ TextNode`), then the markup will be appended to the text node parent's children. Otherwise this is a no-op and will silently do nothing.

The `:xml` flag may be used to specify the format for the markup being parsed, defaulting to the setting for the current document.

Returns the node whose children have been modified.

### method prepend

```
method prepend(DOM::Tiny:D: Str() $ml, Bool :$xml = $!xml) returns DOM::Tiny:D

```

Appends the given markup content immediately before the current node. The `:xml` flag may be set to tell the parser to parse in XML mode or not (with the default being whatever is set for the current node).

If the current node is the root, this operation is a no-op and will silently do nothing.

This method will return the current node.

### method prepend-content

```
method prepend-content(DOM::Tiny:D: Str() $ml, Bool :$xml = $!xml) returns DOM::Tiny:D

```

Appends the given markup content at the beginning of the current node's children, if it is the root or a tag. (This is a no-op that silently does nothing unless the current node is the root or a tag.) The `:xml` flag sets whether to parse the `$ml` as XML or not, with the default being the xml mode flag set on the current node.

This method returns the current node.

### method remove

```
method remove(DOM::Tiny:D:) returns DOM::Tiny:D

```

Removes the current node from the tree and returns the parent node. If this node is the root, then the tree is emptied and the current node (i.e., the root) is returned.

### method replace

```
method replace(DOM::Tiny:D: DOM::Tiny:D $tree) returns DOM::Tiny:D
method replace(DOM::Tiny:D: Str() $ml) returns DOM::Tiny:D

```

The current node is replaced with the tree or markup given.

If the current node is the root, the current node is returned. Otherwise, the original parent of this node, which has been replaced with the new tree, is returned.

### method strip

```
method strip(DOM::Tiny:D:) returns DOM::Tiny:D

```

If the current node is a tag, the tag is removed from the tree and its content moved up into the current node's original parent. This will then return the original node's parent.

If the current node is anything else, this is a no-op that will silently do nothing and return the current node.

### method wrap

```
method wrap(DOM::Tiny:D: Str:D $ml, Bool :$xml = $!xml) returns DOM::Tiny:D

```

The given markup in `$ml` is parsed according to the format given by the `:xml` flag (defaulting to whatever the `xml` setting is for the current node). The current node is put within the innermost tag of the given markup. The current node is returned.

This is a no-op and will silently do nothing if the current node is the root.

### method wrap-content

```
method wrap-content(DOM::Tiny:D: Str:D $ml, Bool :$xml = $!xml) returns DOM::Tiny:D

```

This is a no-op and will silently do nothing unless the current node is the root or a tag.

The given markup in `$ml` is parsed. The parsing proceeds as XML if the `:xml` flag is set or HTML otherwise (with the default being whatever the `xml` flag is set to on the current node). The content of the current node is then placed within the innermost tag of the parsed markup and that parsed markup replaces the content of the current node.

# CAVEATS

This software is beta quality. It has been ported from a mature code base and survived many uses, but it has still only had a small number of bugs reported and fixed. It has a large test suite, but much of that has been ported from the Perl 5 module and is not necessarily specific to the kinds of bugs this port has. There has also been very little done to optimize the code or even to check to make sure it performs well in how it utilizes CPU and memory.

As of the v0.5.0, this project is committed to the following signals regarding changes to this software in the future:

* The major version number ("1" in "1.2.3") will be incremented whenever a documented feature changes in a way that is not backwards compatible.
* The minor version number ("2" in "1.2.3") will be incremented whenever new features or added or any backwards compatible change is made to an undocumented feature or some other significant change is made to the project.
* The patch number ("3" in "1.2.3") will be incremented whenever any other change is made (e.g., documentation, testing, minor bug fixes, etc.)

Semantic versioning is not a perfect system as it is not always crystal clear what distinguishes "bug fix" from "new feature" or "backwards compatible change" until after the fact, but I will try to do my best.

Any change thought to break backwards compatibility will be tagged with "BREAKING CHANGE" in `Changes`.

# AUTHOR AND COPYRIGHT

Copyright 2008-2016 Sebastian Riedel and others.

Copyright 2016 Andrew Sterling Hanenkamp for the port to Perl 6.

This is free software, licensed under:

The Artistic License 2.0 (GPL Compatible)


## parent.md
parent

Combined from primary sources listed below.

# [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_method_parent "direct link")

See primary documentation
[in context](/type/IO/Path#method_parent)
for **method parent**.

```raku
multi method parent(IO::Path:D:)
multi method parent(IO::Path:D: UInt:D $level)
```

Returns the parent path of the invocant. Note that no actual filesystem access is made, so the returned parent is physical and not the logical parent of symlinked directories.

```raku
'/etc/foo'.IO.parent.say; # OUTPUT: «"/etc".IO␤»
'/etc/..' .IO.parent.say; # OUTPUT: «"/etc".IO␤»
'/etc/../'.IO.parent.say; # OUTPUT: «"/etc".IO␤»
'./'      .IO.parent.say; # OUTPUT: «"..".IO␤»
'foo'     .IO.parent.say; # OUTPUT: «".".IO␤»
'/'       .IO.parent.say; # OUTPUT: «"/".IO␤»
IO::Path::Win32.new('C:/').parent.say; # OUTPUT: «"C:/".IO␤»
```

If `$level` is specified, the call is equivalent to calling `.parent()` `$level` times:

```raku
say "/etc/foo".IO.parent(2) eqv "/etc/foo".IO.parent.parent; # OUTPUT: «True␤»

```

# [In X::Inheritance::Unsupported](#___top "go to top of document")[§](#(X::Inheritance::Unsupported)_method_parent "direct link")

See primary documentation
[in context](/type/X/Inheritance/Unsupported#method_parent)
for **method parent**.

The type object that the child tried to inherit from.


## dist_github-retupmoca-Net-AMQP.md
# Net::AMQP

Net::AMQP - a AMQP 0.9.1 client library (built and tested against RabbitMQ)

## Synopsis

First start a consumer that will print the received messages:

```
use v6;

use Net::AMQP;

my $n = Net::AMQP.new;

my $connection = $n.connect.result;

say 'connected';

my $channel = $n.open-channel(1).result;

say 'channel';

my $q = $channel.declare-queue('echo').result;

say 'queue';

$q.message-supply.tap({
    say 'Got message!';
    say $_.body.decode;
    if $_.body.decode eq 'exit' {
        $n.close("", "");
    }
});

say 'set up';

$q.consume;

say 'consuming';

await $connection;

```

Then run the script that will send a message sent on the command line,

```

use v6;

use Net::AMQP;

sub MAIN($message) {
    my $n = Net::AMQP.new;

    await $n.connect;

    my $channel = $n.open-channel(1).result;

    $channel.exchange.result.publish(routing-key => "echo", body => $message.encode);

    await $n.close("", "");
}

```

## Description

This is an async network library. Any -supply method returns a supply, and every
other method will return a promise (with the exception of the initial Net::AMQP.new
call).

## Methods

### Net::AMQP

* new
* close
* open-channel
* connect

### Net::AMQP::Channel

* close
* declare-exchange
* exchange
* declare-queue
* queue
* qos
* flow
* recover

### Net::AMQP::Exchange

* delete
* publish
* return-supply

  NYI
* ack-supply

  NYI

### Net::AMQP::Queue

* bind
* unbind
* purge
* delete
* consume
* cancel

  NYI
* message-supply
* recover

  NYI

## Installation

In order for this to work you will need to have access to an AMQP
broker, the tests will, by default, use a broker on `localhost`
with the default credentials. The tests will be skipped if no
server is available,

If you want to test against other than `localhost` or with different credentials then you can set the environment variables

```
    * AMQP_HOST
    * AMQP_PORT
    * AMQP_LOGIN
    * AMQP_PASSWORD
    * AMQP_VHOST

```

as appropriate before running the tests.

Assuming you have a working installation of Rakudo then you will be able to install this with *zef* :

```
zef install Net::AMQP

# or if you have a local copy

zef install .

```


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

# NAME

Data::StaticTable - a static memory structure in Raku

# INTRODUCTION

A StaticTable allows you to handle bidimensional data in a more natural way

Some features:

* Rows starts at 1 (`Data::StaticTable::Position` is the datatype used to reference row numbers)
* Columns have header names
* Any column can work as an index

If the number of elements provided does not suffice to form a square or a rectangle, filler cells will be added as filler (you can define what goes in these filler cells as well).

The module provides two classes: `StaticTable` and `StaticTable::Query`.

A StaticTable can be populated, but it can not be modified later. To perform searchs and create/store indexes, a Query object is provided. You can add indexes per column, and perform searches (grep) later. If an index exists, it will be used.

You can get data by rows, columns, and create subsets by taking some rows from an existing StaticTable.

# TYPES

## Data::StaticTable::Position

Basically, an integer greater than 0. Used to indicate a row position in the table. A StaticTable do not have rows on index 0.

# OPERATORS

## eqv

Compares the contents (header and data) of two StaticTable objects. Returns `False` as soon as any difference is detected, and `True` if it finds that everything is equal.

```
say '$t1 and $t2 are ' ~ ($t1 eqv $t2) ?? 'equal' !! 'different';

```

# Data::StaticTable CLASS

## Positional features

### Brackets []

You can use [n] to get the full Nth row, in the way of a hash of **'Column name'** => data

So, for example

```
$t[1]

```

Could return a hash like

```
{Column1 => 10, Column2 => 200.4, Column3 => 450}

```

And a call like

```
$t[10]<Column3>

```

would refer to the data in Row 10, with the heading Column3

### The `ci` hash

On construction, a public hash called `ci` (short for **c**olumn **i**ndex) is created. If for some reason, you need to refer the columns by number instead of name, this hash contains the column numbers as keys, and the heading name as values.

if your column number **2** has the name "Weight", you can read the cell in the third row of that column like this:

```
my $val1 = $t.cell('Weight', 3);
my $val2 = $t[3]<Weight>;

```

Or by using the `ci` hash

```
my $val1 = $t.cell($t.ci<2>, 3);
my $val2 = $t[3]{$t.ci<2>};

```

## method new

Depending on how your source data is organized, you can use the 2 **flat array** constructors or a **rowset** constructor.

**Flat array** allows you to pass a long one dimensional array and order it in rows and columns, by specifiying a header. You can pass an array of string to specify the column names, or just a number of columns if you don't care about the column names.

**Rowset** works when your data is already bidimensional, and it can include a first row as header. In the case that your rows contains a hash, you can tell the constructor, and it will take the hash keys to create a header with the appropiate column names. In this case, any row that does not contain a hash will be discarded (you have the option to recover the discarded data).

### The flat array constructor

```
my $t1 = StaticTable.new( 3 , (1 .. 15) );
my $t2 = StaticTable.new(
  <Column1 Column2 Column3> ,
  (
  1, 2, 3,
  4, 5, 6,
  7, 8, 9,
  10,11,12
  13,14,15
  )
);

```

This will create a spreadsheet-like table, with numbered rows and labeled columns.

In the case of `$t1`, since the first parameter is a number, it will have columns named automatically, as `A`, `B`, `C`... etc.

`$t2` has an array as the first parameter. So it will have three columns labeled `Column1`, `Column2` and `Column3`.

You just need to provide an array to fill the table. The rows and columns will be automatically cut and filled in a number of rows.

If you do not provide enough data to fill the last row, empty cells will be appended.

If you already have your data ordered in an array of arrays, use the rowset constructor described below.

### The rowset constructor

You can also create a StaticTable from an array, with each element representing a row. The StaticTable will acommodate the values as best as possible, adding empty values or discarding values that go beyond the boundaries, or data that is not prepared appropiately

This constructor can be called like this, using an Array of Arrays

```
my $t = StaticTable.new(
  (1,2,3),
  (4,5,6),
  (7,8,9)
);

```

For a Array of Hashes, you can call it like this

```
my $t = StaticTable.new(
 [
  { name => 'Eggplant', color => 'aubergine', type => 'vegetal' },
  { name => 'Egg', color => ('white', 'beige'), type => 'animal' },
  { name => 'Banana', color => 'yellow', type => 'fruit' },
  { name => 'Avocado', color => 'green', type => 'fruit',  class => 'Hass' }
 ]
);

```

*(Note the use of brackets, we needed to explicitly pass an Array of Hashes)*

There is a set of named parameters usable in this constructor

```
my $t = StaticTable.new(@ArrayOfArrays):data-has-header

```

This will use the first row as header. Any value that falls outside the column boundaries determined by the header will be discarded in each row.

```
my $t = StaticTable.new(@ArrayOfHashes):set-of-hashes

```

This will consider each row as a hash, and will create columns for each key found. The most populated will be the first columns. Any row that is not a hash will be discarded

### Recovering discarded data

In some situations, some data can be rejected from your original array passed to the constructor. This will happen in two cases, using the rowset constructor:

* You specified `:data-has-header` but there are rows longer that the length of the header. So, if your first row had 4 elements, any row with more that 4 elements will be cut and the extra elements will be rejected
* You specified `:set-of-hashes` but there are rows that does not contain hashes. All these rows will be rejected too.

For recovering discarded data from an Array of Arrays:

```
my %rejected;
my $tAoA = StaticTable.new(
  @ArrayOfArrays, rejected-data => %rejected # <--- Note, rejected is a hash
):data-has-header

```

In this case, `%rejected` is a hash where the key is the row from where the data was discarded, pointing to an array of the elements discarded in that row.

For recovering discarded data from an Array of Hashes:

```
my @rejected;
my $tAoH = StaticTable.new(
  @ArrayOfHashes, rejected-data => @rejected # <--- rejected is an array
):set-of-hashes

```

In this case, `@rejected` will have a list of all the rejected rows.

### The `filler` value

There is another named parameter, called `filler`. This is used to complete rows that need more cells, so the table has every row with the same number of elements.

By default, it uses `Nil`.

Example:

```
my $t = Data::StaticTable.new(
  <A B C>,
  (1,2,3,
   4,5,6,
   7),     # 2 last cells will be fillers, so the 3rd row is complete
  filler => 'N/A'
);

print $t[3]<C>; #This will print N/A

```

## method raku

Returns a representation of the StaticTable. Can be used for serialization.

## method clone

Returns a newly created StaticTable with the same attributes. It does **not** copy attributes to clone. Instead, runs the constructor again.

## method display

Shows a 'visual' representation of the contents of the StaticTable. Used for debugging, **not for serialization**.

It would look like this:

```
A   B   C
⋯  ⋯  ⋯
[1] [2] [3]
[4] [5] [6]
[7] [8] [9]

```

However, you could save the output of this method to a tab-separated csv file.

## method cell(Str $column-heading, Position $row)

Retrieves the content of a cell.

## method column(Str $column-heading)

Retrieves the content of a column like a regular `List`.

## method row(Position $row)

Retrieves the content of a row as a regular `List`.

## method shaped-array

Retrieves the content of the table as a multiple dimension array.

## method elems

Retrieves the number of cells in the table

## method generate-index(Str $heading)

Generate a `Hash`, where the key is the value of the cell, and the value is a list of row numbers (of type `Data::StaticTable::Position`).

## method take(@rownums where .all ~~ Position)

Generate a new `StaticTable`, using a list of row numbers (using the type `Data::StaticTable::Position`)

The order of the rows will be kept, and you can consider repeated rows. You can use `.unique` and `.sort` on the row numbers list. A sorted, unique list will make the construction of the new table **faster**. Consider this is you want to use a lot of rownums.

```
#-- Order and repeated rows will be kept
my $new-t1 = $t.take(@list);
#-- Consider this if @list is big, not sorted and has repeated elements
my $new-t2 = $t.take(@list.uniq.sort)

=end raku

You can combine this with C<generate-index>

=begin code :lang<raku>

my %i-Status = $t.generate-index("Status");
# We want a new table with rows where Status = "Open"
my $t-open = $t.take(%i-Status<Open>);
# We want another where Status = "Awaiting feedback"
my $t-waiting = $t.take(%i-Status{'Awaiting feedback'});

```

Also works with the `.grep` method from the `StaticTable::Query` object. This allows to you do more complex searches in the columns.

An identical, but slurpy version of this method is also available for convenience.

# Data::StaticTable::Query CLASS

Since StaticTable is immutable, a helper class to perform searches is provided. It can contain generated indexes. If an index is provided, it will be used whenever a search is performed.

## Associative features

You can use hash-like keys, to get a specific index for a column

```
$Q1<Column1>
$Q1{'Column1'}

```

Both can get you the index (the same you could get by using `generate-index` in a `StaticTable`).

## method new(Data::StaticTable $T, \*@to-index)

You need to specify an existing `StaticTable` to create this object. Optionally you can pass a list with all the column names you want to consider as indexes.

Examples:

```
my $q1 = Data::StaticTable::Query.new($t);            #-- No index at construction
my $q2 = Data::StaticTable::Query.new($t, 'Address'); #-- Indexing column 'Address'
my $q3 = Data::StaticTable::Query.new($t, $t.header); #-- Indexing all columns

```

If you don't pass any column names in the constructor, you can always use the method `add-index` later

## method raku

Returns a representation of the StaticTable::Query object. Can be used for serialization.

**Note:** This value will contain *the complete* StaticTable for this index.

## method keys

Returns the name of the columns indexed.

## method values

Returns the values indexed.

## method k

Returns the hash of the same indexes in the `Query` object.

## method grep(Mu $matcher where { -> Regex {}($\_); True }, Str $heading, Bool :$h = True, Bool :$n = False, Bool :$r = False, Bool :$nr = False, Bool :$nh = False)

Allows to use grep over a column. Depending on the flags used, returns the resulting row information for all that rows where there are matches. You can not only use a regxep, but a `Junction` of `Regex` elements.

Examples of Regexp and Junctions:

```
# Get the rownumbers where the column 'A' contains '9'
my Data::StaticTable::Position @rs1 = $q.grep(rx/9/, "A"):n;
# Get the rownumbers where the column 'A' contains 'n' and 'e'
my Data::StaticTable::Position @rs2 = $q.grep(all(rx/n/, rx/e/), "A"):n;

```

When you use the flag `:n`, you can use these results later with the method `take`

### Flags

Similar to the default grep method, this contains flags that allows you to receive the information in various ways.

Consider this StaticTable and its Query:

```
my $t = Data::StaticTable.new(
  <Countries  Import      Tons>,
  (
    'US PE CL', 'Copper',    100, # Row 1
    'US RU',    'Alcohol',   50,  # Row 2
    'IL UK',    'Processor', 12,  # Row 3
    'UK',       'Tuxedo',    1,   # Row 4
    'JP CN',    'Tuna',      10,  # Row 5
    'US RU CN', 'Uranium',   0.01 # Row 6
  )
);
my $q = Data::StaticTable::Query.new($t)

```

* :n

Returns only the row numbers.

This is very useful to combine with the `take` method.

```
my @a = $q.grep(all(rx/US/, rx/RU/), 'Countries'):n;
# Result: The array (2, 6)

```

* :r

Returns the rows, just data, no headers

```
my @a = $q.grep(all(rx/US/, rx/RU/), 'Countries'):r;
# Result: The array
# [
#       ("US RU", "Alcohol", 50),
#       ("US RU CN", "Uranium", 0.01)
# ]

```

* :h

Returns the rows as a hash with header information

This is the default mode. You don't need to use the `:h` flag to get this result

```
my @a1 = $q.grep(all(rx/US/, rx/RU/), 'Countries'):h; # :h is the default
my @a2 = $q.grep(all(rx/US/, rx/RU/), 'Countries');   # @a1 and @a2 are identical
# Result: The array
# [
#      {:Countries("US RU"), :Import("Alcohol"), :Tons(50)},
#      {:Countries("US RU CN"), :Import("Uranium"), :Tons(0.01)}
# ]

```

* :nr

Like `:r` but in a hash, with the row number as the key

```
my %h = $q.grep(all(rx/US/, rx/RU/), 'Countries'):nr;
# Result: The hash
# {
#    "2" => $("US RU", "Alcohol", 50),
#    "6" => $("US RU CN", "Uranium", 0.01)
# }

```

* :nh

Like `:h` but in a hash, with the row number as the key

```
my %h = $q.grep(all(rx/US/, rx/RU/), 'Countries'):nh;
# Result: The hash
# {
#    "2" => ${:Countries("US RU"), :Import("Alcohol"), :Tons(50)},
#    "6" => ${:Countries("US RU CN"), :Import("Uranium"), :Tons(0.01)}
# }

```

## method add-index($column-heading)

Creates a new index, and it will return a score indicating the index quality. Values of 1, or very close to zero are the less ideals.

Nevertheless, even an index with a score 1 will help.

Example:

```
my $q1 = Data::StaticTable::Query.new($t); #-- Creates index and ...
$q1.add-index('Address');                  #-- indexes the column 'Address'

```

When an index is created, it is used automatically in any further `grep` calls.

# AUTHOR

shinobi

# COPYRIGHT AND LICENSE

Copyright 2018 - 2019 shinobi

Copyright 2024 Raku Community

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


## printf.md
printf

Combined from primary sources listed below.

# [In IO::Handle](#___top "go to top of document")[§](#(IO::Handle)_method_printf "direct link")

See primary documentation
[in context](/type/IO/Handle#method_printf)
for **method printf**.

```raku
multi method printf(IO::Handle:D: Cool $format, *@args)
```

Formats a string based on the given format and arguments and `.print`s the result into the filehandle. See [sprintf](/routine/sprintf) for details on acceptable format directives.

Attempting to call this method when the handle is [in binary mode](/type/IO/Handle#method_encoding) will result in [`X::IO::BinaryMode`](/type/X/IO/BinaryMode) exception being thrown.

```raku
my $fh = open 'path/to/file', :w;
$fh.printf: "The value is %d\n", 32;
$fh.close;

```

# [In Independent routines](#___top "go to top of document")[§](#(Independent_routines)_routine_printf "direct link")

See primary documentation
[in context](/type/independent-routines#routine_printf)
for **routine printf**.

```raku
multi printf(Cool:D $format, *@args)
```

Produces output according to a format. The format used is the invocant (if called in method form) or the first argument (if called as a routine). The rest of the arguments will be substituted in the format following the format conventions. See [sprintf](/routine/sprintf) for details on acceptable format directives.

```raku
"%s is %s".printf("þor", "mighty");    # OUTPUT: «þor is mighty»
printf( "%s is %s", "þor", "mighty");  # OUTPUT: «þor is mighty»
```

On [`Junction`](/type/Junction)s, it will also autothread, without a guaranteed order.

```raku
printf( "%.2f ", ⅓ | ¼ | ¾ ); # OUTPUT: «0.33 0.25 0.75 »
```

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

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

```raku
method printf(*@args)
```

Uses the object, as long as it is a [format string](/type/independent-routines#Directives), to format and print the arguments

```raku
"%.8f".printf(now - now ); # OUTPUT: «-0.00004118»

```


## dist_zef-guifa-Intl-Regex-CharClass.md
# Intl::Regex::CharClass

This module aims to provide localized variants of built in character classes.
It currently only supports the `<alpha>` class inside of grammars, but support for other classes and outside of grammars.
The API is still experimental, so do not (yet) depend on it.

## Use

It's as simple as importing the module and adding in the trait `is localized`.

```
use Intl::Regex::CharClass

grammar Word is localized('en') {
    token TOP { <alpha>+ }
}
Word.parse('party');  # party
Word.parse('piñata'); # [no match]

grammar Palabra is localized('es') {
    token TOP { <alpha>+ }
}
Palabra.parse('piñata'); # piñata
Palabra.parse('fête');   # [no match]

```

If you do not specify a language, it will by default localized to the system language as defined by `User::Language`.
If for some reason that is not available or detectable, it will default to `en` (English).

### Version history

* **v0.1.0**
  First release with support for `<alpha>`


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

# NAME

Raku port of Perl's reset() built-in

# SYNOPSIS

```
use P5reset;

reset("a");   # reset all "our" variables starting with "a"

reset("a-z"); # reset all "our" variables starting with lowercase letter

reset;        # does not reset any variables

```

# DESCRIPTION

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

# ORIGINAL PERL DOCUMENTATION

```
reset EXPR
reset   Generally used in a "continue" block at the end of a loop to clear
        variables and reset "??" searches so that they work again. The
        expression is interpreted as a list of single characters (hyphens
        allowed for ranges). All variables and arrays beginning with one
        of those letters are reset to their pristine state. If the
        expression is omitted, one-match searches ("?pattern?") are reset
        to match again. Only resets variables or searches in the current
        package. Always returns 1. Examples:

            reset 'X';      # reset all X variables
            reset 'a-z';    # reset lower case variables
            reset;          # just reset ?one-time? searches

        Resetting "A-Z" is not recommended because you'll wipe out your
        @ARGV and @INC arrays and your %ENV hash. Resets only package
        variables; lexical variables are unaffected, but they clean
        themselves up on scope exit anyway, so you'll probably want to use
        them instead. See "my".

```

# PORTING CAVEATS

Since Raku doesn't have the concept of `?one time searches?`, the no-argument form of `reset` will not reset any variables at all.

# 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/P5reset> . 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-lizmat-path-utils.md
[![Actions Status](https://github.com/lizmat/path-utils/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/path-utils/actions) [![Actions Status](https://github.com/lizmat/path-utils/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/path-utils/actions) [![Actions Status](https://github.com/lizmat/path-utils/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/path-utils/actions)

# NAME

path-utils - low-level path introspection utility functions

# SYNOPSIS

```
use path-utils;  # export all subs

use path-utils <path-exists>;  # only export sub path-exists

say path-exists($filename);  0 or 1

```

# DESCRIPTION

path-utils provides a number of low-level path introspection utility functions for those cases where you're interested in performance, rather than functionality.

All subroutines take a (native) string as the only argument.

Note that these functions only return native `int` and native `num` values, which can be used in conditions without any problems, just don't expect them to be upgraded to `Bool` values.

Also note that all functions (except `path-exists`) expect the path to exist. An exception will be thrown if the path does not exist. The reason for this is that in situations where you are already sure a path exists, there is no point checking for its existence again if you e.g. would like to know its size.

# SELECTIVE IMPORTING

```
use path-utils <path-exists>;  # only export sub path-exists

```

By default all utility functions are exported. But you can limit this to the functions you actually need by specifying the names in the `use` statement.

To prevent name collisions and/or import any subroutine with a more memorable name, one can use the "original-name:known-as" syntax. A semi-colon in a specified string indicates the name by which the subroutine is known in this distribution, followed by the name with which it will be known in the lexical context in which the `use` command is executed.

```
use path-utils <path-exists:alive>;  # export "path-exists" as "alive"

say alive "/etc/passwd";  # 1 if on Unixy, 0 on Windows

```

# EXPORTED SUBROUTINES

In alphabetical order:

## path-accessed

Returns number of seconds since epoch as a `num` when path was last accessed.

## path-blocks

Returns the number of filesystem blocks allocated for this path.

## path-block-size

Returns the preferred I/O size in bytes for interacting wuth the path.

## path-created

Returns number of seconds since epoch as a `num` when path was created.

## path-device-number

Returns the device number of the filesystem on which the path resides.

## path-exists

Returns 1 if paths exists, 0 if not.

## path-filesize

Returns the size of the path in bytes.

## path-gid

Returns the numeric group id of the path.

## path-git-repo

Returns the path of the Git repository associated with the **absolute** path given, or returns the empty string if the path is not part inside a Git repository. Note that this not mean that the file is actually part of that Git repository: it merely indicates that the returned path returned `True` with `path-is-git-repo`.

## path-hard-links

Returns the number of hard links to the path.

## path-has-setgid

The path has the SETGID bit set in its attributes.

## path-inode

Returns the inode of the path.

## path-is-device

Returns 1 if path is a device, 0 if not.

## path-is-directory

Returns 1 if path is a directory, 0 if not.

## path-is-empty

Returns 1 if the path has a filesize of 0.

## path-is-executable

Returns a non-zero integer value if path is executable by the current user.

## path-is-github-repo

Returns 1 if path appears to be the top directory in a GitHub repository (as recognized by having a `.github` directory in it).

## path-is-git-repo

Returns 1 if path appears to be the top directory in a Git repository (as recognized by having a <.git> directory in it).

## path-is-group-executable

Returns a non-zero integer value if path is executable by members of the group of the path.

## path-is-group-readable

Returns a non-zero integer value if path is readable by members of the group of the path.

## path-is-group-writable

Returns a non-zero integer value if path is writable by members of the group of the path.

## path-is-moarvm

Returns 1 if path is a `MoarVM` bytecode file (either from core, or from a precompiled module file), 0 if not.

## path-is-owned-by-user

Returns a non-zero integer value if path is owned by the current user.

## path-is-owned-by-group

Returns a non-zero integer value if path is owned by the group of the current user.

## path-is-owner-executable

Returns a non-zero integer value if path is executable by the owner of the path.

## path-is-owner-readable

Returns a non-zero integer value if path is readable by the owner of the path.

## path-is-owner-writable

Returns a non-zero integer value if path is writable by the owner of the path.

## path-is-pdf

Returns 1 if path looks a `PDF` file, judging by its magic number, 0 if not.

## path-is-readable

Returns a non-zero integer value if path is readable by the current user.

## path-is-regular-file

Returns 1 if path is a regular file, 0 if not.

## path-is-sticky

The path has the STICKY bit set in its attributes.

## path-is-symbolic-link

Returns 1 if path is a symbolic link, 0 if not.

## path-is-text

Returns 1 if path looks like it contains text, 0 if not.

## path-is-world-executable

Returns a non-zero integer value if path is executable by anybody.

## path-is-world-readable

Returns a non-zero integer value if path is readable by anybody.

## path-is-world-writable

Returns a non-zero integer value if path is writable by any body.

## path-is-writable

Returns a non-zero integer value if path is writable by the current user.

## path-meta-modified

Returns number of seconds since epoch as a `num` when the meta information of the path was last modified.

## path-mode

Returns the numeric unix-style mode.

## path-modified

Returns number of seconds since epoch as a `num` when path was last modified.

## path-uid

Returns the numeric user id of the path.

# AUTHOR

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

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

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!

# COPYRIGHT AND LICENSE

Copyright 2022, 2023, 2024, 2025 Elizabeth Mattijsen

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


## dist_zef-finanalyst-CWT-Repository-Hash.md
![github-tests-passing-badge](https://github.com/finanalyst/CWT-Repository-Hash/actions/workflows/test.yaml/badge.svg)

# Cro::WebApp::Template::Repository::Hash

> Using Cro templates in a Hash

## Table of Contents

[Introduction](#introduction)
[Usage](#usage)
[Dependencies](#dependencies)
[Differences from CWT documentation](#differences-from-cwt-documentation)
[sub templates-from-hash( %hash-of-templates )](#sub-templates-from-hash-hash-of-templates-)
[sub render-template( $template, $topic, :%parts, :build($)! )](#sub-render-template-template-topic-parts-build-)
[sub modify-template-hash( %templates )](#sub-modify-template-hash-templates-)
[sub wait-for-hash-template-completion](#sub-wait-for-hash-template-completion)

---

# Introduction

This module uses the Cro template language [Cro::WebApp::Template](https://cro.services/docs/reference/cro-webapp-template) (called **CWT** below) where the templates are in a Hash.

**CWT** is aimed at templates that exist as files in some directory / folder, whether on a server or in an online resource. Consequently, each template is contained in a single file. A collection of templates exists under a root directory. The directory may be on-line or local. This paradigm implies the request-response of a server hosted website, with the template used being dependent on the request.

In a Build context that is designed to be distributed via a CDN the structural HTML of a website is static. Consequently, all the templates needed for the structure are known before any incoming request. User interaction with the website is confined to `micro-service` interfaces, each of which have their own server request/responses.

The structural templates can therefore be collected before creating the HTML and can be placed in a Hash. This also allows for templates to use other templates in the Hash via the `<:use>` tag.

# Usage

```
    use v6.d;
    use Cro::WebApp::Template::Repository::Hash;
    # gather template strings
    my %temps = %(
       'format-b' => '<strong><.contents></strong>',
        'heading' => q:to/HEADING/ ,
            <:sub heading($level=1,:$close=False)>
            <?$close>/</?>h<$level></:>

            <<&heading(.level)> id="<.target>">
            <a href="#<.top>" class="u" title="go to top of document">
            <.text>
            </a>
            <<&heading(.level,:close)>>
            HEADING
    );
    # the following is required to create a Build repository, otherwise the
    # default Filesystem repository will be used.
    templates-from-hash %temps;
    # later
    my $parameters = %( :1level, :target<https://docs.raku.org>, :top<__TOP>,
        :text("This is a title") );
    say render-template('heading', $parameters, :hash);

```

# Dependencies

Uses Cro::WebApp::Template

# Differences from CWT documentation

## sub templates-from-hash( %hash-of-templates )

The sub must be called with each value of `%hash-of-templates` containing a valid crotmp template before using `render-template`.

## sub render-template( $template, $topic, :%parts, :build($)! )

`render-template` is used in the same way as documented **CWT**.

## sub modify-template-hash( %templates )

This sub can only be used after `templates-from-hash`, which creates a Build repository. It is NOP otherwise.

The values in %templates over-ride the value in the repository if it was set by `templates-from-hash` or adds to the repository if the key did not previously exist.

## sub wait-for-hash-template-completion

waits for all the compilation promises to stop returning Planned on a status call.

---

Rendered from README at 2022-07-15T22:10:55Z


## dist_github-ugexe-P6TCI.md
## Demonstrate Perl6 module testing on Travis-CI

### HOWTO

Just copy the .travis.yml file from this repo to yours and turn on testing for that repository on Travis-CI.org (toggle the appropriate slider on `https://travis-ci.org/profile/YOUR_GITHUB_USERNAME`)

### DESCRIPTION

Runs travis-ci tests using both supported backends using the most current Rakudo built from source. Rakudo Star is not used for continuous testing purposes as Rakudo changes far too often, and you would end up testing against month old changes. It will also submit test reports for your module to testers.perl6.org, and failures from modules that show up Rakudo commits can help the Rakudo developers see what new changes may have broke.

### TODO

######bin/p6tci

* Generate a .travis.yml in some location based on some arguments.

######Combined test run

* Option to use rakudobrew to test multiple `$ENV{BACKEND}` in one job. Current build times for JVM make this not always possible.


## dist_zef-l10n-L10N-FR.md
# NAME

L10N::FR - French localization of Raku

# SYNOPSIS

```
use L10N::FR;
dis "Hello World";

```

# DESCRIPTION

L10N::FR contains the logic to provide a French localization of the Raku Programming Language.

# AUTHORS

Lucien Grondin

# COPYRIGHT AND LICENSE

Copyright 2023 Raku Localization Team

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


## dist_zef-jonathanstowe-META6.md
# META6

Do things with Raku [META files](http://design.raku.org/S22.html#META6.json)

[![CI](https://github.com/jonathanstowe/META6/actions/workflows/main.yml/badge.svg)](https://github.com/jonathanstowe/META6/actions/workflows/main.yml)

## Synopsis

The below will generate the *META6.json* for this module.

```
use META6;

my $m = META6.new(   name        => 'META6',
                     version     => Version.new('0.0.1'),
                     auth        => 'github:jonathanstowe',
                     api         => '1.0',
                     description => 'Work with Raku META files',
                     raku-version   => Version.new('6.*'),
                     depends     => ['JSON::Class:ver<0.0.15+>', 'JSON::Name' ],
                     test-depends   => <Test JSON::Fast>,
                     tags        => <devel meta utils>,
                     authors     => ['Jonathan Stowe <jns+git@gellyfish.co.uk>'],
                     source-url  => 'https://github.com/jonathanstowe/META6.git',
                     support     => META6::Support.new(
                        source => 'https://github.com/jonathanstowe/META6.git'
                     ),
                     provides => {
                        META6 => 'lib/META6.pm',
                     },
                     license     => 'Artistic',
                     production  => False,
                     meta-version   => 1,

                 );

print $m.to-json;

my $m = META6.new(file => './META6.json');
$m<version description> = v0.0.2, 'Work with Raku META files even better';
say 'Modules in the distribution: ' ~ $m<provides>.keys.join(', ');
spurt('./META6.json', $m.to-json);

```

## Description

This provides a representation of the Raku [META
files](http://design.raku.org/S22.html#META6.json) specification -
the META file data can be read, created , parsed and written in a manner
that is conformant with the specification.

Where they are known about it also makes allowance for "customary"
usage in existing software (such as installers and so forth.)

The intent of this is allow the generation and testing of META files for
module authors, so it can provide meta-information whether the attributes
are mandatory as per the spec and where known the places that "customary"
attributes are used,

### to-json

See [JSON::Fast to-json()](https://github.com/timo/json_fast#to-json) for options. `sorted-keys`
is recommended if you intend to modify the same file multiple times.

## Installation

Assuming you have a working Rakudo installation you should be able to install this with *zef* :

```
# From the source directory

zef install .

# Remote installation

zef install META6

```

## Support

Suggestions/patches are welcomed via [github](https://github.com/jonathanstowe/META6)

I'm particulary interested in knowing about "customary" (i.e. non-spec)
fields that are being used in the wild and in what software so I can
add them if necessary.

## Licence

This free software.

Please see the <LICENCE> file in the distribution for the details.

© Jonathan Stowe 2015 - 2021


## dist_cpan-CTILMES-CroX-HTTP-Transform-GraphQL.md
# Perl 6 GraphQL Cro Helpers

Broke these out of the main GraphQL module. I'm still not happy with
them, but I'm using them so I need to put them somewhere for now..

I'll add tests and documentation at some point..

Copyright © 2017 United States Government as represented by the
Administrator of the National Aeronautics and Space Administration.
No copyright is claimed in the United States under Title 17,
U.S.Code. All Other Rights Reserved.


## but.md
but

Combined from primary sources listed below.

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

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

```raku
multi infix:<but>(Mu $obj1, Mu   $role) is assoc<non>
multi infix:<but>(Mu $obj1, Mu:D $obj2) is assoc<non>
```

Creates a copy of `$obj` with `$role` mixed in. Since `$obj` is not modified, `but` can be used to create immutable values with mixins.

If `$role` supplies exactly one attribute, an initializer can be passed in parentheses:

```raku
role Answerable {
    has $.answer;
}
my $ultimate-question = 'Life, the Universe and Everything' but Answerable(42);
say $ultimate-question;         # OUTPUT: «Life, the Universe and Everything␤»
say $ultimate-question.^name;   # OUTPUT: «Str+{Answerable}␤»
say $ultimate-question.answer;  # OUTPUT: «42␤»

```

Instead of a role, you can provide an instantiated object. In this case, the operator will create a role for you automatically. The role will contain a single method named the same as `$obj.^name` and that returns `$obj`:

```raku
my $forty-two = 42 but 'forty two';
say $forty-two+33;    # OUTPUT: «75␤»
say $forty-two.^name; # OUTPUT: «Int+{<anon|1>}␤»
say $forty-two.Str;   # OUTPUT: «forty two␤»

```

Calling `^name` shows that the variable is an [`Int`](/type/Int) with an anonymous object mixed in. However, that object is of type [`Str`](/type/Str), so the variable, through the mixin, is endowed with a method with that name, which is what we use in the last sentence.

We can also mixin classes, even created on the fly.

```raku
my $s = 12 but class Warbles { method hi { 'hello' } }.new;
say $s.Warbles.hi;    # OUTPUT: «hello␤»
say $s + 42;          # OUTPUT: «54␤»

```

To access the mixed-in class, as above, we use the class name as is shown in the second sentence. If methods of the same name are present already, the last mixed in role takes precedence. A list of methods can be provided in parentheses separated by comma. In this case conflicts will be reported at runtime.


## dist_zef-l10n-L10N-NL.md
# NAME

L10N::NL - Dutch localization of Raku

# SYNOPSIS

```
use L10N::NL;
zeg "Hello World";

```

# DESCRIPTION

L10N::NL contains the logic to provide a Dutch localization of the Raku Programming Language.

# AUTHORS

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

# COPYRIGHT AND LICENSE

Copyright 2023 Raku Localization Team

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


## allomorph.md
class Allomorph

Dual value number and string

```raku
class Allomorph is Str { }
```

The `Allomorph` class is a common parent class for Raku's dual value types: [`ComplexStr`](/type/ComplexStr), [`IntStr`](/type/IntStr), [`NumStr`](/type/NumStr), [`RatStr`](/type/RatStr).

The dual value types (often referred to as [allomorphs](/language/glossary#Allomorph)) allow for the representation of a value as both a string and a numeric type. Typically they will be created for you when the context is "stringy" but they can be determined to be numbers, such as in some [quoting constructs](/language/quoting):

```raku
my $c = <42+0i>;  say $c.^name; # OUTPUT: «ComplexStr␤»
my $i = <42>;     say $i.^name; # OUTPUT: «IntStr␤»
my $n = <42.1e0>; say $n.^name; # OUTPUT: «NumStr␤»
my $r = <42.1>;   say $r.^name; # OUTPUT: «RatStr␤»
```

As a subclass of both a [`Numeric`](/type/Numeric) class and [`Str`](/type/Str), via the `Allomorph` class, an allomorph will be accepted where either is expected. However, an allomorph does not share object identity with its [`Numeric`](/type/Numeric) parent class- or [`Str`](/type/Str)-only variants:

```raku
my ($complex-str, $int-str, $num-str, $rat-str)
           = < 42+0i 42 42e10 42.1 >;

my (Complex $complex, Int $int, Num $num, Rat $rat)
           =  $complex-str, $int-str, $num-str, $rat-str;  # OK!

my Str @strings
           =  $complex-str, $int-str, $num-str, $rat-str;  # OK!

# ∈ operator cares about object identity
say 42+0i ∈ < 42+0i 42 42e10 42.1 >;  # OUTPUT: «False␤»
say 42    ∈ < 42+0i 42 42e10 42.1 >;  # OUTPUT: «False␤»
say 42e10 ∈ < 42+0i 42 42e10 42.1 >;  # OUTPUT: «False␤»
say 42.1  ∈ < 42+0i 42 42e10 42.1 >;  # OUTPUT: «False␤»

```

Please see [the Numerics page](/language/numerics#Allomorphs) for a more complete description on how to work with these allomorphs.

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

## [method ACCEPTS](#class_Allomorph "go to top of document")[§](#method_ACCEPTS "direct link")

```raku
multi method ACCEPTS(Allomorph:D: Any:D \a)
```

If the `a` parameter is [`Numeric`](/type/Numeric) (including another [allomorph](/language/glossary#Allomorph)), checks if invocant's [`Numeric`](/type/Numeric) value [ACCEPTS](/type/Numeric#method_ACCEPTS) `a`. If the `a` parameter is [`Str`](/type/Str), checks if invocant's [`Str`](/type/Str) value [ACCEPTS](/type/Str#method_ACCEPTS) `a`. If the `a` parameter is anything else, checks if both [`Numeric`](/type/Numeric) and [`Str`](/type/Str) values of the invocant `ACCEPTS` `a`.

```raku
say "5.0" ~~ <5>; # OUTPUT: «False␤»
say 5.0   ~~ <5>; # OUTPUT: «True␤»
say <5.0> ~~ <5>; # OUTPUT: «True␤»
```

## [method Bool](#class_Allomorph "go to top of document")[§](#method_Bool "direct link")

```raku
multi method Bool(::?CLASS:D:)
```

Returns `False` if the invocant is numerically `0`, otherwise returns `True`. The [`Str`](/type/Str) value of the invocant is not considered.

**Note**: For the `Allomorph` subclass [`RatStr`](/type/RatStr) also see [`Rational.Bool`](/type/Rational#method_Bool).

## [method chomp](#class_Allomorph "go to top of document")[§](#method_chomp "direct link")

```raku
method chomp(Allomorph:D:)
```

Calls [`Str.chomp`](/type/Str#routine_chomp) on the invocant's [`Str`](/type/Str) value.

## [method chop](#class_Allomorph "go to top of document")[§](#method_chop "direct link")

```raku
method chop(Allomorph:D: |c)
```

Calls [`Str.chop`](/type/Str#routine_chop) on the invocant's [`Str`](/type/Str) value.

## [method comb](#class_Allomorph "go to top of document")[§](#method_comb "direct link")

```raku
method comb(Allomorph:D: |c)
```

Calls [`Str.comb`](/type/Str#routine_comb) on the invocant's [`Str`](/type/Str) value.

## [method fc](#class_Allomorph "go to top of document")[§](#method_fc "direct link")

```raku
method fc(Allomorph:D:)
```

Calls [`Str.fc`](/type/Str#routine_fc) on the invocant's [`Str`](/type/Str) value.

## [method flip](#class_Allomorph "go to top of document")[§](#method_flip "direct link")

```raku
method flip(Allomorph:D:)
```

Calls [`Str.flip`](/type/Str#routine_flip) on the invocant's [`Str`](/type/Str) value.

## [method lc](#class_Allomorph "go to top of document")[§](#method_lc "direct link")

```raku
method lc(Allomorph:D:)
```

Calls [`Str.lc`](/type/Str#routine_lc) on the invocant's [`Str`](/type/Str) value.

## [method pred](#class_Allomorph "go to top of document")[§](#method_pred "direct link")

```raku
method pred(Allomorph:D:)
```

Calls [`Numeric.pred`](/type/Numeric#method_pred) on the invocant's numeric value.

## [method raku](#class_Allomorph "go to top of document")[§](#method_raku "direct link")

```raku
multi method raku(Allomorph:D:)
```

Return a representation of the object that can be used via [`EVAL`](/routine/EVAL) to reconstruct the value of the object.

## [method samecase](#class_Allomorph "go to top of document")[§](#method_samecase "direct link")

```raku
method samecase(Allomorph:D: |c)
```

Calls [`Str.samecase`](/type/Str#method_samecase) on the invocant's [`Str`](/type/Str) value.

## [method samemark](#class_Allomorph "go to top of document")[§](#method_samemark "direct link")

```raku
method samemark(Allomorph:D: |c)
```

Calls [`Str.samemark`](/type/Str#routine_samemark) on the invocant's [`Str`](/type/Str) value.

## [method split](#class_Allomorph "go to top of document")[§](#method_split "direct link")

```raku
method split(Allomorph:D: |c)
```

Calls [`Str.split`](/type/Str#routine_split) on the invocant's [`Str`](/type/Str) value.

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

```raku
method Str(Allomorph:D:)
```

Returns the [`Str`](/type/Str) value of the invocant.

## [method subst](#class_Allomorph "go to top of document")[§](#method_subst "direct link")

```raku
method subst(Allomorph:D: |c)
```

Calls [`Str.subst`](/type/Str#method_subst) on the invocant's [`Str`](/type/Str) value.

## [method subst-mutate](#class_Allomorph "go to top of document")[§](#method_subst-mutate "direct link")

```raku
method subst-mutate(Allomorph:D \SELF: |c)
```

Calls [`Str.subst-mutate`](/type/Str#method_subst-mutate) on the invocant's [`Str`](/type/Str) value.

## [method substr](#class_Allomorph "go to top of document")[§](#method_substr "direct link")

```raku
method substr(Allomorph:D: |c)
```

Calls [`Str.substr`](/type/Str#routine_substr) on the invocant's [`Str`](/type/Str) value.

## [method substr-rw](#class_Allomorph "go to top of document")[§](#method_substr-rw "direct link")

```raku
method substr-rw(Allomorph:D \SELF: $start = 0, $want = Whatever)
```

Calls [`Str.substr-rw`](/type/Str#method_substr-rw) on the invocant's [`Str`](/type/Str) value.

## [method succ](#class_Allomorph "go to top of document")[§](#method_succ "direct link")

```raku
method succ(Allomorph:D:)
```

Calls [`Numeric.succ`](/type/Numeric#method_succ) on the invocant's numeric value.

## [method tc](#class_Allomorph "go to top of document")[§](#method_tc "direct link")

```raku
method tc(Allomorph:D:)
```

Calls [`Str.tc`](/type/Str#routine_tc) on the invocant's [`Str`](/type/Str) value.

## [method tclc](#class_Allomorph "go to top of document")[§](#method_tclc "direct link")

```raku
method tclc(Allomorph:D:)
```

Calls [`Str.tclc`](/type/Str#routine_tclc) on the invocant's [`Str`](/type/Str) value.

## [method trim](#class_Allomorph "go to top of document")[§](#method_trim "direct link")

```raku
method trim(Allomorph:D:)
```

Calls [`Str.trim`](/type/Str#method_trim) on the invocant's [`Str`](/type/Str) value.

## [method trim-leading](#class_Allomorph "go to top of document")[§](#method_trim-leading "direct link")

```raku
method trim-leading(Allomorph:D:)
```

Calls [`Str.trim-leading`](/type/Str#method_trim-leading) on the invocant's [`Str`](/type/Str) value.

## [method trim-trailing](#class_Allomorph "go to top of document")[§](#method_trim-trailing "direct link")

```raku
method trim-trailing(Allomorph:D:)
```

Calls [`Str.trim-trailing`](/type/Str#method_trim-trailing) on the invocant's [`Str`](/type/Str) value.

## [method uc](#class_Allomorph "go to top of document")[§](#method_uc "direct link")

```raku
method uc(Allomorph:D:)
```

Calls [`Str.uc`](/type/Str#routine_uc) on the invocant's [`Str`](/type/Str) value.

## [method WHICH](#class_Allomorph "go to top of document")[§](#method_WHICH "direct link")

```raku
multi method WHICH(Allomorph:D:)
```

Returns an object of type [`ValueObjAt`](/type/ValueObjAt) which uniquely identifies the object.

```raku
my $f = <42.1e0>;
say $f.WHICH;     # OUTPUT: «NumStr|Num|42.1|Str|42.1e0␤»
```

# [Operators](#class_Allomorph "go to top of document")[§](#Operators "direct link")

## [infix cmp](#class_Allomorph "go to top of document")[§](#infix_cmp "direct link")

```raku
multi infix:<cmp>(Allomorph:D $a, Allomorph:D $b)
```

Compare two `Allomorph` objects. The comparison is done on the [`Numeric`](/type/Numeric) value first and then on the [`Str`](/type/Str) value. If you want to compare in a different order then you would coerce to a [`Numeric`](/type/Numeric) or [`Str`](/type/Str) value first:

```raku
my $f = IntStr.new(42, "smaller");
my $g = IntStr.new(43, "larger");
say $f cmp $g;          # OUTPUT: «Less␤»
say $f.Str cmp $g.Str;  # OUTPUT: «More␤»
```

## [infix eqv](#class_Allomorph "go to top of document")[§](#infix_eqv "direct link")

```raku
multi infix:<eqv>(Allomorph:D $a, Allomorph:D $b --> Bool:D)
```

Returns `True` if the two `Allomorph` `$a` and `$b` are of the same type, their [`Numeric`](/type/Numeric) values are [equivalent](/routine/eqv) and their [`Str`](/type/Str) values are also [equivalent](/routine/eqv). Returns `False` otherwise.

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

Type relations for `Allomorph`

raku-type-graph

Allomorph
Allomorph

Str
Str

Allomorph->Str

Mu
Mu

Any
Any

Any->Mu

Cool
Cool

Cool->Any

Stringy
Stringy

Str->Cool

Str->Stringy

Numeric
Numeric

Real
Real

Real->Numeric

Int
Int

Int->Cool

Int->Real

IntStr
IntStr

IntStr->Allomorph

IntStr->Int

Num
Num

Num->Cool

Num->Real

NumStr
NumStr

NumStr->Allomorph

NumStr->Num

Complex
Complex

Complex->Cool

Complex->Numeric

ComplexStr
ComplexStr

ComplexStr->Allomorph

ComplexStr->Complex

Rational
Rational

Rational->Real

Rat
Rat

Rat->Cool

Rat->Rational

RatStr
RatStr

RatStr->Allomorph

RatStr->Rat

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


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

# NAME

MQTT::Client - Minimal MQTT v3 client interface for Perl 6

# SYNOPSIS

```
use MQTT::Client;

my $m = MQTT::Client.new('test.mosquitto.org');
await $m.connect;

$m.publish("hello-world", "$*PID is still here!");

react {
    whenever $m.subscribe("typing-speed-test.aoeu.eu") {
        say "Typing test completed at { .<message>.decode("utf8-c8") }";
    }

    whenever Supply.interval(10) {
        $m.publish("hello-world", "$*PID is still here!");
    }
}

```

# METHODS

## new($server, $port)

Returns a new `MQTT::Client` object. Note: it does not automatically connect. Before doing anything, `.connect` should be called!

## connect

Attempts to connect to the MQTT broker, and returns a `Promise` that will be kept after connection confirmation from the broker.

## connection

Returns a `Promise` that isn't kept until the connection ends.

## publish(Str $topic, Buf|Str $message)

## retain(Str $topic, Buf|Str $message)

Publish a message to the MQTT broker. If the $message is a Str, it will be UTF-8 encoded. Topics are always UTF-8 encoded in MQTT.

## subscribe($topic)

Subscribes to the topic, returning a `Supply` of messages that match the topic. Note that messages that are matched by multiple subscriptions will be passed to all of the supplies that match.

Tap the supply to receive, for each message, a hash with the keys `topic`, `message`, and a boolean `retain`. Note that `message` is a `Buf` (binary buffer), which in most cases you will need to `.decode` before you can use it.

# FUNCTIONS

## MQTT::Client::filter\_as\_regex(topic\_filter)

Given a valid MQTT topic filter, returns the corresponding regular expression.

# NOT YET IMPLEMENTED

The following features that are present in Net::MQTT::Simple for Perl, have not yet been implemented in `MQTT::Client` for Raku:

* dropping the connection when a large message is received
* unsubscribe
* automatic reconnecting
* SSL
* connection timeouts
* simple functional interface

# NOT SUPPORTED

* QoS (Quality of Service)

Every message is published at QoS level 0, that is, "at most once", also known as "fire and forget".

* DUP (Duplicate message)

Since QoS is not supported, no retransmissions are done, and no message will indicate that it has already been sent before.

* Authentication

No username and password are sent to the server.

* Last will

The server won't publish a "last will" message on behalf of us when our connection's gone.

* Large data

Because everything is handled in memory and there's no way to indicate to the server that large messages are not desired, the connection is dropped as soon as the server announces a packet larger than 2 megabytes.

* Validation of server-to-client communication

The MQTT spec prescribes mandatory validation of all incoming data, and disconnecting if anything (really, anything) is wrong with it. However, this minimal implementation silently ignores anything it doesn't specifically handle, which may result in weird behaviour if the server sends out bad data.

Most clients do not adhere to this part of the specifications.

# AUTHOR

Juerd Waalboer

# COPYRIGHT AND LICENSE

Copyright 2015 - 2019 Juerd Waalboer

Copyright 2024 Raku Community

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

# SEE ALSO

[Net::MQTT::Simple](https://metacpan.org/pod/Net::MQTT::Simple) inr Perl


## dist_cpan-KJPYE-Geo-Coordinates-UTM.md
# NAME

Geo::Coordinates::UTM - Perl extension for Latitude Longitude conversions.

# SYNOPSIS

use Geo::Coordinates::UTM;

my ($zone,$easting,$northing)=|latlon-to-utm($ellipsoid,$latitude,$longitude);

my ($latitude,$longitude)=|utm-to-latlon($ellipsoid,$zone,$easting,$northing);

my ($zone,$easting,$northing)=|mgrs-to-utm($mgrs);

my ($latitude,$longitude)=|mgrs-to-latlon($ellipsoid,$mgrs);

my ($mgrs)=|utm-to-mgrs($zone,$easting,$northing);

my ($mgrs)=|latlon-to-mgrs($ellipsoid,$latitude,$longitude);

my @ellipsoids=ellipsoid-names;

my($name, $r, $sqecc) = |ellipsoid-info 'WGS-84';

# DESCRIPTION

This module will translate latitude longitude coordinates to Universal Transverse Mercator(UTM) coordinates and vice versa.

## Mercator Projection

The Mercator projection was first invented to help mariners. They needed to be able to draw a straight line on a map and follow that bearing to arrive at a destination. In order to do this, Mercator invented a projection which preserved angle, by projecting the earth's surface onto a cylinder, sharing the same axis as the earth itself. This caused all Latitude and Longitude lines to be straight and to intersect at a 90 degree angle, but the downside was that the scale of the map increased as you moved away from the equator so that the lines of longitude were parallel.

Because the scale varies, areas near the poles appear much larger on the map than a similar sized object near the equator. The Mercator Projection is useless near the poles since the scale becomes infinite.

## Transverse Mercator Projection

A Transverse Mercator projection takes the cylinder and turns it on its side. Now the cylinder's axis passes through the equator, and it can be rotated to line up with the area of interest. Many countries use Transverse Mercator for their grid systems. The disadvantage is that now neither the lines of latitude or longitude (apart from the central meridian) are straight.

## Universal Transverse Mercator

The Universal Transverse Mercator(UTM) system sets up a universal world wide system for mapping. The Transverse Mercator projection is used, with the cylinder in 60 positions. This creates 60 zones around the world. Positions are measured using Eastings and Northings, measured in meters, instead of Latitude and Longitude. Eastings start at 500,000 on the centre line of each zone. In the Northern Hemisphere, Northings are zero at the equator and increase northward. In the Southern Hemisphere, Northings start at 10 million at the equator, and decrease southward. You must know which hemisphere and zone you are in to interpret your location globally. Distortion of scale, distance and area increase away from the central meridian.

UTM projection is used to define horizontal positions world-wide by dividing the surface of the Earth into 6 degree zones, each mapped by the Transverse Mercator projection with a central meridian in the center of the zone. UTM zone numbers designate 6 degree longitudinal strips extending from 80 degrees South latitude to 84 degrees North latitude. UTM zone characters designate 8 degree zones extending north and south from the equator. Eastings are measured from the central meridian (with a 500 km false easting to insure positive coordinates). Northings are measured from the equator (with a 10,000 km false northing for positions south of the equator).

UTM is applied separately to the Northern and Southern Hemisphere, thus within a single UTM zone, a single X / Y pair of values will occur in both the Northern and Southern Hemisphere. To eliminate this confusion, and to speed location of points, a UTM zone is sometimes subdivided into 20 zones of Latitude. These grids can be further subdivided into 100,000 meter grid squares with double-letter designations. This subdivision by Latitude and further division into grid squares is generally referred to as the Military Grid Reference System (MGRS). The unit of measurement of UTM is always meters and the zones are numbered from 1 to 60 eastward, beginning at the 180th meridian. The scale distortion in a north-south direction parallel to the central meridian (CM) is constant However, the scale distortion increases either direction away from the CM. To equalize the distortion of the map across the UTM zone, a scale factor of 0.9996 is applied to all distance measurements within the zone. The distortion at the zone boundary, 3 degrees away from the CM is approximately 1%.

## Datums and Ellipsoids

Unlike local surveys, which treat the Earth as a plane, the precise determination of the latitude and longitude of points over a broad area must take into account the actual shape of the Earth. To achieve the precision necessary for accurate location, the Earth cannot be assumed to be a sphere. Rather, the Earth's shape more closely approximates an ellipsoid (oblate spheroid): flattened at the poles and bulging at the Equator. Thus the Earth's shape, when cut through its polar axis, approximates an ellipse. A "Datum" is a standard representation of shape and offset for coordinates, which includes an ellipsoid and an origin. You must consider the Datum when working with geospatial data, since data with two different Datum will not line up. The difference can be as much as a kilometer!

# EXAMPLES

A description of the available ellipsoids and sample usage of the conversion routines follows

## Ellipsoids

The Ellipsoids available are as follows:

# over

6

* 1 Airy
* 2 Australian National
* 3 Bessel 1841
* 4 Bessel 1841 (Nambia)
* 5 Clarke 1866
* 6 Clarke 1880
* 7 Everest 1830 (India)
* 8 Fischer 1960 (Mercury)
* 9 Fischer 1968
* 10 GRS 1967
* 11 GRS 1980
* 12 Helmert 1906
* 13 Hough
* 14 International
* 15 Krassovsky
* 16 Modified Airy
* 17 Modified Everest
* 18 Modified Fischer 1960
* 19 South American 1969
* 20 WGS 60
* 21 WGS 66
* 22 WGS-72
* 23 WGS-84
* 24 Everest 1830 (Malaysia)
* 25 Everest 1956 (India)
* 26 Everest 1964 (Malaysia and Singapore)
* 27 Everest 1969 (Malaysia)
* 28 Everest (Pakistan)
* 29 Indonesian 1974
* 30 Arc 1950
* 31 NAD 27
* 32 NAD 83

# back

## ellipsoid-names

The ellipsoids can be accessed using ellipsoid-names. To store thes into an array you could use

```
my @names = ellipsoid-names;

```

## ellipsoid-info

Ellipsoids may be called either by name, or number. To return the ellipsoid information, ( "official" name, equator radius and square eccentricity) you can use ellipsoid-info and specify a name. The specified name can be numeric (for compatibility reasons) or a more-or-less exact name. Any text between parentheses will be ignored.

```
my($name, $r, $sqecc) = |ellipsoid-info 'wgs84';
my($name, $r, $sqecc) = |ellipsoid-info 'WGS 84';
my($name, $r, $sqecc) = |ellipsoid-info 'WGS-84';
my($name, $r, $sqecc) = |ellipsoid-info 'WGS-84 (new specs)';
my($name, $r, $sqecc) = |ellipsoid-info 23;

```

## latlon-to-utm

Latitude values in the southern hemisphere should be supplied as negative values (e.g. 30 deg South will be -30). Similarly Longitude values West of the meridian should also be supplied as negative values. Both latitude and longitude should not be entered as deg,min,sec but as their decimal equivalent, e.g. 30 deg 12 min 22.432 sec should be entered as 30.2062311

The ellipsoid value should correspond to one of the numbers above, e.g. to use WGS-84, the ellipsoid value should be 23

For latitude 57deg 49min 59.000sec North longitude 02deg 47min 20.226sec West

using Clarke 1866 (Ellipsoid 5)

```
($zone,$east,$north)=|latlon-to-utm('clarke 1866',57.803055556,-2.788951667)

```

returns

```
$zone  = 30V
$east  = 512543.777159849
$north = 6406592.20049111

```

On occasions, it is necessary to map a pair of (latitude, longitude) coordinates to a predefined zone. This is done by p[roviding a value for the optional named parameter zone as follows:

```
($zone, $east, $north)=|latlon-to-utm('international', :zone($zone_number),
                                     $latitude, $longitude)

```

For instance, Spain territory goes over zones 29, 30 and 31 but sometimes it is convenient to use the projection corresponding to zone 30 for all the country.

Santiago de Compostela is at 42deg 52min 57.06sec North, 8deg 32min 28.70sec West

```
($zone, $east, $norh)=|latlon-to-utm('international',  42.882517, -8.541306)

```

returns

```
$zone = 29T
$east = 537460.331
$north = 4747955.991

```

but forcing the conversion to zone 30:

```
($zone, $east, $norh)=|latlon-to-utm('international', :zone(30),
                                     42.882517, -8.541306)

```

returns

```
$zone = 30T
$east = 47404.442
$north = 4762771.704

```

## utm-to-latlon

Reversing the above example,

```
($latitude,$longitude)=|utm-to-latlon(5,'30V',512543.777159849,6406592.20049111)

```

returns

```
$latitude  = 57.8030555601332
$longitude = -2.7889516669741

which equates to

latitude  57deg 49min 59.000sec North
longitude 02deg 47min 20.226sec West

```

## latlon-to-mgrs

Latitude values in the southern hemisphere should be supplied as negative values (e.g. 30 deg South will be -30). Similarly Longitude values West of the meridian should also be supplied as negative values. Both latitude and longitude should not be entered as deg,min,sec but as their decimal equivalent, e.g. 30 deg 12 min 22.432 sec should be entered as 30.2062311

The ellipsoid value should correspond to one of the numbers above, e.g. to use WGS-84, the ellipsoid value should be 23

For latitude 57deg 49min 59.000sec North longitude 02deg 47min 20.226sec West

using WGS84 (Ellipsoid 23)

```
($mgrs)=|latlon-to-mgrs(23,57.8030590197684,-2.788956799)

```

returns

```
$mgrs  = 30VWK1254306804

```

## mgrs-to-latlon

Reversing the above example,

```
($latitude,$longitude)=|mgrs-to-latlon(23,'30VWK1254306804')

```

returns

```
$latitude  = 57.8030590197684
$longitude = -2.788956799645

```

## mgrs-to-utm

```
Similarly it is possible to convert MGRS directly to UTM

    ($zone,$easting,$northing)=|mgrs-to-utm('30VWK1254306804')

returns

    $zone = 30V
    $easting = 512543
    $northing = 6406804

```

## utm-to-mgrs

```
and the inverse converting from UTM yo MGRS is done as follows

   ($mgrs)=|utm-to-mgrs('30V',512543,6406804);

returns
    $mgrs = 30VWK1254306804

```

# AUTHOR

Graham Crookham, [grahamc@cpan.org](mailto:grahamc@cpan.org)

# THANKS

Thanks go to the following:

Felipe Mendonca Pimenta for helping out with the Southern hemisphere testing.

Michael Slater for discovering the Escape \Q bug.

Mark Overmeer for the ellipsoid\_info routines and code review.

Lok Yan for the >72deg. N bug.

Salvador Fandino for the forced zone UTM and additional tests

Matthias Lendholt for modifications to MGRS calculations

Peder Stray for the short MGRS patch

# COPYRIGHT

Copyright (c) 2000,2002,2004,2007,2010,2013 by Graham Crookham. All rights reserved.

copyright (c) 2017 by Kevin Pye.

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


## cache.md
cache

Combined from primary sources listed below.

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

See primary documentation
[in context](/type/Any#method_cache)
for **method cache**.

```raku
method cache()
```

Provides a [`List`](/type/List) representation of the object itself, calling the method `list` on the instance.

# [In role PositionalBindFailover](#___top "go to top of document")[§](#(role_PositionalBindFailover)_method_cache "direct link")

See primary documentation
[in context](/type/PositionalBindFailover#method_cache)
for **method cache**.

```raku
method cache(PositionalBindFailover:D: --> List:D)
```

Returns a [`List`](/type/List) based on the `iterator` method, and caches it. Subsequent calls to `cache` always return the same [`List`](/type/List) object.


## dist_zef-lizmat-Method-Protected.md
[![Actions Status](https://github.com/lizmat/Method-Protected/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/Method-Protected/actions) [![Actions Status](https://github.com/lizmat/Method-Protected/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/Method-Protected/actions) [![Actions Status](https://github.com/lizmat/Method-Protected/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/Method-Protected/actions)

# NAME

Method::Protected - add "is protected" trait to methods

# SYNOPSIS

```
use Method::Protected;

my @words = "/usr/share/dict/words".IO.lines;

class Frobnicate {
    has %!hash;
    method pick() is protected { %!hash{@words.pick}++ }
    method hash() is protected { %!hash.clone          }
}

# Set up 2 threads massively updating a single hash
my $frobnicator = Frobnicate.new;
start { loop { $frobnicator.pick }
start { loop { $frobnicator.pick }

# Start reporter
until $frobnicator.hash.elems == @words.elems {
    say $frobnicator.hash.elems;
    sleep .1;
}

```

# DESCRIPTION

The `Method::Protected` distribution provides an `is protected` trait to methods in a class. If applied to a method, all calls to that method will be protected by a [Lock](https://docs.raku.org/type/Lock), making sure that any other method call to this method (or any other method protected by the trait) from another thread, will block until the call is finished.

Functionally this is similar to what the [OO::Monitor](https://raku.land/cpan:JNTHN/OO::Monitors) does, except that with this module this logic is only applied to methods that actuall have the `is protected` trait applied.

# THEORY OF OPERATION

When the trait is applied on a method, the class of the method id checked whether it already has a `$!LOCK` attribute. If not, then that attribute is added, and the associated accessor method `LOCK` is also added. Then the method will be [wrapped](https://docs.raku.org/routine/wrap) with code that will protect the execution of the original body of the method.

# A NOTE OF CAUTION

If the method being protected has an `is raw` or `is rw` trait set, then the protected version will also have that set. However, this is usually used to return a container, which can potentially cause a race-condition **outside** of the protected method because the container **may** contain logic that would execute code in a non-threadsafe manner (e.g. in the autovivification of keys in a hash).

So only use `is raw` or `is rw` on protected methods if you **really** know what you're doing. Generally spoken: don't do that! If you think you need to do this, first find another way to structure your code, e.g. by using [`hyper`](https://docs.raku.org/type/Iterable#method_hyper).

# AUTHOR

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

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

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!

# COPYRIGHT AND LICENSE

Copyright 2024, 2025 Elizabeth Mattijsen

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


## abs.md
abs

Combined from primary sources listed below.

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

See primary documentation
[in context](/type/Complex#routine_abs)
for **routine abs**.

```raku
method abs(Complex:D: --> Num:D)
multi  abs(Complex:D $z --> Num:D)
```

Returns the absolute value of the invocant (or the argument in sub form). For a given complex number `$z` the absolute value `|$z|` is defined as `sqrt($z.re * $z.re + $z.im * $z.im)`.

```raku
say (3+4i).abs;                 # OUTPUT: «5␤»
                                # sqrt(3*3 + 4*4) == 5
```

# [In role Numeric](#___top "go to top of document")[§](#(role_Numeric)_routine_abs "direct link")

See primary documentation
[in context](/type/Numeric#routine_abs)
for **routine abs**.

```raku
multi        abs(Numeric:D  --> Real:D)
multi method abs(Numeric:D: --> Real:D)
```

Returns the absolute value of the number.

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

See primary documentation
[in context](/type/Cool#routine_abs)
for **routine abs**.

```raku
sub abs(Numeric() $x)
method abs()
```

Coerces the invocant (or in the sub form, the argument) to [`Numeric`](/type/Numeric) and returns the absolute value (that is, a non-negative number).

```raku
say (-2).abs;       # OUTPUT: «2␤»
say abs "6+8i";     # OUTPUT: «10␤»
```