## objects.md
## Chunk 1 of 2
Object orientation

Object orientation in Raku

Raku provides strong support for [Object Oriented Programming (OOP)](https://en.wikipedia.org/wiki/Object-oriented_programming). Although Raku allows programmers to program in multiple paradigms, Object Oriented Programming is at the heart of the language.

Raku comes with a wealth of predefined types, which can be classified in two categories: regular and [*native* types](/language/nativetypes). Everything that you can store in a variable is either a *native value* or an *object*. That includes literals, types (type objects), code and containers.

Native types are used for low-level types (like `uint64`). Even if *native* types do not have the same capabilities as objects, if you call methods on them, they are automatically *boxed* into normal objects.

Everything that is not a *native* value is an *object*. Objects do allow for both [inheritance](https://en.wikipedia.org/wiki/Object-oriented_programming#Inheritance_and_behavioral_subtyping) and [encapsulation](https://en.wikipedia.org/wiki/Object-oriented_programming#Encapsulation).

# [Using objects](#Object_orientation "go to top of document")[§](#Using_objects "direct link")

To call a method on an object, add a dot, followed by the method name:

```raku
say "abc".uc;
# OUTPUT: «ABC␤»

```

This calls the `uc` method on `"abc"`, which is an object of type [`Str`](/type/Str). To supply arguments to the method, add arguments inside parentheses after the method.

```raku
my $formatted-text = "Fourscore and seven years ago...".indent(8);
say $formatted-text;
# OUTPUT: «        Fourscore and seven years ago...␤»

```

`$formatted-text` now contains the above text, but indented 8 spaces.

Multiple arguments are separated by commas:

```raku
my @words = "Abe", "Lincoln";
@words.push("said", $formatted-text.comb(/\w+/));
say @words;
# OUTPUT: «[Abe Lincoln said (Fourscore and seven years ago)]␤»

```

Similarly, multiple arguments can be specified by placing a colon after the method and separating the argument list with a comma:

```raku
say @words.join('--').subst: 'years', 'DAYS';
# OUTPUT: «Abe--Lincoln--said--Fourscore and seven DAYS ago␤»

```

Since you have to put a `:` after the method if you want to pass arguments without parentheses, a method call without a colon or parentheses is unambiguously a method call without an argument list:

```raku
say 4.log:   ; # OUTPUT: «1.38629436111989␤» ( natural logarithm of 4 )
say 4.log: +2; # OUTPUT: «2␤» ( base-2 logarithm of 4 )
say 4.log  +2; # OUTPUT: «3.38629436111989␤» ( natural logarithm of 4, plus 2 )
```

Many operations that don't look like method calls (for example, smartmatching or interpolating an object into a string) might result in method calls under the hood.

Methods can return mutable containers, in which case you can assign to the return value of a method call. This is how read-writable attributes to objects are used:

```raku
$*IN.nl-in = "\r\n";

```

Here, we call method `nl-in` on the `$*IN` object, without arguments, and assign to the container it returned with the [`=`](/routine/= (item assignment)) operator.

All objects support methods from class [`Mu`](/type/Mu), which is the type hierarchy root. All objects derive from [`Mu`](/type/Mu).

Object equality needs a specific operator: [`eqv`](/language/operators#infix_eqv), the structural comparison operator:

```raku
class Foo {
    has $.bar;
    has $.baz
};
my $bar = "42";
my $baz = 24;
my $zipi = Foo.new( :$baz, :$bar);
my $zape = Foo.new( :$bar, :$baz);
say $zipi eqv $zape; # OUTPUT: «True␤»

```

Object identity, on the other hand, uses `===`. Using it above will return `False`, for instance.

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

Types themselves are objects and you can get the *type object* by writing its name:

```raku
my $int-type-obj = Int;

```

You can request the type object of anything by calling the `WHAT` method, which is actually a macro in method form:

```raku
my $int-type-obj = 1.WHAT;

```

Type objects (other than [`Mu`](/type/Mu)) can be compared for equality with the [`===`](/routine/===) identity operator:

```raku
sub f(Int $x) {
    if $x.WHAT === Int {
        say 'you passed an Int';
    }
    else {
        say 'you passed a subtype of Int';
    }
}

```

Although, in most cases, the [`.isa`](/routine/isa) method will suffice:

```raku
sub f($x) {
    if $x.isa(Int) {
        ...
    }
    ...
}

```

Subtype checking is done by [smartmatching](/language/operators#infix_~~):

```raku
if $type ~~ Real {
    say '$type contains Real or a subtype thereof';
}

```

# [Classes](#Object_orientation "go to top of document")[§](#Classes "direct link")

Classes are declared using the `class` keyword, typically followed by a name.

```raku
class Journey { }

```

This declaration results in a type object being created and installed in the current package and current lexical scope under the name `Journey`. You can also declare classes lexically:

```raku
my class Journey { }

```

This restricts their visibility to the current lexical scope, which can be useful if the class is an implementation detail nested inside a module or another class.

## [Attributes](#Object_orientation "go to top of document")[§](#Attributes "direct link")

Attributes are variables that exist per instance of a class; when instantiated to a value, the association between the variable and its value is called a property. They are where the state of an object is stored. In Raku, all attributes are *private*, which means they can be accessed directly only by the class instance itself. They are typically declared using the `has` declarator and the `!` twigil.

```raku
class Journey {
    has $!origin;
    has $!destination;
    has @!travelers;
    has $!notes;
}

```

Alternatively, you can omit the twigil, which will still create the private attribute (with a `!` twigil), and will also create an alias that binds the name (without the twigil) to that attribute. Thus, you can declare the same class above with

```raku
class Journey {
    has $origin;
    has $destination;
    has @travelers;
    has $notes;
}

```

If you declare the class like this, you can subsequently access the attributes either with or without the twigil – e.g., `$!origin` and `$origin` refer to same attribute.

While there is no such thing as a public (or even protected) attribute, there is a way to have accessor methods generated automatically: replace the `!` twigil with the `.` twigil (the `.` should remind you of a method call).

```raku
class Journey {
    has $.origin;
    has $.destination;
    has @!travelers;
    has $.notes;
}

```

This defaults to providing a read-only accessor. In order to allow changes to the attribute, add the [is rw](/routine/is%20rw) trait:

```raku
class Journey {
    has $.origin;
    has $.destination;
    has @!travelers;
    has $.notes is rw;
}

```

Now, after a `Journey` object is created, its `.origin`, `.destination`, and `.notes` will all be accessible from outside the class, but only `.notes` can be modified.

If an object is instantiated without certain attributes, such as origin or destination, we may not get the desired result. To prevent this, provide default values or make sure that an attribute is set on object creation by marking an attribute with an [is required](/routine/is%20required) trait.

```raku
class Journey {
    # error if origin is not provided
    has $.origin is required;
    # set the destination to Orlando as default (unless that is the origin!)
    has $.destination = self.origin eq 'Orlando' ?? 'Kampala' !! 'Orlando';
    has @!travelers;
    has $.notes is rw;
}

```

Since classes inherit a default constructor from [`Mu`](/type/Mu) and we have requested that some accessor methods are generated for us, our class is already somewhat functional.

```raku
# Create a new instance of the class.
my $vacation = Journey.new(
    origin      => 'Sweden',
    destination => 'Switzerland',
    notes       => 'Pack hiking gear!'
);

# Use an accessor; this outputs Sweden.
say $vacation.origin;

# Use a rw accessor to change the value.
$vacation.notes = 'Pack hiking gear and sunglasses!';

```

Note that, although the default constructor can initialize read-only attributes, it will only set attributes that have an accessor method. That is, even if you pass `travelers => ["Alex", "Betty"]` to the default constructor, the attribute `@!travelers` is not initialized.

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

Methods are declared with the `method` keyword inside a class body.

```raku
class Journey {
    has $.origin;
    has $.destination;
    has @!travelers;
    has $.notes is rw;

    method add-traveler($name) {
        if $name ne any(@!travelers) {
            push @!travelers, $name;
        }
        else {
            warn "$name is already going on the journey!";
        }
    }

    method describe() {
        "From $!origin to $!destination"
    }
}

```

A method can have a signature, just like a subroutine. Attributes can be used in methods and can always be used with the `!` twigil, even if they are declared with the `.` twigil. This is because the `.` twigil declares an attribute and generates an accessor method for it.

Looking at the code above, there is a subtle but important difference between using `$!origin` and `$.origin` in the method `describe`. `$!origin` is an inexpensive and obvious lookup of the attribute. `$.origin` is a method call and thus may be overridden in a subclass. Only use `$.origin` if you want to allow overriding.

Unlike subroutines, additional named arguments will not produce compile time or runtime errors. That allows chaining of methods via [Re-dispatching](/language/functions#Re-dispatching).

You may write your own accessors to override any or all of the autogenerated ones.

```raku
my $ⲧ = " " xx 4; # A tab-like thing
class Journey {
    has $.origin;
    has $.destination;
    has @.travelers;
    has Str $.notes is rw;

    multi method notes() { "$!notes\n" };
    multi method notes( Str $note ) { $!notes ~= "$note\n$ⲧ" };

    method Str { "⤷ $!origin\n$ⲧ" ~ self.notes() ~ "$!destination ⤶\n" };
}

my $trip = Journey.new( :origin<Here>, :destination<There>,
                        travelers => <þor Freya> );

$trip.notes("First steps");
notes $trip: "Almost there";
print $trip;

# OUTPUT:
#⤷ Here
#       First steps
#       Almost there
#
#There ⤶

```

The declared multi method `notes` overrides the auto-generated methods implicit in the declaration of `$.notes`, using a different signature for reading and writing.

Please note that in `notes $trip: "Almost there"` we are using indirect invocant syntax, which puts first the method name, then the object, and then, separated by a colon, the arguments: `method invocant: arguments`. We can use this syntax whenever it feels more natural than the classical period-and-parentheses one. It works exactly in the same way.

Note how the call to the `notes` method in the [`Str`](/routine/Str) method is made on `self`. Writing method calls this way will leave the return value of the method as is with regards to containers. To containerize return values, you can make method calls on a sigil instead of `self`. This calls various methods on the return value of the method depending on the sigil used to containerize it:

| Sigil | Method |
| --- | --- |
| $ | item |
| @ | list |
| % | hash |
| & | item |

For example, the [`Str`](/routine/Str) method of `Journey` can be rewritten not to use the `~` operator by embedding a sigiled method call in the string it returns:

```raku
method Str { "⤷ $!origin\n$ⲧ$.notes()$!destination ⤶\n" }

```

The syntax used to update `$.notes` changed in this section with respect to the previous [Attributes](#Attributes) section. Instead of an assignment:

```raku
$vacation.notes = 'Pack hiking gear and sunglasses!';

```

we now do a method call:

```raku
$trip.notes("First steps");

```

Classes Overriding the default auto-generated accessor means it is no longer available to provide a mutable container on return for an assignment. A method call is the preferred approach to adding computation and logic to the update of an attribute (see 'programmatic use' of such calls in the following section). Many modern languages can update an attribute by overloading assignment with a “setter” method. While Raku can overload the assignment operator for this purpose with a [`Proxy`](/type/Proxy) object, overloading assignment to set attributes with complex logic is currently discouraged as [weaker object oriented design](https://6guts.wordpress.com/2016/11/25/perl-6-is-biased-towards-mutators-being-really-simple-thats-a-good-thing/).

## [Class and instance methods](#Object_orientation "go to top of document")[§](#Class_and_instance_methods "direct link")

Method names can be resolved at runtime with the `.""` operator which enables programmatic use of such names. For example, since an attribute name is also a method, we can show attribute `a`'s value by calling the `a` method:

```raku
class A { has $.a = 9 }
my $method = 'a';
A.new."$method"().say;
# OUTPUT: «9␤»

```

A method with arguments may be called in a similar manner:

```raku
class B {
    has $.b = 9;
    method mul($n) {
        $!b * $n
    }
}
my $method = 'mul';
B.new."$method"(6).say;
# OUTPUT: «54␤»

```

A method's signature can have an *explicit invocant* as its first parameter followed by a colon, which allows for the method to refer to the object it was called on.

```raku
class Foo {
    method greet($me: $person) {
        say "Hi, I am $me.^name(), nice to meet you, $person";
    }
}
Foo.new.greet("Bob");    # OUTPUT: «Hi, I am Foo, nice to meet you, Bob␤»

```

Providing an invocant in the method signature also allows for defining the method as either as a class method, or as an object method, through the use of [type constraints](/language/signatures#Type_constraints). The `::?CLASS` variable can be used to provide the class name at compile time, combined with either `:U` (for class methods AKA static in other languages) or `:D` (for instance methods).

```raku
class Pizza {
    has $!radius = 42;
    has @.ingredients;

    # class method: construct from a list of ingredients
    method from-ingredients(::?CLASS:U $pizza: @ingredients) {
        $pizza.new( ingredients => @ingredients );
    }

    # instance method
    method get-radius(::?CLASS:D:) { $!radius }
}
my $p = Pizza.from-ingredients: <cheese pepperoni vegetables>;
say $p.ingredients;     # OUTPUT: «[cheese pepperoni vegetables]␤»
say $p.get-radius;      # OUTPUT: «42␤»
say Pizza.get-radius;   # This will fail.
CATCH { default { put .^name ~ ":\n" ~ .Str } };
# OUTPUT: «X::Parameter::InvalidConcreteness:␤
#          Invocant of method 'get-radius' must be
#          an object instance of type 'Pizza',
#          not a type object of type 'Pizza'.
#          Did you forget a '.new'?»

```

A method can be both a class and object method by using the [multi](/syntax/multi) declarator:

```raku
class C {
    multi method f(::?CLASS:U:) { say "class method"  }
    multi method f(::?CLASS:D:) { say "object method" }
}
C.f;       # OUTPUT: «class method␤»
C.new.f;   # OUTPUT: «object method␤»

```

## [`self`](#Object_orientation "go to top of document")[§](#self "direct link")

Inside a method, the term `self` is available and bound to the invocant object. `self` can be used to call further methods on the invocant, including constructors:

```raku
class Box {
  has $.data;

  method make-new-box-from() {
      self.new: data => $!data;
  }
}

```

`self` can be used in class or instance methods as well, though beware of trying to invoke one type of method from the other:

```raku
class C {
    method g()            { 42     }
    method f(::?CLASS:U:) { self.g }
    method d(::?CLASS:D:) { self.f }
}
C.f;        # OUTPUT: «42␤»
C.new.d;    # This will fail.
CATCH { default { put .^name ~ ":\n" ~ .Str } };
# OUTPUT: «X::Parameter::InvalidConcreteness:␤
#          Invocant of method 'f' must be a type object of type 'C',
#          not an object instance of type 'C'.  Did you forget a 'multi'?»

```

`self` can also be used with attributes, as long as they have an accessor. `self.a` will call the accessor for an attribute declared as `has $.a`. However, there is a difference between `self.a` and `$.a`, since the latter will itemize; `$.a` will be equivalent to `self.a.item` or `$(self.a)`.

```raku
class A {
    has Int @.numbers;
    has $.x = (1, 2, 3);

    method show-diff() { .say for self.x; .say for $.x }

    method twice  { self.times: 2 }
    method thrice { $.times: 3    }

    method times($val = 1) { @!numbers.map(* * $val).list }
};

my $obj = A.new(numbers => [1, 2, 3]);
$obj.show-diff;   # OUTPUT: «1␤2␤3␤(1 2 3)␤»
say $obj.twice;   # OUTPUT: «(2 4 6)␤»
say $obj.thrice;  # OUTPUT: «(3 6 9)␤»

```

The colon-syntax for method arguments is supported for method calls using either `self` or the shortcut, as illustrated with the methods `twice` and `thrice` in the example above.

Note that if the relevant methods `bless`, `CREATE` of [`Mu`](/type/Mu) are not overloaded, `self` will point to the type object in those methods.

On the other hand, the submethods `BUILD` and `TWEAK` are called on instances, in different stages of initialization. Submethods of the same name from subclasses have not yet run, so you should not rely on potentially virtual method calls inside these methods.

## [Private methods](#Object_orientation "go to top of document")[§](#Private_methods "direct link")

Methods with an exclamation mark `!` before the method name are not callable from anywhere outside the defining class; such methods are private in the sense that they are not visible from outside the class that declares them. Private methods are invoked with an exclamation mark instead of a dot:

```raku
class FunMath {
    has $.value is required;
    method !do-subtraction( $num ) {
        if $num ~~ Str {
            return $!value + (-1 * $num.chars);
        }
        return $!value + (-1 * $num);
    }
    method minus( $minuend: $subtrahend ) {
        # invoking the private method on the explicit invocant
        $minuend!do-subtraction($subtrahend);
    }
}
my $five = FunMath.new(value => 5);
say $five.minus(6);         # OUTPUT: «-1␤»

say $five.do-subtraction(6);
CATCH { default { put .^name ~ ":\n" ~ .Str } }
# OUTPUT: «X::Method::NotFound:
# No such method 'do-subtraction' for invocant of type
# 'FunMath'. Did you mean '!do-subtraction'?␤»

```

Private methods have their own namespace. They're not virtual, i.e., private methods cannot be overridden within the inheriting class to provide any polymorphic behavior, thus missing ones are detected at compile time. Unlike in some languages where `private` is an [accessibility modifier](https://en.wikipedia.org/wiki/Access_modifiers) on a method, in Raku "private methods" and "methods" are quite different things - that is to say, it's better to read "private method" as a compound noun rather than an adjective describing a noun.

Private methods are not inherited by subclasses.

## [Submethods](#Object_orientation "go to top of document")[§](#Submethods "direct link")

Submethods are public methods that will not be inherited by subclasses. The name stems from the fact that they are semantically similar to subroutines.

Submethods are useful for object construction and destruction tasks, as well as for tasks that are so specific to a certain type that subtypes would certainly have to override them.

For example, the [default method new](/type/Mu#method_new) calls submethod `BUILD` on each class in an [inheritance](#Inheritance) chain:

```raku
class Point2D {
    has $.x;
    has $.y;

    submethod BUILD(:$!x, :$!y) {
        say "Initializing Point2D";
    }
}

class InvertiblePoint2D is Point2D {
    submethod BUILD() {
        say "Initializing InvertiblePoint2D";
    }
    method invert {
        self.new(x => - $.x, y => - $.y);
    }
}

say InvertiblePoint2D.new(x => 1, y => 2);
# OUTPUT: «Initializing Point2D␤»
# OUTPUT: «Initializing InvertiblePoint2D␤»
# OUTPUT: «InvertiblePoint2D.new(x => 1, y => 2)␤»

```

See also: [Object construction](#Object_construction).

## [Inheritance](#Object_orientation "go to top of document")[§](#Inheritance "direct link")

Classes can have *parent classes*.

```raku
class Child is Parent1 is Parent2 { }

```

If a method is called on the child class, and the child class does not provide that method, the method of that name in one of the parent classes is invoked instead, if it exists. The order in which parent classes are consulted is called the *method resolution order* (MRO). Raku uses the [C3 method resolution order](https://en.wikipedia.org/wiki/C3_linearization). You can ask a type for its MRO through a call to its metaclass:

```raku
say List.^mro;      # OUTPUT: «((List) (Cool) (Any) (Mu))␤»

```

If a class does not specify a parent class, [`Any`](/type/Any) is assumed by default. All classes directly or indirectly derive from [`Mu`](/type/Mu), the root of the type hierarchy.

All calls to public methods are "virtual" in the C++ sense, which means that the actual type of an object determines which method to call, not the declared type:

```raku
class Parent {
    method frob {
        say "the parent class frobs"
    }
}

class Child is Parent {
    method frob {
        say "the child's somewhat more fancy frob is called"
    }
}

my Parent $test;
$test = Child.new;
$test.frob;          # calls the frob method of Child rather than Parent
# OUTPUT: «the child's somewhat more fancy frob is called␤»

```

If you want to explicitly call the parent method on a child object, refer to its full name in the parent namespace:

```raku
$test.Parent::frob;  # calls the frob method of Parent
# OUTPUT: «the parent class frobs␤»

```

## [Delegation](#Object_orientation "go to top of document")[§](#Delegation "direct link")

Delegation is a technique whereby an object, the *delegator*, accepts a method call but has designated another object, the *delegatee*, to process the call in its place. In other words, the *delegator* publishes one or more of the *delegatee*'s methods as its own.

In Raku, delegation is specified by applying the [handles](/language/typesystem#trait_handles) trait to an attribute. The arguments provided to the trait specify the methods the object and the *delegatee* attribute will have in common. Instead of a list of method names, you can provide a [`Pair`](/type/Pair) (to rename; the key becomes the new name), a [`Regex`](/type/Regex) (to handle every method with a matching name), a [`Whatever`](/type/Whatever) (to delegate all methods that the attribute [can](/type/Metamodel/ClassHOW#method_can) call), or a [`HyperWhatever`](/type/HyperWhatever) (to delegate all method calls, even ones that will lead to the attribute's [FALLBACK](/routine/FALLBACK) method). You can also provide a [`List`](/type/List) providing any of those items to delegate multiple methods. Note that the [`Regex`](/type/Regex), [`Whatever`](/type/Whatever), and [`HyperWhatever`](/type/HyperWhatever) forms do not delegate any methods that the class has inherited (for example, from [`Any`](/type/Any) or [`Mu`](/type/Mu)) but that explicitly naming the method does delegate it.

```raku
class Book {
    has Str  $.title;
    has Str  $.author;
    has Str  $.language;
    has Cool $.publication;
}

class Product {
    has Book $.book handles('title', 'author', 'language', year => 'publication');
}

my $book = Book.new:
    :title<Dune>,
    :author('Frank Herbert'),
    :language<English>,
    :publication<1965>
;

given Product.new(:$book) {
    say .title;    # OUTPUT: «Dune␤»
    say .author;   # OUTPUT: «Frank Herbert␤»
    say .language; # OUTPUT: «English␤»
    say .year;     # OUTPUT: «1965␤»
}

```

In the example above, the class `Product` defines the attribute `$.book` and mark it with the `handles` trait to specify the methods that will be forwarded to the class `Book` whenever they're invoked on an instance object of the `Product` class. There are a few things to notice here:

* We didn't write any methods inside the `Product` class that we invoked in its instance object. Instead, we instructed the class to delegate a call to any those methods to the `Book` class.
* We've specified the method names `title`, `author`, and `language` as they appear in the `Book` class. On the other hand, we've renamed the `publication` method to `year` by providing the appropriate [`Pair`](/type/Pair).

Delegation can be used as an alternative to inheritance by delegating to the parent class and not inheriting all of its methods. For example, the following `Queue` class delegates several methods proper of queues to the [`Array`](/type/Array) class while also providing a preferred interface for a few of those methods (e.g., `enqueue` for `push`):

```raku
class Queue {
    has @!q handles(
        enqueue => 'push', dequeue => 'shift',
        'push', 'shift', 'head', 'tail', 'elems', 'splice'
    );

    method gist {
        '[' ~ @!q.join(', ') ~ ']'
    }
}

my Queue $q .= new;
$q.enqueue($_) for 1..5;
$q.push(6);
say $q.shift;                  # OUTPUT: «1␤»
say $q.dequeue while $q.elems; # OUTPUT: «2␤3␤4␤5␤6␤»

$q.enqueue($_) for <Perl Python Raku Ruby>;
say $q.head;                   # OUTPUT: «Perl␤»
say $q.tail;                   # OUTPUT: «Ruby␤»
say $q;                        # OUTPUT: «[Perl, Python, Raku, Ruby]␤»
$q.dequeue while $q.elems;
say $q;                        # OUTPUT: «[]␤»

```

## [Object construction](#Object_orientation "go to top of document")[§](#Object_construction "direct link")

Objects are generally created through method calls, either on the type object or on another object of the same type.

Class [`Mu`](/type/Mu) provides a constructor method called [new](/routine/new), which takes named [arguments](/language/functions#Arguments) and uses them to initialize public attributes.

```raku
class Point {
    has $.x;
    has $.y;
}
my $p = Point.new( x => 5, y => 2);
#             ^^^ inherited from class Mu
say "x: ", $p.x;
say "y: ", $p.y;
# OUTPUT: «x: 5␤»
# OUTPUT: «y: 2␤»

```

`Mu.new` calls method [bless](/routine/bless) on its invocant, passing all the named [arguments](/language/functions#Arguments). `bless` creates the new object, and then walks all subclasses in reverse method resolution order (i.e. from [`Mu`](/type/Mu) to most derived classes). In each class `bless` executes the following steps in the order given here:

* It checks for the existence of a method named `BUILD`. If the method exists, the method is called with all the named arguments it received (from the `new` method).
* If no `BUILD` method was found, the public attributes from this class are initialized from named arguments of the same name.
* All attributes that have not been touched in any of the previous steps have their default values applied:

  `has $.attribute = 'default value';`
* `TWEAK` is called should it exist. It will receive the same arguments `BUILD` receives.

This object construction scheme has several implications:

* Named arguments to the default `new` constructor (inherited from [`Mu`](/type/Mu)) can correspond directly to public attributes of any of the classes in the method resolution order, or to any named parameter of any `BUILD` or `TWEAK` submethod.
* Custom `BUILD` methods should always be submethods, otherwise they are inherited to subclasses and prevent default attribute initialization (item two in the above list) should the subclass not have its own `BUILD` method.
* `BUILD` may set an attribute, but it does not have access to the contents of the attribute declared as its default as they are only applied later. `TWEAK` on the other hand is called after default values have been applied and will thus find the attributes initialized. So it can be used to check things or modify attributes after object construction:

  Raku highlighting

  ```
  class RectangleWithCachedArea {
      has ($.x1, $.x2, $.y1, $.y2);
      has $.area;
      submethod TWEAK() {
          $!area = abs( ($!x2 - $!x1) * ( $!y2 - $!y1) );
      }
  }

  say RectangleWithCachedArea.new( x2 => 5, x1 => 1, y2 => 1, y1 => 0).area;
  # OUTPUT: «4␤»

  ```
* Since passing arguments to a routine binds the arguments to the parameters, one can simplify BUILD methods by using the attribute as a parameter.

  A class using ordinary binding in the `BUILD` method:

  Raku highlighting

  ```
  class Point {
      has $.x;
      has $.y;

      submethod BUILD(:$x, :$y) {
          $!x := $x;
          $!y := $y;
      }
  }
  my $p1 = Point.new( x => 10, y => 5 );

  ```

  The following `BUILD` method is equivalent to the above:

  Raku highlighting

  ```
  submethod BUILD(:$!x, :$!y) {
      # Nothing to do here anymore, the signature binding
      # does all the work for us.
  }

  ```
* In order to use default values together with a `BUILD()` method one can't use parameter binding of attributes, as that will always touch the attribute and thus prevent the automatic assignment of default values (step three in the above list). Instead one would need to conditionally assign the value:

  Raku highlighting

  ```
  class A {
      has $.attr = 'default';
      submethod BUILD(:$attr) {
          $!attr = $attr if defined $attr;
      }
  }
  say A.new(attr => 'passed').raku;
  say A.new().raku;
  # OUTPUT: «A.new(attr => "passed")␤»
  # OUTPUT: «A.new(attr => "default")␤»

  ```

  It's simpler to set a default value of the `BUILD` parameter instead though:

  Raku highlighting

  ```
  class A {
      has $.attr;
      submethod BUILD(:$!attr = 'default') {}
  }

  ```
* Be careful when using parameter binding of attributes when the attribute has a special type requirement such as an [`Int`](/type/Int) type. If `new` is called without this parameter, then a default of [`Any`](/type/Any) will be assigned, which will cause a type error. The easy fix is to add a default value to the `BUILD` parameter.

  Raku highlighting

  ```
  class A {
      has Int $.attr;
      submethod BUILD(:$!attr = 0) {}
  }
  say A.new(attr => 1).raku;
  say A.new().raku;
  # OUTPUT: «A.new(attr => 1)␤»
  # OUTPUT: «A.new(attr => 0)␤»

  ```
* `BUILD` allows to create aliases for attribute initialization:

  Raku highlighting

  ```
  class EncodedBuffer {
      has $.enc;
      has $.data;

      submethod BUILD(:encoding(:$!enc), :$!data) { }
  }
  my $b1 = EncodedBuffer.new( encoding => 'UTF-8', data => [64, 65] );
  my $b2 = EncodedBuffer.new( enc      => 'UTF-8', data => [64, 65] );
  #  both enc and encoding are allowed now

  ```
* Note that the name `new` is not special in Raku. It is merely a common convention, one that is followed quite thoroughly in [most Raku classes](/routine/new). You can call `bless` from any method, or use `CREATE` to fiddle around with low-level workings.
* If you want a constructor that accepts positional arguments, you must write your own `new` method:

  Raku highlighting

  ```
  class Point {
      has $.x;
      has $.y;
      method new($x, $y) {


## objects.md
## Chunk 2 of 2
 self.bless(:$x, :$y);
      }
  }

  ```

  Do note, however, that `new` is a normal method and not involved in any of the construction process of `bless`. So any logic placed in the `new` method will not be called when using a different `new` method or a `new` of a subclass.

  Raku highlighting

  ```
  class Vector {
      has $.x;
      has $.y;
      has $.length;
      method new($x, $y) {
          self.bless(:$x, :$y, length => sqrt($x**2 * $y**2));
      }
  }

  class NamedVector is Vector {
      has $.name;
      method new($name, $x, $y) {
          self.bless(:$name, :$x, :$y);
      }
  }

  my $v = Vector.new: 3, 4;
  say $v.length; # OUTPUT: «5␤»

  my $f = NamedVector.new: 'Francis', 5, 12;
  say $f.length; # OUTPUT: «(Any)␤»

  ```

Here is an example where we *enrich* the [`Str`](/type/Str) class with an auto-incrementing ID:

```raku
class Str-with-ID is Str {
    my $counter = 0;
    has Int $.ID  is rw = 0;

    multi method new( $str ) {
        self.bless( value => $str );
    }
    submethod BUILD( :$!ID = $counter++ ) {}
}

say Str-with-ID.new("1.1,2e2").ID;                  # OUTPUT: «0␤»
my $enriched-str = Str-with-ID.new("3,4");
say "$enriched-str, {$enriched-str.^name}, {$enriched-str.ID}";
# OUTPUT: «3,4, Str-with-ID, 1␤»

```

We create a custom `new` since we want to be able to be able to initialize our new class with a bare string. `bless` will call `Str.BUILD` which will *capture* the value it's looking for, the pair `value => $str` and initialize itself. But we have to also initialize the properties of the subclass, which is why within `BUILD` we initialize `$.ID`. As seen in the output, the objects will be correctly initialized with an ID and can be used just like a normal [`Str`](/type/Str).

## [Object cloning](#Object_orientation "go to top of document")[§](#Object_cloning "direct link")

The cloning is done using the [clone](/routine/clone) method available on all objects, which shallow-clones both public and private attributes. New values for *public* attributes can be supplied as named arguments.

```raku
class Foo {
    has $.foo = 42;
    has $.bar = 100;
}

my $o1 = Foo.new;
my $o2 = $o1.clone: :bar(5000);
say $o1; # OUTPUT: «Foo.new(foo => 42, bar => 100)␤»
say $o2; # OUTPUT: «Foo.new(foo => 42, bar => 5000)␤»

```

See document for [clone](/routine/clone) for details on how non-scalar attributes get cloned, as well as examples of implementing your own custom clone methods.

# [Roles](#Object_orientation "go to top of document")[§](#Roles "direct link")

Roles are a collection of attributes and methods; however, unlike classes, roles are meant for describing only parts of an object's behavior; this is why, in general, roles are intended to be *mixed in* classes and objects. In general, classes are meant for managing objects and roles are meant for managing behavior and code reuse within objects.

Roles use the keyword `role` preceding the name of the role that is declared. Roles are mixed in using the `does` keyword preceding the name of the role that is mixed in.

Roles can also be mixed into a class using `is`. However, the semantics of `is` with a role are quite different from those offered by `does`. With `is`, a class is punned from the role, and then inherited from. Thus, there is no flattening composition, and none of the safeties which `does` provides.

```raku
constant ⲧ = " " xx 4; #Just a ⲧab
role Notable {
    has Str $.notes is rw;

    multi method notes() { "$!notes\n" };
    multi method notes( Str $note ) { $!notes ~= "$note\n" ~ ⲧ };

}

class Journey does Notable {
    has $.origin;
    has $.destination;
    has @.travelers;

    method Str { "⤷ $!origin\n" ~ ⲧ ~ self.notes() ~ "$!destination ⤶\n" };
}

my $trip = Journey.new( :origin<Here>, :destination<There>,
                        travelers => <þor Freya> );

$trip.notes("First steps");
notes $trip: "Almost there";
print $trip;
# OUTPUT:
#⤷ Here
#       First steps
#       Almost there
#
#There ⤶

```

Roles are immutable as soon as the compiler parses the closing curly brace of the role declaration.

## [Applying roles](#Object_orientation "go to top of document")[§](#Applying_roles "direct link")

Role application differs significantly from class inheritance. When a role is applied to a class, the methods of that role are copied into the class. If multiple roles are applied to the same class, conflicts (e.g. attributes or non-multi methods of the same name) cause a compile-time error, which can be solved by providing a method of the same name in the class.

This is much safer than multiple inheritance, where conflicts are never detected by the compiler, but are instead resolved to the superclass that appears earlier in the method resolution order, which might not be what the programmer wanted.

For example, if you've discovered an efficient method to ride cows, and are trying to market it as a new form of popular transportation, you might have a class `Bull`, for all the bulls you keep around the house, and a class `Automobile`, for things that you can drive.

```raku
class Bull {
    has Bool $.castrated = False;
    method steer {
        # Turn your bull into a steer
        $!castrated = True;
        return self;
    }
}
class Automobile {
    has $.direction;
    method steer($!direction) { }
}
class Taurus is Bull is Automobile { }

my $t = Taurus.new;
say $t.steer;
# OUTPUT: «Taurus.new(castrated => Bool::True, direction => Any)␤»

```

With this setup, your poor customers will find themselves unable to turn their Taurus and you won't be able to make more of your product! In this case, it may have been better to use roles:

```raku
role Bull-Like {
    has Bool $.castrated = False;
    method steer {
        # Turn your bull into a steer
        $!castrated = True;
        return self;
    }
}
role Steerable {
    has Real $.direction;
    method steer(Real $d = 0) {
        $!direction += $d;
    }
}
class Taurus does Bull-Like does Steerable { }

```

This code will die with something like:

｢text｣ without highlighting

```

```

===SORRY!===
Method 'steer' must be resolved by class Taurus because it exists in
multiple roles (Steerable, Bull-Like)

```

```

This check will save you a lot of headaches:

```raku
class Taurus does Bull-Like does Steerable {
    method steer($direction?) {
        self.Steerable::steer($direction)
    }
}

```

When a role is applied to a second role, the actual application is delayed until the second role is applied to a class, at which point both roles are applied to the class. Thus

```raku
role R1 {
    # methods here
}
role R2 does R1 {
    # methods here
}
class C does R2 { }

```

produces the same class `C` as

```raku
role R1 {
    # methods here
}
role R2 {
    # methods here
}
class C does R1 does R2 { }

```

## [Stubs](#Object_orientation "go to top of document")[§](#Stubs "direct link")

When a role contains a stubbed method, that is, a method whose code is limited to `...`, a non-stubbed version of a method of the same name must be supplied at the time the role is applied to a class. This allows you to create roles that act as abstract interfaces.

```raku
role AbstractSerializable {
    method serialize() { ... }        # literal ... here marks the
                                      # method as a stub
}

# the following is a compile time error, for example
#        Method 'serialize' must be implemented by Point because
#        it's required by a role

class APoint does AbstractSerializable {
    has $.x;
    has $.y;
}

# this works:
class SPoint does AbstractSerializable {
    has $.x;
    has $.y;
    method serialize() { "p($.x, $.y)" }
}

```

The implementation of the stubbed method may also be provided by another role.

## [Inheritance](#Object_orientation "go to top of document")[§](#Inheritance_0 "direct link")

Roles cannot inherit from classes, but they may *carry* classes, causing any class which does that role to inherit from the carried classes. So if you write:

```raku
role A is Exception { }
class X::Ouch does A { }
X::Ouch.^parents.say # OUTPUT: «((Exception))␤»

```

then `X::Ouch` will inherit directly from Exception, as we can see above by listing its parents.

As they do not use what can properly be called inheritance, roles are not part of the class hierarchy. Roles are listed with the `.^roles` metamethod instead, which uses `transitive` as flag for including all levels or just the first one. Despite this, a class or instance may still be tested with smartmatches or type constraints to see if it does a role.

```raku
role F { }
class G does F { }
G.^roles.say;                    # OUTPUT: «((F))␤»
role Ur {}
role Ar does Ur {}
class Whim does Ar {}; Whim.^roles(:!transitive).say;   # OUTPUT: «((Ar))␤»
say G ~~ F;                      # OUTPUT: «True␤»
multi a (F $a) { "F".say }
multi a ($a)   { "not F".say }
a(G);                            # OUTPUT: «F␤»

```

## [Pecking order](#Object_orientation "go to top of document")[§](#Pecking_order "direct link")

A method defined directly in a class will always override definitions from applied roles or from inherited classes. If no such definition exists, methods from roles override methods inherited from classes. This happens both when said class was brought in by a role, and also when said class was inherited directly.

```raku
role M {
  method f { say "I am in role M" }
}

class A {
  method f { say "I am in class A" }
}

class B is A does M {
  method f { say "I am in class B" }
}

class C is A does M { }

B.new.f; # OUTPUT: «I am in class B␤»
C.new.f; # OUTPUT: «I am in role M␤»

```

Note that each candidate for a multi-method is its own method. In this case, the above only applies if two such candidates have the same signature. Otherwise, there is no conflict, and the candidate is just added to the multi-method.

## [Automatic role punning](#Object_orientation "go to top of document")[§](#Automatic_role_punning "direct link")

Any attempt to directly instantiate a role or use it as a type object will automatically create a class with the same name as the role, making it possible to transparently use a role as if it were a class.

```raku
role Point {
    has $.x;
    has $.y;
    method abs { sqrt($.x * $.x + $.y * $.y) }
    method dimensions { 2 }
}
say Point.new(x => 6, y => 8).abs; # OUTPUT: «10␤»
say Point.dimensions;              # OUTPUT: «2␤»

```

We call this automatic creation of classes *punning*, and the generated class a *pun*.

Punning is not caused by most [metaprogramming](/language/mop) constructs, however, as those are sometimes used to work directly with roles.

## [Parameterized roles](#Object_orientation "go to top of document")[§](#Parameterized_roles "direct link")

Roles can be parameterized, by giving them a signature in square brackets:

```raku
role BinaryTree[::Type] {
    has BinaryTree[Type] $.left;
    has BinaryTree[Type] $.right;
    has Type $.node;

    method visit-preorder(&cb) {
        cb $.node;
        for $.left, $.right -> $branch {
            $branch.visit-preorder(&cb) if defined $branch;
        }
    }
    method visit-postorder(&cb) {
        for $.left, $.right -> $branch {
            $branch.visit-postorder(&cb) if defined $branch;
        }
        cb $.node;
    }
    method new-from-list(::?CLASS:U: *@el) {
        my $middle-index = @el.elems div 2;
        my @left         = @el[0 .. $middle-index - 1];
        my $middle       = @el[$middle-index];
        my @right        = @el[$middle-index + 1 .. *];
        self.new(
            node    => $middle,
            left    => @left  ?? self.new-from-list(@left)  !! self,
            right   => @right ?? self.new-from-list(@right) !! self,
        );
    }
}

my $t = BinaryTree[Int].new-from-list(4, 5, 6);
$t.visit-preorder(&say);    # OUTPUT: «5␤4␤6␤»
$t.visit-postorder(&say);   # OUTPUT: «4␤6␤5␤»

```

Here the signature consists only of a type capture, but any signature will do:

```raku
enum Severity <debug info warn error critical>;

role Logging[$filehandle = $*ERR] {
    method log(Severity $sev, $message) {
        $filehandle.print("[{uc $sev}] $message\n");
    }
}

Logging[$*OUT].log(debug, 'here we go'); # OUTPUT: «[DEBUG] here we go␤»

```

You can have multiple roles of the same name, but with different signatures; the normal rules of multi dispatch apply for choosing multi candidates.

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

Roles can be mixed into objects. A role's given attributes and methods will be added to the methods and attributes the object already has. Multiple mixins and anonymous roles are supported.

```raku
role R { method Str() {'hidden!'} };
my $i = 2 but R;
sub f(\bound){ put bound };
f($i); # OUTPUT: «hidden!␤»
my @positional := <a b> but R;
say @positional.^name; # OUTPUT: «List+{R}␤»

```

Note that the object got the role mixed in, not the object's class or the container. Thus, @-sigiled containers will require binding to make the role stick as is shown in the example with `@positional`. Some operators will return a new value, which effectively strips the mixin from the result. That is why it might be more clear to mix in the role in the declaration of the variable using `does`:

```raku
role R {};
my @positional does R = <a b>;
say @positional.^name; # OUTPUT: «Array+{R}␤»

```

The operator `infix:<but>` is narrower than the list constructor. When providing a list of roles to mix in, always use parentheses.

```raku
role R1 { method m {} }
role R2 { method n {} }
my $a = 1 but R1,R2; # R2 is in sink context, issues a WARNING
say $a.^name;
# OUTPUT: «Int+{R1}␤»
my $all-roles = 1 but (R1,R2);
say $all-roles.^name; # OUTPUT: «Int+{R1,R2}␤»

```

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

```raku
role Named {
    has $.name;
}
my $hero = 1.Rat but Named('Remy');
say $hero.name;     # OUTPUT: «Remy␤»

```

Mixins can be used at any point in your object's life.

```raku
# A counter for Table of Contents
role TOC-Counter {
    has Int @!counters is default(0);
    method Str() { @!counters.join: '.' }
    method inc($level) {
        @!counters[$level - 1]++;
        @!counters.splice($level);
        self
    }
}

my Num $toc-counter = NaN;     # don't do math with Not A Number
say $toc-counter;              # OUTPUT: «NaN␤»
$toc-counter does TOC-Counter; # now we mix the role in
$toc-counter.inc(1).inc(2).inc(2).inc(1).inc(2).inc(2).inc(3).inc(3);
put $toc-counter / 1;          # OUTPUT: «NaN␤» (because that's numerical context)
put $toc-counter;              # OUTPUT: «2.2.2␤» (put will call TOC-Counter::Str)

```

Roles can be anonymous.

```raku
my %seen of Int is default(0 but role :: { method Str() {'NULL'} });
say %seen<not-there>;          # OUTPUT: «NULL␤»
say %seen<not-there>.defined;  # OUTPUT: «True␤» (0 may be False but is well defined)
say Int.new(%seen<not-there>); # OUTPUT: «0␤»

```

# [Metaobject programming and introspection](#Object_orientation "go to top of document")[§](#Metaobject_programming_and_introspection "direct link")

Raku has a metaobject system, which means that the behavior of objects, classes, roles, grammars, enums, etc. are themselves controlled by other objects; those objects are called *metaobjects*. Metaobjects are, like ordinary objects, instances of classes, in this case we call them *metaclasses*.

For each object or class you can get the metaobject by calling `.HOW` on it. Note that although this looks like a method call, it works more like a macro.

So, what can you do with the metaobject? For one you can check if two objects have the same metaclass by comparing them for equality:

```raku
say 1.HOW ===   2.HOW;      # OUTPUT: «True␤»
say 1.HOW === Int.HOW;      # OUTPUT: «True␤»
say 1.HOW === Num.HOW;      # OUTPUT: «False␤»

```

Raku uses the word *HOW* (Higher Order Workings) to refer to the metaobject system. Thus it should be no surprise that in Rakudo, the class name of the metaclass that controls class behavior is called `Perl6::Metamodel::ClassHOW`. For each class there is one instance of `Perl6::Metamodel::ClassHOW`.

But the metamodel does much more for you. For example, it allows you to introspect objects and classes. The calling convention for methods on metaobjects is to call the method on the metaobject and pass in the object of interest as first argument to the object. So to get the name of the class of an object, you could write:

```raku
my $object = 1;
my $metaobject = 1.HOW;
say $metaobject.name($object);      # OUTPUT: «Int␤»

# or shorter:
say 1.HOW.name(1);                  # OUTPUT: «Int␤»

```

(The motivation is that Raku also wants to allow a more prototype-based object system, where it's not necessary to create a new metaobject for every type).

There's a shortcut to keep from using the same object twice:

```raku
say 1.^name;                        # OUTPUT: «Int␤»
# same as
say 1.HOW.name(1);                  # OUTPUT: «Int␤»

```

See [`Metamodel::ClassHOW`](/type/Metamodel/ClassHOW) for documentation on the metaclass of `class` and also the [general documentation on the metaobject protocol](/language/mop).


## dist_zef-jonathanstowe-Unix-Groups.md
# Unix::Groups

Access to the Unix group file in Raku

![Build Status](https://github.com/jonathanstowe/Unix-Groups/workflows/CI/badge.svg)

## Synopsis

```
use Unix::Groups;

my $groups = Unix::Groups.new;

say "The logged in user is member of these groups:";

for $groups.groups-for-user($*USER.Str) -> $group {
	say $group.name;
}

```

## Description

This module provides access to the group details from `/etc/group`,
with similar to `getgrent()`, `getgrnam` and `getgrgid`
in the Unix standard C library.

The methods either return a Unix::Groups::Group object or an array of
those objects.

Because this module goes directly to the group file, if your system is
configured to retrieve its group information from e.g. NIS or LDAP it
may not necessarily reflect all the groups present, just the local ones.

## 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 User::Groups

```

## Support

Suggestions/patches are welcomed via github at <https://github.com/jonathanstowe/User-Groups/issues>

## Licence

This is free software.

Please see the <LICENCE> file in the distribution

© Jonathan Stowe 2015 - 2021


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

# NAME

Test::IO::Socket::Async - A test double for IO::Socket::Async

# SYNOPSIS

```
use Test::IO::Socket::Async;

```

# DESCRIPTION

Test::IO::Socket::Async is provides the same API as `IO::Socket::Async` but for testing. See the [associated blog post](https://6guts.wordpress.com/2016/01/06/not-guts-but-6-part-3/) for more information.

# AUTHOR

Jonathan Worthington

# COPYRIGHT AND LICENSE

Copyright 2016 - 2017 Jonathan Worthington

Copyright 2024, 2025 Raku Community

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


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

# NAME

snip - Provide functionality similar to Haskell's span

# SYNOPSIS

```
use snip;

.say for snip * < 10, 2, 2, 2, 5, 5, 7, 13, 9, 6, 2, 20, 4;
# (2 2 2 5 5 7)
# (13 9 6 2 20 4)

.say for snip (* < 10, * < 20), 2, 2, 2, 5, 5, 7, 13, 9, 6, 2, 20, 4;
# (2 2 2 5 5 7)
# (13 9 6 2)
# (20 4)

.say for snip Int, 2, 2, 2, 5, 5, "a", "b", "c";
# (2 2 2 5 5)
# (a b c)

```

# DESCRIPTION

The `snip` distribution exports a single subroutine `snip` that mimics the functionality provided by [Haskell's span functionality](https://hackage.haskell.org/package/base-4.16.1.0/docs/Prelude.html#v:snip). But only if the core does not supply a `snip` subroutine already (which it may at some point in the future).

The `snip` subroutine takes a matcher much like `grep` does, which can be a `Callable` or any other object that can have the `ACCEPTS` method called on it. Different from the Haskell's `span` implementation, `snip` can take multiple matchers to snip the origin list in more than 2 parts.

# AUTHOR

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

Source can be located at: <https://github.com/lizmat/snip> . 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, 2024 Elizabeth Mattijsen

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


## dist_zef-raku-community-modules-IO-Dir.md
[![Build Status](https://travis-ci.org/zoffixznet/perl6-IO-Dir.svg)](https://travis-ci.org/zoffixznet/perl6-IO-Dir)

# NAME

IO::Dir - IO::Path.dir you can close

# SYNOPSIS

```
    # Won't always suit, since non-exhausted iterator holds on to an open
    # file descriptor until GC:
    'foo'.IO.dir[^3].say;

    # all good; we explicitly close the file descriptor when done
    .dir[^3].say and .close with IO::Dir.open: 'foo';

```

# DESCRIPTION

[`IO::Path.dir`](https://docs.raku.org/routine/dir) does the job well for
most cases, however, there's an edge case where it's no good:

* You don't exhaust or [eagerly](https://docs.raku.org/routine/eager)
  evaluate the `Seq` `dir` returns
* You do that enough times in some tight loop that
  [GC](https://en.wikipedia.org/wiki/Garbage_collection_(computer_science))
  doesn't get a chance to clean up unreachable `dir` `Seq`s; or
* You run this on some system with tight open file limits

If you're in that category, then good news! `IO::Dir` gives you a `dir` whose
file descriptor you can close without relying on GC or having to [fully
reify](https://docs.raku.org/language/glossary#index-entry-Reify)
the dir's `Seq`.

# METHODS

## `.new`

Creates a new `IO::Dir` object. Takes no args.

## `.open`

Opens for reading directory given as a positional argument, which can be
any object that can be coerced to `IO::Path` via `.IO` method. Defaults to
opening `'.'` directory.

Will first `.close` the invocant if it was previously opened.

```
    $dir1.open;
    $dir2.open: 'foo';

```

## `.dir`

Takes similar arguments as
[`IO::Path.dir`](https://docs.raku.org/routine/dir), that have the same
meaning, returning the same type of `Seq`. Will `.close` the invocant when
the result is exhausted.

The additional arguments are boolean `:absolute` and `:Str` that control whether to return absolute paths when dir was opened via an absolute path and whether to
return paths as `IO::Path` or `Str` objects.

**Note:** you cannot call `.dir` more than once; re-open the
invocant or create a new `IO::Dir` if you need that. Will die if called on
an un-opened `IO::Dir`.

```
    # Explicit close:
    .dir[^3].say and .close with IO::Dir.open: 'foo';

    # Implicit close (arrays are mostly-eager, so our Seq is exhausted here)
    my @files = IO::Dir.open('foo').dir;

```

## `.close`

Closes an open `IO::Dir`, freeing the file descriptor.

```
    .dir[^3].say and .close with IO::Dir.open: 'foo';

```

---

#### REPOSITORY

Fork this module on GitHub:
<https://github.com/raku-community-modules/IO-Dir>

#### BUGS

To report bugs or request features, please use
<https://github.com/raku-community-modules/IO-Dir/issues>

#### AUTHOR

Zoffix Znet (<http://perl6.party/>)

#### LICENSE

You can use and distribute this module under the terms of the
The Artistic License 2.0. See the `LICENSE` file included in this
distribution for complete details.

The `META6.json` file of this distribution may be distributed and modified
without restrictions or attribution.


## subst.md
subst

Combined from primary sources listed below.

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

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

```raku
multi method subst(Str:D: $matcher, $replacement = "", *%options)
```

Returns the invocant string where `$matcher` is replaced by `$replacement` (or the original string, if no match was found). If no `$replacement` is provided, the empty string is used (i.e., matched string(s) are removed).

There is an in-place syntactic variant of `subst` spelled `s/matcher/replacement/` and with adverb following the `s` or inside the matcher.

`$matcher` can be a [`Regex`](/type/Regex), or a literal `Str`. Non-Str matcher arguments of type [`Cool`](/type/Cool) are coerced to `Str` for literal matching. If a [`Regex`](/type/Regex) `$matcher` is used, the [`$/` special variable](/syntax/$$SOLIDUS) will be set to [`Nil`](/type/Nil) (if no matches occurred), a [`Match`](/type/Match) object, or a [`List`](/type/List) of [`Match`](/type/Match) objects (if multi-match options like `:g` are used).

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

See primary documentation
[in context](/type/Allomorph#method_subst)
for **method subst**.

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

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

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

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

```raku
method subst(|)
```

Coerces the invocant to [`Stringy`](/type/Stringy) and calls [Str.subst](/type/Str#method_subst).


## dist_zef-elcaro-Math-Combinatorics.md
# Math::Combinatorics

This module provides a few functions for generating combinatoric sequences.

## USAGE

The functions in this module can be selectively imported, eg.

```
use Math::Combinatorics < multicombinations variations >;

```

Or you can import everything with the `:ALL` tag

```
use Math::Combinatorics :ALL;

```

## FUNCTIONS

### multicombinations

Also known as 'combinations with replacement', 'k-multicombinations', or 'multisubsets'

```
say multicombinations(<A B C D>, 2);
# OUTPUT: ((A A) (A B) (A C) (A D) (B B) (B C) (B D) (C C) (C D) (D D))

```

> Implemented in NQP

### variations

Also known as 'k-permutations of n'. I opted to give this the more archaic name of `variations` rather than creating a multi of `permutations`.

```
say variations(<A B C D>, 2);
# OUTPUT: ((A B) (A C) (A D) (B A) (B C) (B D) (C A) (C B) (C D) (D A) (D B) (D C))

```

> Implemented in NQP

### partitions

Also known as 'integer partitions'.

```
say partitions(5);
# OUTPUT: ((1 1 1 1 1) (1 1 1 2) (1 1 3) (1 2 2) (1 4) (2 3) (5))

```

> Implemented in NQP

### derangements

Essentially the permutations where no element is in it's original place

```
say derangements(<A B C D>)
# OUTPUT: ((B A D C) (B C D A) (B D A C) (C A D B) (C D A B) (C D B A) (D A B C) (D C A B) (D C B A))

```

> implemented in Raku

### factorial and subfactorial

Since several functions rely on getting the factorial (or subfactorial) of a number, I have those functions defined as well.

```
say factorial(6);     # OUTPUT: 720
say subfactorial(6);  # OUTPUT: 256

```

## NOTES

The goal of this module is to be something similar to Perl's [Algorithm::Combinatorics](https://metacpan.org/pod/Algorithm::Combinatorics), implemented in NQP for fast performance. Not all functions are implemented in NQP, and if there's a function you'd like to add, I'm happy to accept pull requests for more algorithms, even in pure Raku. I - or others - can always work towards translating them to NQP later as time permits.

## CAVEATS & LIMITATIONS

I held off on publishing this module for many years because I wanted to polish it, provide more functions, and implement faster `.skip` on things like `permutations` (where the n-th permutation in a sequence can be determined algorithmically). Unfortunately, I have learned that my life doesn't always permit the long periods of time to dedicate to this.

My skill with NQP is that of a amateur, so I may not have written the *most* efficient code, however the implementations written in NQP should at least be noticeably faster than most pure-Raku functions implementing the same algorithms.

As always - pull requests are welcome, both for new functions, and improvements to the existing ones.

## LICENSE

```
The Artistic License 2.0

```

See LICENSE file in the repository for the full license text.


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

# NAME

Hash::int - provide a hash with native integer keys

# SYNOPSIS

```
use Hash::int;

my %hash is Hash::int = 42 => "foo", 666 => "bar";

```

# DESCRIPTION

Hash::int is module that provides the `Hash::int` class to be applied to the initialization of an Associative, making it limit the keys to native integers that fit the `int` type. This allows this module to take some shortcuts, making it up to **7x** as fast as a normal hash.

# AUTHOR

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

Source can be located at: <https://github.com/lizmat/Hash-int> . 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 2021, 2024, 2025 Elizabeth Mattijsen

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


## dist_github-MattOates-Text-Emotion.md
# Text::Emotion [Build Status](https://travis-ci.org/MattOates/Text--Emotion)

Perl6 package for scoring the emotional content of a piece of text from its word use.

# Sentiment Data

Currently the AFINN data set from Twitter usage is used to give base word scores for sentiment.
<https://github.com/fnielsen/afinn>

AFINN is a list of English words rated for valence with an integer between minus five (negative) and plus five (positive). The words have been manually labeled by Finn Årup Nielsen in 2009-2011. The file is tab-separated.

# Example Use

'emobot' included is an example IRC bot using Text::Emotion::Scorer and Net::IRC::Bot.

```
#!/usr/bin/env perl6
use v6;

#Create a Scorer object and all of the sentiment data is loaded for your use
use Text::Emotion::Scorer;
my $emotion = Text::Emotion::Scorer.new;

#Score a whole passage of positive sounding text
say $emotion.score("I really love Perl6. Hurrah!");

#Score a whole passage of negative sounding text
say $emotion.score("I hate Monday's they suck!");

#Just get the word scores the passage score is working with
say $emotion.score_word("failure");

```


## dist_zef-raku-community-modules-JSON-Pretty.md
[![Actions Status](https://github.com/raku-community-modules/JSON-Pretty/workflows/test/badge.svg)](https://github.com/raku-community-modules/JSON-Pretty/actions)

# NAME

JSON::Pretty - A JSON (de)serializer that produces easily readable JSON

# SYNOPSIS

```
use JSON::Pretty;
my $json = to-json([1, 2, "a third item"]);
my $copy-of-original-data-structure = from-json($json);

```

# DESCRIPTION

A simple Raku module for serializing and deserializing JSON, with the difference that produced JSON is indented. Its goal is to be readable especially for debugging purposes.

This module exposes the same API as `JSON::Fast`, so all you have to do to switch between both is to change your `use` statement.

All files (unless noted otherwise) can be used, modified and redistributed under the terms of the Artistic License Version 2. Examples (in the documentation, in tests or distributed as separate files) can be considered public domain.

# CREDITS

Moritz Lenz Johan Viklund Jonathan Worthington

# AUTHOR

Tobias Leich (FROGGS)

Source can be located at: <https://github.com/raku-community-modules/JSON-Pretty> . Comments and Pull Requests are welcome.

# COPYRIGHT AND LICENSE

Copyright 2013, 2015, 2016, 2017 Tobias Leich, 2023 Raku Community

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


## dist_github-cosimo-Digest-MD5.md
## Perl6 Digest::MD5 module

An interface-compatible port of
[Perl 5 Digest::MD5](https://metacpan.org/pod/Digest::MD5) to Perl 6.

Cosimo Streppone ([cosimo@cpan.org](mailto:cosimo@cpan.org))

### Synopsis

```
    use Digest::MD5;
    say Digest::MD5.new.md5_hex("My awesome data to hash");

```

### Methods

#### `new`

```
    my $d = Digest::MD5.new;

```

Returns a new `Digest::MD5` object.

#### `md5_hex`

```
    my $md5_hash = $d.md5_hex('data');

    my @data = "one", "two", "and more";
    my $md5_hash = $d.md5_hex( @data );

    # returns string '009ef1defa9fa27032f9f52cdeda8698'

```

Takes either a string or an array as the argument and returns MD5 hash
as a hex string.

#### `md5_buf`

```
    my $md5_buf = $d.md5_buf('data');

    # returns Buf:0x<8d 77 7f 38 5d 3d fe c8 81 5d 20 f7 49 60 26 dc>

```

Takes same arguments as `md5_hex`, except returns a
[Buf](http://docs.perl6.org/type/Buf) instead of a string.

### Subroutines

### `Digest::MD5::md5`

```
my $data = $str.encode('ascii');
my $md5_buf = Digest::MD5::md5($data);

    # returns Buf:0x<8d 77 7f 38 5d 3d fe c8 81 5d 20 f7 49 60 26 dc>

```

Takes a buffer or array as an argument. Returns a [Buf](http://docs.perl6.org/type/Buf).

### Repository

<http://github.com/cosimo/perl6-digest-md5>

### Current status (2012-01-31)

Should work with latest (2012.01) release
of Rakudo, the "nom" branch-based version.


## dist_zef-thundergnat-Terminal-Boxer.md
[![Actions Status](https://github.com/thundergnat/Terminal-Boxer/actions/workflows/test.yml/badge.svg)](https://github.com/thundergnat/Terminal-Boxer/actions)

# NAME

Terminal::Boxer - Draw boxed tables in a terminal.

# SYNOPSIS

```
use Terminal::Boxer;

say ss-box(:3col, :3cw, :indent("  "), 'A'..'E')

#`[
  ┌───┬───┬───┐
  │ A │ B │ C │
  ├───┼───┼───┤
  │ D │ E │   │
  └───┴───┴───┘
]

say dd-box( :8cw, :4ch, :indent("  "), ( "one of\nthese", "\nthings\nis not", "\nlike\nthe\nothers" ) );

#`[
  ╔════════╦════════╦════════╗
  ║ one of ║        ║        ║
  ║  these ║ things ║  like  ║
  ║        ║ is not ║   the  ║
  ║        ║        ║ others ║
  ╚════════╩════════╩════════╝
]

```

# DESCRIPTION

Use Terminal::Boxer to easily generate "boxed" ASCII tables primarily for display in a terminal.

Has multiple pre-made subs using standard line drawing characters as well as a few non line drawing options. Provide your own drawing characters or rendering routine if desired.

## Premade Routines

All of the premade routines take several optional parameters to specify layout and behavior:

* :&f - Optional routine to render the text inside each cell. By default this is a centering routine. Pass in a specialized routine if (for instance) you want to use ANSI color codes but don't want to count the ANSI as characters.
* :col - Optional, number of columns to render the table in. Defaults to the number of elements in @content.
* :cw - Optional, cell width in characters. If none provided, uses the maximum width element size from the given content list. If too small a :cw is provided, will not truncate, will distort table.
* :ch - Optional, cell height in characters. If none provided, uses the maximum height (lines) element size from the given content list. If :ch is provided, will truncate excess lines to that height.
* :indent - Optional indent for the rendered table. Defaults to ''. Pass in a value to prepend to each row of the table. (Nominally, but not necessarily, whitespace.)
* @content - List or array. The actual content rendered to each cell.

If :cols (columns) is not specified, draws a single row table. If @content.elems is not evenly divisible by :cols, pads table with blank cells.

Multi line cells are always rendered top biased. If you want to center or bottom bias the contents, it is up to you to pad the content with blank lines to properly locate it.

--

`ss-box(:3col, :3cw, :indent(" "), 'A'..'E')` single horizontal, single vertical

```
┌───┬───┬───┐
│ A │ B │ C │
├───┼───┼───┤
│ D │ E │   │
└───┴───┴───┘

```

--

`rs-box(:3col, :3cw, :indent(" "), 'A'..'E')` rounded corner, single horizontal, single vertical

```
╭───┬───┬───╮
│ A │ B │ C │
├───┼───┼───┤
│ D │ E │   │
╰───┴───┴───╯

```

--

`hs-box(:3col, :3cw, :indent(" "), 'A'..'E')` heavy single horizontal, heavy single vertical

```
┏━━━┳━━━┳━━━┓
┃ A ┃ B ┃ C ┃
┣━━━╋━━━╋━━━┫
┃ D ┃ E ┃   ┃
┗━━━┻━━━┻━━━┛

```

--

`hl-box(:3col, :3cw, :indent(" "), 'A'..'E')` heavy single horizontal, light single vertical

```
┍━━━┯━━━┯━━━┑
│ A │ B │ C │
┝━━━┿━━━┿━━━┥
│ D │ E │   │
┕━━━┷━━━┷━━━┙

```

--

`lh-box(:3col, :3cw, :indent(" "), 'A'..'E')` light single horizontal, heavy single vertical

```
┎───┰───┰───┒
┃ A ┃ B ┃ C ┃
┠───╂───╂───┨
┃ D ┃ E ┃   ┃
┖───┸───┸───┚

```

--

`sd-box(:3col, :3cw, :indent(" "), 'A'..'E')` single horizontal, double vertical

```
╓───╥───╥───╖
║ A ║ B ║ C ║
╟───╫───╫───╢
║ D ║ E ║   ║
╙───╨───╨───╜

```

--

`ds-box(:3col, :3cw, :indent(" "), 'A'..'E')` double horizontal, single vertical

```
╒═══╤═══╤═══╕
│ A │ B │ C │
╞═══╪═══╪═══╡
│ D │ E │   │
╘═══╧═══╧═══╛

```

--

`dd-box(:3col, :3cw, :indent(" "), 'A'..'E')` double horizontal, double vertical

```
╔═══╦═══╦═══╗
║ A ║ B ║ C ║
╠═══╬═══╬═══╣
║ D ║ E ║   ║
╚═══╩═══╩═══╝

```

--

`ascii-box(:3col, :3cw, :indent(" "), 'A'..'E')` basic ASCII drawing characters

```
+---+---+---+
| A | B | C |
+---+---+---+
| D | E |   |
+---+---+---+

```

--

`block-box(:3col, :3cw, :indent(" "), 'A'..'E')` heavy block drawing characters

```
▉▉▉▉▉▉▉▉▉▉▉▉▉
▉ A ▉ B ▉ C ▉
▉▉▉▉▉▉▉▉▉▉▉▉▉
▉ D ▉ E ▉   ▉
▉▉▉▉▉▉▉▉▉▉▉▉▉

```

--

`no-box(:3col, :3cw, :indent(" "), 'A'..'E')` spaces

```
A   B   C

D   E

```

### Roll your own.

`draw(:$draw, :&f, :$col, :$cw, :$ch, :$indent, *@content)` The basic drawing routine

If you need ultimate control, supply your own drawing characters, routine, anything.

The drawing characters must be a 10 character string of the: horizontal, vertical, upper left, upper center, upper right, middle left, middle center, middle right, lower left, lower center, lower right, characters.

For example, the ss-box routine is implemented as:

`draw( :draw('─│┌┬┐├┼┤└┴┘'), :&f, :col($columns), :cw($cell-width), :ch($cell-height), :indent($indent), @content )`

with the appropriate defaults.

# AUTHOR

Steve Schulze (thundergnat)

# COPYRIGHT AND LICENSE

Copyright 2020 Steve Schulze

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


## dist_zef-raku-community-modules-Games-TauStation-DateTime.md
[![Actions Status](https://github.com/raku-community-modules/Games-TauStation-DateTime/actions/workflows/test.yml/badge.svg)](https://github.com/raku-community-modules/Games-TauStation-DateTime/actions)

# NAME

Games::TauStation::DateTime — Convert TauStation's Galactic Coordinated Time to Old Earth Time

# SYNOPSIS

```
use Games::TauStation::DateTime;

# Show time in GCT or Old Earth time:
say GCT.new('193.99/59:586 GCT');    # OUTPUT: «193.99/59:586 GCT␤»
say GCT.new('193.99/59:586 GCT').OE; # OUTPUT: «2017-03-03T16:00:32.229148Z␤»

# Show duration from now:
say GCT.new('D12/43:044 GCT');    # OUTPUT: «198.27/19:285 GCT␤»
say GCT.new('D12/43:044 GCT').OE; # OUTPUT: «2018-05-05T06:20:12.543815Z␤»

# Adjust date using GCT or Old Earth time units:
say GCT.new('193.99/59:586 GCT').later(:30segments).earlier(:2hours);
# OUTPUT: «193.99/81:253 GCT␤»

# We inherit from DateTime class:
say GCT.new('2018-04-03T12:20:43Z');    # OUTPUT: «197.95/44:321 GCT␤»
say GCT.new('193.99/59:586 GCT').posix; # OUTPUT: «1488556832␤»

```

# DESCRIPTION

This module implements a subclass of [`DateTime`](https://docs.raku.org/type/DateTime) that lets you convert times between [TauStation](https://taustation.space/)'s [Galactic Coordinated Time (GCT)](https://alpha.taustation.space/archive/general/gct) and Old Earth (i.e. "real life") time.

# METHODS

## Inherited

Inherits all methods from [`DateTime`](https://docs.raku.org/type/DateTime)

## new

```
multi method new(Str:D $ where /<gct-time>/ --> GCT:D);
multi method new(Str:D $ where /<gct-duration>/ --> GCT:D);

```

In addition to regular [`DateTime` constructors](https://docs.raku.org/type/DateTime#method_new), two new ones are provided that take a string with either a GCT time or GCT duration, which is similar to time, except it's prefixed with uppercase letter `D` (see [CORETECHS archive for details](https://alpha.taustation.space/archive/general/gct)).

Negative times and durations are allowed. For durations, the minus sign goes after letter `D` Cycle and day units may be omitted. When cycle is omitted, the dot that normally follows it must be omitted as well; when both cycle and day are omitted, the slash before the time must be present. Whitespace can be used between units and separators.

These are examples of valid times:

* 198.14/07:106GCT`
* 198.14/07:106 GCT`
* * 198 . 14 / 07 : 106 GCT`
* 14/07:106 GCT`
* -14/07:106 GCT`
* /07:106 GCT`
* -/07:106 GCT`

These are examples of valid durations:

* D198.14/07:106GCT`
* D198.14/07:106 GCT`
* D - 198 . 14 / 07 : 106 GCT`
* D 14/07:106 GCT`
* D-14/07:106 GCT`
* D /07:106 GCT`
* D-/07:106 GCT`

## OE / OldEarth

```
say GCT.new('D12/43:044 GCT');          # OUTPUT: «198.27/19:285 GCT␤»
say GCT.new('D12/43:044 GCT').OE;       # OUTPUT: «2018-05-05T06:20:12.543815Z␤»
say GCT.new('D12/43:044 GCT').OldEarth; # OUTPUT: «2018-05-05T06:20:12.543815Z␤»

```

`.OE` is an alias for `.OldEarth`. The methods don't take any arguments and return a cloned `GCT` object with [`.formatter`](https://docs.perl6.org/type/DateTime#%28Dateish%29_method_formatter) set to the default [`DateTime`](https://docs.perl6.org/type/DateTime) formatter (i.e. the date when printed would be printed as Old Earth time instead of GCT).

## DateTime

```
say GCT.new('D12/43:044 GCT').DateTime;       # OUTPUT: «2018-05-05T06:29:14.494109Z␤»
say GCT.new('D12/43:044 GCT').DateTime.^name; # OUTPUT: «DateTime␤»

```

Coerces a `GCT` object to plain [`DateTime`](https://docs.raku.org/type/DateTime) object.

# AUTHOR

Zoffix Znet

# COPYRIGHT AND LICENSE

Copyright 2017 Zoffix Znet

Copyright 2018 - 2022 Raku Community

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


## dist_zef-librasteve-Contact-Name.md
[![](https://img.shields.io/badge/License-Artistic%202.0-0298c3.svg)](https://opensource.org/licenses/Artistic-2.0)

# Contact::Name

## Synopsis

This module takes a Str (or an Array of Str) and tries to extract to a valid English first name.

It uses two techniques:

1. It matches the start of each Str to a dictionary (based on Scotland 2007 birth registrations).
2. Failing that if takes the text to the left of the first "dot" character such as <[.-\_]>.

This seems to work reasonably effectively on a sample of emails.

```
my $n = Name.new;
$n.about;
$n.fail = 'no match';  #default is 'none'

$n.parse( @column[^$limit], :email, :!dotty );

$n.dict.grep: { m:i/$needle/ };
$n.parse: $needle;

```

Options:

* :email ... this tells Contact::Name that it should strip the trailing '@...' when you give it an email address
* :dotty ... this tells Contact::Name to suppress the progress dots

## Script

This module is served up with a side order of the `ract-name` script for your convenience. If you want to use that then please note that the script depends on [Net::Google::Sheets](https://github.com/librasteve/raku-Net-Google-Sheets) which in turn depends on [OAuth2::Client::Google](https://github.com/bduggan/p6-oauth2-client-google), so please follow instructions over there to configure your keys and so on.

Absent the script, only `Text::CSV` is a pre-requisite.

```
ract-name list
ract-name --sname='reading-c2e-v2' --range='Sheet2' set
ract-name --email=0 -l=5 extract
ract-name --email=0 --first=2 -l=5 convert
ract-name --needle=Joe check

Usage:
  ./ract-name [--sname=<Str>] [--range=<Str>] [--needle=<Str>] [--email[=Int]] [--first[=Int]] [-l[=Real]] [-q] <cmd>

    <cmd>             One of set upload clear list get extract convert check
    --sname=<Str>     Active Google Sheet name (from list)
    --range=<Str>     Active Google Sheet range (e.g. 'Sheet2')
    --needle=<Str>    Item to check (e.g. 'Joe')
    --email[=Int]     Column number of emails (input)
    --first[=Int]     Column number of first names (output)
    -l[=Real]         Limit the data processed [default: Inf]
    -q                Quiet mode (suppress cmd echo)

```

### Copyright

copyright(c) 2024 Henley Cloud Consulting Ltd.


## dist_cpan-FISCHER-Lingua-Palindrome.md
# Lingua::Palindrome

Module and script for checking whether a string is a palindrome.

[![Release](https://img.shields.io/github/release/sfischer13/perl6-Lingua-Palindrome.svg?style=flat-square)](https://github.com/sfischer13/perl6-Lingua-Palindrome/releases) [![License](https://img.shields.io/github/license/sfischer13/perl6-Lingua-Palindrome.svg?style=flat-square)](https://github.com/sfischer13/perl6-Lingua-Palindrome/blob/master/LICENSE) [![Travis](https://img.shields.io/travis/sfischer13/perl6-Lingua-Palindrome.svg?style=flat-square)](https://travis-ci.org/sfischer13/perl6-Lingua-Palindrome)

---

## Introduction

`Lingua::Palindrome` is a Perl 6 module for checking whether a string is a palindrome.

## Installation

```
# latest release
zef install Lingua::Palindrome

# specific version
zef -v install https://github.com/sfischer13/perl6-Lingua-Palindrome.git@v0.1.0

# developer version
zef -v install https://github.com/sfischer13/perl6-Lingua-Palindrome.git

```

## Development

```
git archive --prefix=Lingua-Palindrome-0.1.0/ -o ../Lingua-Palindrome-0.1.0.tar.gz HEAD

```

## Credits

This project is authored and maintained by Stefan Fischer.
The source code is available under the **MIT License**.
See [LICENSE](https://github.com/sfischer13/perl6-Lingua-Palindrome/blob/master/LICENSE) for further details.


## dist_github-jpve-Pod-Strip.md
# Pod::Strip (Perl6)

Strip Pod annotation from Perl6. Converts Pod documentation to empty lines of the same size.

**Bugs**:

* Also strips Pod-style annotation from strings and comments! This is incorrect behaviour and is to be changed in the future.

## Installation

Using panda:

```
$ panda update
$ panda install Pod::Strip

```

Using ufo:

```
$ ufo
$ make
$ make test
$ make install

```

## Usage:

```
use Pod::Strip;

my Str $code = slurp $?FILE;
say pod-strip($code);

```


## dist_github-alabamenhu-Intl-Format-Unit.md
# Intl::Format::Unit

A module for formatting units in a localized manner

To use

```
use Intl::Format::Unit;

say format-unit 0,        :unit<length-meter>; # 0 m
say format-unit 1234,     :unit<length-meter>; # 53,425.21 m
say format-unit 53425.21, :unit<length-meter>; # 1,234 m

```

The sub `format-unit` takes the following arguments:

* **`quantity`**
  The amount of the unit (a number).
* **`unit`**
  The type of unit (e.g. meter, liter, etc).
* **`:language`**
  The language to use in formatting. Defaults to **user-language**.
* **`:length`**
  Any of **long**, **short** or **narrow**. Defaults to *short*.
* **`:case`**
  The grammatical case to use (normally only applicable with *long* length). Defaults to *nominative*

The units can be quite complex, even to the point of making no sense. Assuming English,

```
format-unit 12345.6789, :unit<solar-radius-cubic-yottaliter-per-pound-square-millimeter>;
# 12,345.6789 R☉⋅Yl³/lb⋅mm²

```

## Supported units

The units that are generally supported by CLDR's `validity/units.xml` file. These have been curated a bit to have the following base units:

> **g-force meter second arc-minute arc-second degree radian
> revolution acre hectare foot inch mile yard dunam karat
> gram liter mole percent permille permyriad permillion item
> portion gallon gallon-imperial bit byte century decade
> day day-person hour minute month month-person week week-person
> year year-person ampere ohm volt calorie foodcalorie joule
> watt-hour electronvolt therm-us british-thermal-unit pound-force newton
> hertz dot em pixel astronomical-unit fathom furlong light-year
> mile-scandinavian nautical-mile parsec point earth-radius solar-radius
> candela lumen lux solar-luminosity carat grain metric-ton ounce
> ounce-troy pound stone ton dalton earth-mass solar-mass watt
> horsepower atmosphere inch-ofhg bar meter-ofhg pascal
> ofhg knot celsius fahrenheit generic kelvin pound-force-foot
> newton-meter acre-foot bushel cup cup-metric dessert-spoon
> dessert-spoon-imperial drop dram jigger pinch quart-imperial
> fluid-ounce fluid-ounce-imperial pint pint-metric quart
> tablespoon teaspoon barrel**

All of these make take the following SI and SI-ish (*˟*) prefixes:

> **yotta zetta exa peta tera giga mega kilo hecto deka
> deci centi milli micro nano pico femto atto zepto yocto
> exbi˟ pebi˟ tebi˟ gibi˟ mebi˟ kibi˟**

Lastly, the following powers are supported:

> **square cubic**

Using the above units, you can combine them in the following way:

* To prefix, attach directly: `millimeter` `kiloliter`
* To raise to a power, separate the power and the unit by a hyphen: `square-foot`, `cubic-centimeter`
* To multiple two units, separate by a hyphen: `watt-hour`
* To divide two units, separate by a hyphenated per: `miles-per-hour`.

These can combined in almost infinite complexity. The only restriction is that there may only be
*one* `-per-` (subsequent ones, per TR 35, are ignored).

Also note that the rarer the combination of units that you get, the more likely that non-major languages
may not have full support. For Latin-based languages, this might not look terrible,
but for others, it means that the fallback versions (all Latin-script) may be inserted.

## ⚠ Warning

More so than other modules in the `Intl` namespace, this module should be considered experimental for the following reasons:

1. The method of selecting the unit is not intuitive and will likely be changed.
2. Composed units were only introduced in CLDR v.38 (early 2020) with support for two languages (French and German).
   As of v.38.1 (late 2020), this has not changed. Use caution when attempting to use these, as some languages may end up creating unexpected combinations (like saying *liter per minutes* instead of *liters per minute*). This should not affect the most simple units such as *meter* or *liter* or even common ones like *kilometers per hour*.

## Dependencies

* `Intl::CLDR`
  Houses the data for calculating the counts
* `Intl::UserLanguage`
  Determines the default language when not provided
* `Intl::Format::Number`
  Formats the quantity as a decimal number
* `Intl::Number::Plural`
  Determines the grammatical-ish number to select the correct pattern

## Todo

* More tests files (especially for compound units)

## Version History

* **v0.2.0**
  * Initial support for composed units
* **v0.1.0**
  * Initial version

## License and Copyright

© 2020-2021 Matthew Stephen Stuckwisch.
Licensed under the Artistic License 2.0.


## dist_zef-grizzlysmit-Syntax-Highlighters.md
## Table of Contents

* [NAME](#name)
* [AUTHOR](#author)
* [VERSION](#version)
* [TITLE](#title)
* [SUBTITLE](#subtitle)
* [COPYRIGHT](#copyright)
* [Introduction](#introduction)
* [HighlighterFailed](#highlighterfailed)
* [VariablesBase](#variablesbase)
* [VariablesBaseActions](#variablesbaseactions)
* [Variables and VariablesActions](#variables-and-variablesactions)
* [ValueBase and ValueBaseActions](#valuebase-and-valuebaseactions)
* [Value and ValueActions](#value-and-valueactions)
* [highlight-var](#highlight-var)
* [highlight-val](#highlight-val)

# NAME

Syntax::Highlighters

# AUTHOR

Francis Grizzly Smit ([grizzly@smit.id.au](mailto:grizzly@smit.id.au))

# VERSION

0.1.5

# TITLE

Syntax::Highlighters

# SUBTITLE

A Raku module to do basic syntax highlighting.

# COPYRIGHT

LGPL V3.0+ [LICENSE](https://github.com/grizzlysmit/Syntax-Highlighters/blob/main/LICENSE)

[Top of Document](#table-of-contents)

# Introduction

Some syntax highlighting stuff: grammars to parse basic **Raku** forms and highlight them with colours. And functions to use them.

**NB: by no means complete or exhaustive (as yet at least), and no way to parse expressions etc**.

[Top of Document](#table-of-contents)

# HighlighterFailed

An Exception class for reporting errors in parsing.

```
class HighlighterFailed is Exception is export {
    has Str:D $.msg = 'Error: Highlighter Failed.';
    method message( --> Str:D) {
        $!msg;
    }
}

```

[Top of Document](#table-of-contents)

## VariablesBase

A grammar for parsing variable forms forms the basis of **Variables** which syntax highlights variable forms.

## VariablesBaseActions

A role to assist in the parsing variable forms forms the basis of **VariablesActions** which syntax highlights variable forms.

[Top of Document](#table-of-contents)

## Variables and VariablesActions

The grammar and class pair that do the actual syntax highlighting of the variable forms.

**NB: Uses VariablesBase and VariablesBaseActions to do the actual parsing**.

```
grammar Variables is VariablesBase is export {
    token TOP { <var> }
}

class VariablesActions does VariablesBaseActions is export {
    method TOP($made) {
        my %spec = $made<var>.made;
        my Str $top = t.color(255,0,0) ~ %spec«sigil»;
        if %spec«twigil» eq '<' {
            $top ~= t.color(0,255,255) ~ '<' ~ %spec«name» ~ '>';
        } elsif %spec«type» eq 'Failed' {
            $top ~= t.color(255,0,0) ~ %spec«name»;
        } else {
            $top ~= %spec«twigil» ~ t.color(0,255,255) ~ %spec«name»;
        }
        if %spec«derref»:exists && (%spec«derref»«derref-char»:exists) {
            if %spec«derref»«derref-char» eq '[' {
                $top ~= t.color(255,0,0) ~ '[' ~ t.color(255,0,255) ~ %spec«derref»«ind» ~ t.color(255,0,0) ~ ']';
            } elsif %spec«derref»«derref-char» eq '«' {
                $top ~= t.color(255,74,0) ~ '«' ~ %spec«derref»«ind» ~ '»';
            } elsif %spec«derref»«derref-char» eq '<' {
                $top ~= t.color(255,0,0) ~ '<' ~ t.color(255,0,255) ~ %spec«derref»«ind» ~ t.color(255,0,0) ~ '>';
            } elsif %spec«derref»«derref-char» eq '{' {
                $top ~= t.color(255,0,0) ~ '{$' ~ t.color(255,0,255) ~ %spec«derref»«ind» ~ t.color(255,0,0) ~ '}';
            } elsif %spec«derref»«derref-char» eq '(' {
                $top ~= t.color(255,0,0) ~ '(' ~ t.color(255,0,255) ~ %spec«derref»«ind» ~ t.color(255,0,0) ~ ')';
            }
        }
        $made.make: $top;
    }
}

```

[Top of Document](#table-of-contents)

## ValueBase and ValueBaseActions

ValueBase and ValueBaseActions are a grammar role pair that implement parsing of **Raku** style values.

**NB: not comprehensive nor complete (yet at least)**.

## Value and ValueActions

Value and ValueActions are a grammar class pair that implements syntax highlighting of **Raku** style values, using ValueBase and ValueBaseActions, as the parsing work horse.

```
grammar Value is ValueBase is export {
    token TOP            { ^ <value> $ }
}

class ValueActions does ValueBaseActions is export {
    method !highlight(%spec) {
        my $highlight = '';
        $highlight ~= %spec«space»«val» if %spec«space»;
        if %spec«type» eq 'int' {
            $highlight ~= t.color(255, 0, 255) ~ %spec«val»;
        } elsif %spec«type» eq 'rat-val' {
            $highlight ~= t.color(255, 0, 255) ~ %spec«numerator» ~ '/' ~ %spec«denominator»;
        } elsif %spec«type» eq 'num' {
            $highlight ~= t.color(255, 0, 255) ~ %spec«mantisa»;
            $highlight ~= %spec«exponent»«signifitant» ~ %spec«exponent»«sign» ~ %spec«exponent»«exp» if %spec«exponent»;
        } elsif %spec«type» eq 'bool' {
            $highlight ~= t.color(255, 0, 255) ~ %spec«val»;
        } elsif %spec«type» eq 'bare-word' {
            $highlight ~= t.color(255, 0, 255) ~ %spec«val»;
        } elsif %spec«type» eq 'string' {
            $highlight ~= t.color(255, 0, 255) ~ %spec«open» ~ %spec«val» ~ %spec«close»;
        } elsif %spec«type» eq 'array-val' {
            $highlight ~= t.color(255, 0, 0) ~  '[';
            $highlight ~= %spec«a-space»«val» if %spec«a-space»;
            my Str:D $sep = '';
            my @vals = |%spec«val»;
            for @vals -> %val {
                $highlight ~= t.color(255, 0, 0) ~ $sep ~ self!highlight(%val);
                $sep = ',';
            }
            $highlight ~= %spec«a-space-after»«val» if %spec«a-space-after»;
            $highlight ~= t.color(255, 0, 0) ~ ']';
        } elsif %spec«type» eq 'hash-val' {
            $highlight ~= t.color(255, 0, 0) ~  '{';
            $highlight ~= %spec«h-space»«val» if %spec«h-space»;
            my Str:D $sep = '';
            my @vals = |%spec«val»;
            for @vals -> %val {
                $highlight ~= t.color(255, 0, 0) ~ $sep ~ self!highlight(%val);
                $sep = ',';
            }
            $highlight ~= %spec«h-space-after»«val» if %spec«h-space-after»;
            $highlight ~= t.color(255, 0, 0) ~ '}';
        } elsif %spec«type» eq 'pair0' {
            $highlight ~= t.color(255, 0, 255) ~ %spec«key» ~ t.color(255, 0, 0) ~ ' => ' ~ self!highlight(%spec«val»);
        } elsif %spec«type» eq 'pair1' {
            $highlight ~= t.color(255, 0, 0) ~ ':' ~ t.color(255, 0, 255)
                                               ~ %spec«key» ~ t.color(255, 0, 0) ~ '(' ~ self!highlight(%spec«val»)
                                                                                ~ t.color(255, 0, 0) ~ ')';
        }
        $highlight ~= %spec«space-after»«val» if %spec«space-after»;
        return $highlight;
    }
    method TOP($made) {
        my %spec = $made<value>.made;
        my Str $top = self!highlight(%spec);
        $made.make: $top;
    }
} # class ValueActions does ValueBaseActions #

```

[Top of Document](#table-of-contents)

## highlight-var

wraps up the actual usage of the grammars above.

Defined as:

```
sub highlight-var($var --> Str:D) is export {
    my $actions = VariablesActions;
    my $tmp = Variables.parse($var, :enc('UTF-8'), :$actions).made;;
    HighlighterFailed.new(:msg("Error: Variables.parse Failed.")).throw if $tmp === Any;
    return $tmp;
} # sub highlight-var($var --> Str:D) is export #

```

## highlight-val

```
sub highlight-val($val --> Str:D) is export {
    my $actions = ValueActions;
    my $tmp = Value.parse($val, :enc('UTF-8'), :$actions).made;;
    HighlighterFailed.new(:msg("Error: Variables.parse Failed.")).throw if $tmp === Any;
    return $tmp;
} # sub highlight-val($val --> Str:D) is export #

```

[Top of Document](#table-of-contents)


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

# NAME

**QueryOS** - Provides a class and an executable, `query-os`, to list OS details

# SYNOPSIS

```
use QueryOS;
my $o = OS.new;
say $o.version-name # OUTPUT: «debian␤»

```

# DESCRIPTION

**QueryOS** is a module that provides a class, `OS`, with methods and attributes to simplify module authors' porting their work to various operating systems by identifying important system discriminators. The module relies on the attributes of Raku's `$*USER`, `$*DISTRO`, and `$*KERNEL` variables and parses out additional details in parts of those attributes.

Current attributes and methods are:

* name - from `$*DISTRO.name`
* version - from `$*DISTRO.version`
* version-name - text part of `$*DISTRO.name`
* version-serial - number part of `$*DISTRO.name`
* is-linux
* is-windows
* is-macos

# List of known DISTRO names:

* debian
* gentoo
* macos
* mswin
* suse
* ubuntu

# Example binary use

When I execute `query-os q` on my system I get:

```
This program is currently running on:

    Host:           bigtom
    User:           tbrowde
    Distro:         debian*
    Version name:   bullseye
    Version number: 11
    System:         x86_64

This module provides class 'OS' whose attributes
provide details of the system to aid module
authors porting to multiple versions. See the
README for more information or use the 'list'
option to this program.

*NOTE: If the 'Distro' name is not recognized,
       it will be so stated in parentheses
       following the reported name.

```

# AUTHOR

Tom Browder [tbrowder@acm.org](mailto:tbrowder@acm.org)

# COPYRIGHT AND LICENSE

© 2023-2024 Tom Browder

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


## dist_github-MattOates-Stats.md
# Stats [Build Status](https://travis-ci.org/MattOates/Stats)

Perl6 statistics modules. Currently has some basic statistics functions revolving around averages.

## Contributing

Feel free to PR anything you want. Please add some tests to t/ for any new classes/features.
You can run the tests by doing:

```
prove -e 'perl6 -I ./lib' -lrv t/

```

## Examples

```
use v6;
use Stats;

my @data = (1,2,3,4,5,6,6,3,2,9);

#Get some summary statistics similar to R
summary @data;

#Get the mean/median/mode
mean @data; median @data; mode @data;

#Get the quartiles/standard deviation of the data
iqr @data; sd @data;

```


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

# NAME

Algorithm::Elo

# SYNOPSIS

```
use Algorithm::Elo;

my ( $player-a-score, $player-b-score ) = 1_600, 1_600;

( $player-a-score, $player-b-score ) = calculate-elo($player-a-score, $player-b-score, :left);

```

# DESCRIPTION

This module implements the Elo rating system, commonly used to rate chess players.

# SUBROUTINES

## calculate-elo(Int $left, Int $right, :left, :right, :draw)

Given two current ratings and the result of a match (`:left` if the left player wins, `:right` if the right player wins, `:draw` for a draw), return two new ratings for the left and right players.

# SEE-ALSO

[Elo Rating System](https://en.wikipedia.org/wiki/Elo_rating_system)

# AUTHORS

* Rob Hoelz
* Raku Community

# COPYRIGHT AND LICENSE

Copyright (c) 2015 - 2017 Rob Hoelz

Copyright (c) 2024 Raku Community

This library is free software; you can redistribute it and/or modify it under the MIT license.


## dist_cpan-JMASLAK-BusyIndicator.md
# NAME

busy-indicator.raku - Luxafor Indicators based on Google Calendar and Webcam Status

# SYNOPSIS

```
# busy-indicator.rakuo --calendar=you@example.com

```

# DESCRIPTION

This controls Luxafor flag indicators based on a combination of Google Calendar meetings (when in a meeting, the flag is on, as well as two minutes before and after the meeting) and webcam usage (when the webcam is in use, it turns the Luxafor flag on). It also provides for manual control of the Luxafor flag.

This allows people to know if I'm "busy" or not without disturbing me or a conference call I might be on.

# OPTIONAL PARAMETERS

## --calendar=

This is a comma-seperated list of Google calendars your Google account has access to examine and which you want to use to control the Luxafor flag.

To access these calendars, this program uses the `gcalcli` program. Thus, you need to install `gcalcli` before using this option. You also need to execute gcalcli once from the command line (which will open a browser for you to authenticate to Google) to have `gcalcli` cache a Google access token.

If you don't want to use Google calendar integration, simply don't provide this option.

## --interval=

This determines how often the script fetches Google calendar entries and writes a status line to the screen. The default is `60` seconds.

## --port=

This determines what control port is used for this script. By default, it is 0 (disabled). If you use a control port (this is an advanced usage), you must specify a port number. Note that no authentication is used for this port, so it must not be firewalled or otherwise protected from outside access.

# USER INTERFACE

Once you run the program, every minute (or whatever you specified for the `--interval` option) it will update the screen with a status. This status will indicate if you are currently in a meeting or, otherwise, the next meeting that is scheduled for today.

There are some keyboard commands that can be used to override the automatic busy indications:

The "b" command will turn the light(s) on (with a red light).

The "o" command will turn the light(s) off until the next meeting.

The "g" command will turn the light on, but as a green light.

The "n" displays the next meeting on your calendar.

The "a" shows you an "agenda" view of your upcoming meetings.

# INSTALLATION PREREQUISITES

You must have a Luxafor flag to use this program.

You need relatively recent Raku to be installed. Download Raku for your OS from: <https://www.raku.org/>

You must install `LibUSB` development libraries. On Ubuntu, this is done with:

```
sudo apt-get install libusb-1.0-0-dev

```

You must also install `gcalcli` if using the Google Calendar integration. To do that on Ubuntu:

```
sudo apt-get install gcalcli

```

Then you'll want to run gcalcli the first time, and log into Google with your proper credentials (the first time you run gcalcli, it'll open a browser for you to log into your Google account): gcalcli agenda

You must ensure that the Luxafor Flag is not bound to the `usbhid` module. To do that on Ubuntu, create a file `/etc/modprobe.d/luxafor.conf` that contains:

```
options usbhid quirks=0x04d8:0xf372:0x0004

```

You will need to reboot after making this change for it to take effect.

If you wish to run this program as a standard user (highly recommended), you also need to create a file named `/etc/udev/rules.d/luxafor.rules` with the following content:

```
SUBSYTEM=="usb", ATTR{idVendor}="04d8", ATTR{idProduct}=="f372" MODE="0664" OWNER="jmaslak"

```

Replace `jmaslak` in the above file with your username. Then you will need to reboot for this change to take effect.

As root (or another user depending on your Raku installation), you can install this package with: zef install BusyIndicator

Now you can run the script using "busy-indicator-raku" from the command line!

# COPYRIGHT

Copyright © 2019-2021 Joelle Maslak This application is free software; you can distribute it and/or modify it under the Artistic License 2.0

Also included is a modified version of Travis Gibson's `LibUSB` which has a copyright: Copyright © 2020 Travis Gibson It is also licensed under the Artistic License 2.0.