class Any

Thing/object

class Any is Mu {}

While Mu is the root of the Perl 6 class hierarchy, Any is the class that serves as a default base class for new classes, and as the base class for most built-in classes.

Since Perl 6 intentionally confuses items and single-element lists, most methods in Any are also present on class List, and coerce to List or a list-like type.

Methods

method ACCEPTS

Defined as:

multi method ACCEPTS(Any:D: Mu $other)

Usage:

EXPR.ACCEPTS(EXPR);

Returns True if $other === self (i.e. it checks object identity).

Many built-in types override this for more specific comparisons.

method any

Defined as:

method any(--> Junction:D)

Interprets the invocant as a list and creates an any-Junction from it.

say so 2 == <1 2 3>.any;        # OUTPUT: «True␤» 
say so 5 == <1 2 3>.any;        # OUTPUT: «False␤»

method all

Defined as:

method all(--> Junction:D)

Interprets the invocant as a list and creates an all-Junction from it.

say so 1 < <2 3 4>.all;         # OUTPUT: «True␤» 
say so 3 < <2 3 4>.all;         # OUTPUT: «False␤»

method one

Defined as:

method one(--> Junction:D)

Interprets the invocant as a list and creates a one-Junction from it.

say so 1 == (123).one;      # OUTPUT: «True␤» 
say so 1 == (121).one;      # OUTPUT: «False␤»

method none

Defined as:

method none(--> Junction:D)

Interprets the invocant as a list and creates a none-Junction from it.

say so 1 == (123).none;     # OUTPUT: «False␤» 
say so 4 == (123).none;     # OUTPUT: «True␤»

method list

Defined as:

multi method list(Any:U: --> List)
multi method list(Any:D \SELF: --> List)

Applies the infix , operator to the invocant and returns the resulting List:

say 42.list.^name;           # OUTPUT: «List␤» 
say 42.list.elems;           # OUTPUT: «1␤»

Subclasses of Any may choose to return any core type that does the Positional role from .list. Use .List to coerce specifically to List.

@ can also be used as a list or Positional contextualizer:

my $not-a-list-yet = $[1,2,3];
say $not-a-list-yet.perl;             # OUTPUT: «$[1, 2, 3]␤» 
my @maybe-a-list = @$not-a-list-yet;
say @maybe-a-list.^name;              # OUTPUT: «Array␤» 

In the first case, the list is itemized. @ as a prefix puts the initial scalar in a list context by calling .list and turning it into an Array.

method push

Defined as:

method push(|values --> Positional:D)

The method push is defined for undefined invocants and allows for autovivifying undefined to an empty Array, unless the undefined value implements Positional already. The argument provided will then be pushed into the newly created Array.

my %h;
say %h<a>;     # OUTPUT: «(Any)␤»      <-- Undefined 
%h<a>.push(1); # .push on Any 
say %h;        # OUTPUT: «{a => [1]}␤» <-- Note the Array

routine reverse

Defined as:

multi sub    reverse(*@list  --> Seq:D)
multi method reverse(List:D: --> Seq:D)

Returns a Seq with the same elements in reverse order.

Note that reverse always refers to reversing elements of a list; to reverse the characters in a string, use flip.

Examples:

say <hello world!>.reverse;     # OUTPUT: «(world! hello)␤» 
say reverse ^10;                # OUTPUT: «(9 8 7 6 5 4 3 2 1 0)␤»

method sort

Defined as:

multi method sort()
multi method sort(&custom-routine-to-use)

Sorts iterables with cmp or given code object and returns a new Seq. Optionally, takes a Callable as a positional parameter, specifying how to sort.

Examples:

say <b c a>.sort;                           # OUTPUT: «(a b c)␤» 
say 'bca'.comb.sort.join;                   # OUTPUT: «abc␤» 
say 'bca'.comb.sort({$^b cmp $^a}).join;    # OUTPUT: «cba␤» 
say '231'.comb.sort(&infix:«<=>»).join;     # OUTPUT: «123␤»

method map

Defined as:

multi method map(Hash:D \hash)
multi method map(Iterable:D \iterable)
multi method map(|c)
multi method map(\SELF: &block;; :$label:$item)
multi sub map(&code+values)

map will iterate over the invocant and apply the number of positional parameters of the code object from the invocant per call. The returned values of the code object will become elements of the returned Seq.

The :$label and :$item are useful only internally, since for loops get converted to maps. The :$label takes an existing Label to label the .map's loop with and :$item controls whether the iteration will occur over (SELF,) (if :$item is set) or SELF.

In sub form, will apply the code block to the values, which will be used as invocant.

The form with \c, Iterable:D \iterable and Hash:D \hash as signatures will fail with X::Cannot::Map, and are mainly meant to catch common traps.

method deepmap

Defined as:

method deepmap(&block --> Listis nodal

deepmap will apply &block to each element and return a new List with the return values of &block, unless the element does the Iterable role. For those elements deepmap will descend recursively into the sublist.

say [[1,2,3],[[4,5],6,7]].deepmap(* + 1);
# OUTPUT: «[[2 3 4] [[5 6] 7 8]]␤»

In the case of Associatives, it will be applied to its values:

{ what => "is"this => "thing"=> <real list> }.deepmap*.flip ).say
# OUTPUT: «{a => (laer tsil), this => gniht, what => si}␤» 

method duckmap

Defined as:

method duckmap(&blockis rw is nodal

duckmap will apply &block on each element that behaves in such a way that &block can be applied. If it fails, it will descend recursively if possible, or otherwise return the item without any transformation. It will act on values if the object is Associative.

<a b c d e f g>.duckmap(-> $_ where <c d e>.any { .uc }).say;
# OUTPUT: «(a b C D E f g)␤» 
(('d''e'), 'f').duckmap(-> $_ where <e f>.any { .uc }).say;
# OUTPUT: «((d E) F)␤» 
{ first => ('d''e'), second => 'f'}.duckmap(-> $_ where <e f>.any { .uc }).say;
# OUTPUT: «{first => (d E), second => F}␤» 

In the first case, it is applied to c, d and e which are the ones that meet the conditions for the block ({ .uc }) to be applied; the rest are returned as is.

In the second case, the first item is a list that does not meet the condition, so it's visited; that flat list will behave in the same way as the first one. In this case:

say [[1,2,3],[[4,5],6,7]].duckmap*² ); # OUTPUT: «[9 9]␤»

You can square anything as long as it behaves like a number. In this case, there are two arrays with 3 elements each; these arrays will be converted into the number 3 and squared. In the next case, however

say [[1,2,3],[[4,5],6.1,7.2]].duckmap-> Rat $_ { $_²} );
# OUTPUT: «[[1 2 3] [[4 5] 37.21 51.84]]␤»

3-item lists are not Rat, so it descends recursively, but eventually only applies the operation to those that walk (or slither, as the case may be) like a Rat.

Although on the surface (and name), duckmap might look similar to deepmap, the latter is applied recursively regardless of the type of the item.

method nodemap

Defined as:

method nodemap(&block --> Listis nodal

nodemap will apply &block to each element and return a new List with the return values of &block. In contrast to deepmap it will not descend recursively into sublists if it finds elements which do the Iterable role.

say [[1,2,3], [[4,5],6,7], 7].nodemap(*+1);
# OUTPUT: «(4, 4, 8)␤» 
 
say [[23], [4, [56]]]».nodemap(*+1)
# OUTPUT: «((3 4) (5 3))␤»

The examples above would have produced the exact same results if we had used map instead of nodemap. The difference between the two lies in the fact that map flattens out slips while nodemap doesn't.

say [[2,3], [[4,5],6,7], 7].nodemap({.elems == 1 ?? $_ !! slip});
# OUTPUT: «(() () 7)␤» 
say [[2,3], [[4,5],6,7], 7].map({.elems == 1 ?? $_ !! slip});
# OUTPUT: «(7)␤»

When applied to Associatives, it will act on the values:

{ what => "is"this => "thing" }.nodemap*.flip ).say;
# OUTPUT: «{this => gniht, what => si}␤»

method flat

Defined as:

method flat() is nodal

Interprets the invocant as a list, flattens non-containerized Iterables into a flat list, and returns that list. Keep in mind Map and Hash types are Iterable and so will be flattened into lists of pairs.

say ((12), (3), %(:42a));      # OUTPUT: «((1 2) 3 {a => 42})␤» 
say ((12), (3), %(:42a)).flat# OUTPUT: «(1 2 3 a => 42)␤»

Note that Arrays containerize their elements by default, and so flat will not flatten them. You can use hyper method call to call .List method on all the inner Iterables and so de-containerize them, so that flat can flatten them:

say [[123], [(45), 67]]      .flat# OUTPUT: «([1 2 3] [(4 5) 6 7])␤» 
say [[123], [(45), 67]]».List.flat# OUTPUT: «(1 2 3 4 5 6 7)␤»

For more fine-tuned options, see deepmap, duckmap, and signature destructuring

method eager

Defined as:

method eager() is nodal

Interprets the invocant as a List, evaluates it eagerly, and returns that List.

my  $range = 1..5;
say $range;         # OUTPUT: «1..5␤» 
say $range.eager;   # OUTPUT: «(1 2 3 4 5)␤»

method elems

Defined as:

multi method elems(Any:U: --> 1)
multi method elems(Any:D:)

Interprets the invocant as a list, and returns the number of elements in the list.

say 42.elems;                   # OUTPUT: «1␤» 
say <a b c>.elems;              # OUTPUT: «3␤» 
say Whatever.elems ;            # OUTPUT: «1␤»

It will also return 1 for classes.

method end

multi method end(Any:U: --> 0)
multi method end(Any:D:)

Interprets the invocant as a list, and returns the last index of that list.

say 6.end;                      # OUTPUT: «0␤» 
say <a b c>.end;                # OUTPUT: «2␤»

method pairup

Defined as:

multi method pairup(Any:U:)
multi method pairup(Any:D:)

Returns an empty Seq if the invocant is a type object

Range.pairup.say# OUTPUT: «()␤»

Interprets the invocant as a list, and constructs a list of pairs from it, in the same way that assignment to a Hash does. That is, it takes two consecutive elements and constructs a pair from them, unless the item in the key position already is a pair (in which case the pair is passed through, and the next list item, if any, is considered to be a key again). It returns a Seq of Pairs.

say (=> 1'b''c').pairup.perl;     # OUTPUT: «(:a(1), :b("c")).Seq␤»

sub item

Defined as:

multi item(\x)
multi item(|c)
multi item(Mu $a)

Forces given object to be evaluated in item context and returns the value of it.

say item([1,2,3]).perl;              # OUTPUT: «$[1, 2, 3]␤» 
say item( %apple => 10 ) ).perl;   # OUTPUT: «${:apple(10)}␤» 
say item("abc").perl;                # OUTPUT: «"abc"␤»

You can also use $ as item contextualizer.

say $[1,2,3].perl;                   # OUTPUT: «$[1, 2, 3]␤» 
say $("abc").perl;                   # OUTPUT: «"abc"␤»

method Array

Defined as:

method Array(--> Array:Dis nodal

Coerces the invocant to an Array.

method List

Defined as:

method List(--> List:Dis nodal

Coerces the invocant to List, using the list method.

method serial

Defined as

multi method serial()

This method is Rakudo specific, and is not included in the Perl 6 spec.

The method returns the self-reference to the instance itself:

my $b;                 # defaults to Any 
say $b.serial.^name;   # OUTPUT: «Any␤» 
say $b.^name;          # OUTPUT: «Any␤» 
my $breakfast = 'food';
$breakfast.serial.say# OUTPUT: «food␤» 

This is apparently a no-op, as exemplified by the third example above. However, in HyperSeqs and RaceSeqs it returns a serialized Seq, so it can be considered the opposite of the hyper/race methods. As such, it ensures that we are in serial list-processing mode, as opposed to the autothreading mode of those methods.

method Hash

Defined as:

multi method Hash--> Hash:D)

Coerces the invocant to Hash.

method hash

Defined as:

multi method hash(Any:U:)
multi method hash(Any:D:)

When called on a type object, returns an empty Hash. On instances, it is equivalent to assigning the invocant to a %-sigiled variable and returning that.

Subclasses of Any may choose to return any core type that does the Associative role from .hash. Use .Hash to coerce specifically to Hash.

my $d# $d is Any 
say $d.hash# OUTPUT: {} 
 
my %m is Map = => 42=> 666;
say %m.hash;  # Map.new((a => 42, b => 666)) 
say %m.Hash;  # {a => 42, b => 666} 

method Slip

Defined as:

method Slip(--> Slip:Dis nodal

Coerces the invocant to Slip.

method Map

Defined as:

method Map(--> Map:Dis nodal

Coerces the invocant to Map.

method Bag

Defined as:

method Bag(--> Bag:Dis nodal

Coerces the invocant to Bag, whereby Positionals are treated as lists of values.

method BagHash

Defined as:

method BagHash(--> BagHash:Dis nodal

Coerces the invocant to BagHash, whereby Positionals are treated as lists of values.

method Set

Defined as:

method Set(--> Set:Dis nodal

Coerces the invocant to Set, whereby Positionals are treated as lists of values.

method SetHash

Defined as:

method SetHash(--> SetHash:Dis nodal

Coerces the invocant to SetHash, whereby Positionals are treated as lists of values.

method Mix

Defined as:

method Mix(--> Mix:Dis nodal

Coerces the invocant to Mix, whereby Positionals are treated as lists of values.

method MixHash

Defined as:

method MixHash(--> MixHash:Dis nodal

Coerces the invocant to MixHash, whereby Positionals are treated as lists of values.

method Supply

Defined as:

method Supply(--> Supply:Dis nodal

First, it coerces the invocant to a list by applying its .list method, and then to a Supply.

method min

Defined as:

multi method min()
multi method min(&by)
multi sub min(+args:&by!)
multi sub min(+args)

Coerces the invocant to Iterable and returns the numerically smallest element; in the case of Hashes, it returns the Pair with the lowest value. In sub form, the invocant is passed as an argument.

If a Callable positional argument is provided, each value is passed into the filter, and its return value is compared instead of the original value. The original value is still the one returned from min.

say (1,7,3).min();              # OUTPUT:«1␤» 
say (1,7,3).min({1/$_});        # OUTPUT:«7␤» 
say min(1,7,3);                 # OUTPUT: «1␤» 
say min(1,7,3,:by{ 1/$_ } )); # OUTPUT: «7␤» 
min( %(=> 3b=> 7 ) ).say ;  # OUTPUT: «a => 3␤»

method max

Defined as:

multi method max()
multi method max(&by)
multi sub max(+args:&by!)
multi sub max(+args)

Coerces the invocant to Iterable and returns the numerically largest element; in the case of Hashes, the Pair with the highest value.

If a Callable positional argument is provided, each value is passed into the filter, and the return value is compared instead of the original value. The original value is still the one returned from max.

say (1,7,3).max();                # OUTPUT:«7␤» 
say (1,7,3).max({1/$_});          # OUTPUT:«1␤» 
say max(1,7,3,:by{ 1/$_ } ));   # OUTPUT: «1␤» 
say max(1,7,3);                   # OUTPUT: «7␤» 
max( %(=> 'B'b=> 'C' ) ).say# OUTPUT: «b => C␤»

method minmax

Defined as:

multi method minmax()
multi method minmax(&by)
multi sub minmax(+args:&by!)
multi sub minmax(+args)

Returns a Range from the smallest to the largest element.

If a Callable positional argument is provided, each value is passed into the filter, and its return value is compared instead of the original value. The original values are still used in the returned Range.

say (1,7,3).minmax();        # OUTPUT:«1..7␤» 
say (1,7,3).minmax({-$_});   # OUTPUT:«7..1␤» 
say minmax(1,7,3);           # OUTPUT: «1..7␤» 
say minmax(1,7,3,:by( -* )); # OUTPUT: «7..1␤»

method minpairs

Defined as:

multi method minpairs(Any:D:)

Calls .pairs and returns a Seq with all of the Pairs with minimum values, as judged by the cmp operator:

<a b c a b c>.minpairs.perl.put# OUTPUT: «(0 => "a", 3 => "a").Seq␤» 
%(:42a, :75b).minpairs.perl.put# OUTPUT: «(:a(42),).Seq␤»

method maxpairs

Defined as:

multi method maxpairs(Any:D:)

Calls .pairs and returns a Seq with all of the Pairs with maximum values, as judged by the cmp operator:

<a b c a b c>.maxpairs.perl.put# OUTPUT: «(2 => "c", 5 => "c").Seq␤» 
%(:42a, :75b).maxpairs.perl.put# OUTPUT: «(:b(75),).Seq␤»

method keys

Defined as:

multi method keys(Any:U: --> List)
multi method keys(Any:D: --> List)

For defined Any returns its keys after calling list on it, otherwise calls list and returns it.

my $setty = Set(<Þor Oðin Freija>);
say $setty.keys# OUTPUT: «(Þor Oðin Freija)␤»

See also List.keys.

Trying the same on a class will return an empty list, since most of them don't really have keys.

method flatmap

Defined as:

method flatmap(&block:$label)

DEPRECATION NOTICE: This method is deprecated in 6.d and will be removed in 6.e. Use .map followed by .flat instead.

Applies map to every element with the block and Label used as an argument and flattens out the result using .flat.

say "aabbccc".comb.Mix.flatmap: "→ " ~ *# OUTPUT: «(→ b␉2 → c␉3 → a␉2)␤»

In this case, the elements of the Mix are itemized to key␉value, and then mapped and flattened. Same result as

say "aabbccc".comb.Mix.map"→ " ~ * ).flat

Which is why it is deprecated in 6.d and will be eventually eliminated in 6.e.

method roll

Defined as:

multi method roll(--> Any)
multi method roll($n --> Seq)

Coerces the invocant to a list by applying its .list method and uses List.roll on it.

my Mix $m = ("þ" xx 3"ð" xx 4"ß" xx 5).Mix;
say $m.roll;    # OUTPUT: «ð␤» 
say $m.roll(5); # OUTPUT: «(ß ß þ ß þ)␤»

$m, in this case, is converted into a list and then a (weighted in this case) dice is rolled on it. See also List.roll for more information.

method iterator

Defined as:

multi method iterator(Any:)

Returns the object as an iterator after converting it to a list. This is the function called from the for statement.

.say for 3# OUTPUT: «3␤»

Most subclasses redefine this method for optimization, so it's mostly types that do not actually iterate the ones that actually use this implementation.

method pick

Defined as:

multi method pick(--> Any)
multi method pick($n --> Seq)

Coerces the invocant to a list by applying its .list method and uses List.pick on it.

my Range $rg = 'α'..'ω';
say $rg.pick(3); # OUTPUT: «(β α σ)␤»

method skip

Defined as:

multi method skip()
multi method skip(Whatever)
multi method skip(Callable:D $w)
multi method skip(Int() $n)

Creates a Seq from 1-item list's iterator and uses Seq.skip on it, please check that document for real use cases; calling skip without argument is equivalent to skip(1).

Calling it with Whatever will return an empty iterator:

say <1 2 3>.skip(*);   # OUTPUT: «()␤»

The multi that uses a Callable is intended mainly to be used this way:

say <1 2 3>.skip(*-1); # OUTPUT: «(3)␤»

Instead of throwing away the first $n elements, it throws away everything but the elements indicated by the WhateverCode, in this case all but the last one.

method prepend

Defined as:

multi method prepend(--> Array)
multi method prepend(@values --> Array)

Called with no arguments on an empty variable, it initializes it as an empty Array; if called with arguments, it creates an array and then applies Array.prepend on it.

my $a;
say $a.prepend# OUTPUT: «[]␤» 
say $a;         # OUTPUT: «[]␤» 
my $b;
say $b.prepend(1,2,3); # OUTPUT: «[1 2 3]␤»

method unshift

Defined as:

multi method unshift(--> Array)
multi method unshift(@values --> Array)

Initializes Any variable as empty Array and calls Array.unshift on it.

my $a;
say $a.unshift# OUTPUT: «[]␤» 
say $a;         # OUTPUT: «[]␤» 
my $b;
say $b.unshift([1,2,3]); # OUTPUT: «[[1 2 3]]␤»

method first

Defined as:

multi method first(Bool:D $t)
multi method first(Regex:D $test:$end*%a)
multi method first(Callable:D $test:$end*%a is copy)
multi method first(Mu $test:$end*%a)
multi method first(:$end*%a)
multi sub first(Bool:D $t|)
multi sub first(Mu $test+values*%a)

In general, coerces the invocant to a list by applying its .list method and uses List.first on it.

However, this is a multi with different signatures, which are implemented with (slightly) different behavior, although using it as a subroutine is equivalent to using it as a method with the second argument as the object.

For starters, using a Bool as the argument will always return a Failure. The form that uses a $test will return the first element that smartmatches it, starting from the end if :end is used.

say (3..33).first;           # OUTPUT: «3␤» 
say (3..33).first(:end);     # OUTPUT: «33␤» 
say (⅓,⅔…30).first0xF );   # OUTPUT: «15␤» 
say first 0xF, (⅓,⅔…30);     # OUTPUT: «15␤» 
say (3..33).first( /\d\d/ ); # OUTPUT: «10␤»

The third and fourth examples use the Mu $test forms which smartmatches and returns the first element that does. The last example uses as a test a regex for numbers with two figures, and thus the first that meets that criterion is number 10. This last form uses the Callable multi:

say (⅓,⅔…30).first* %% 11:end:kv ); # OUTPUT: «(65 22)␤»

Besides, the search for first will start from the :end and returns the set of key/values in a list; the key in this case is simply the position it occupies in the Seq. The :kv argument, which is part of the %a argument in the definitions above, modifies what first returns, providing it as a flattened list of keys and values; for a listy object, the key will always be the index.

From version 6.d, the test can also be a Junction:

say (⅓,⅔…30).first3 | 33:kv ); # OUTPUT: «(8 3)␤»

method unique

Defined as:

multi method unique()
multi method unique:&as!:&with! )
multi method unique:&as! )
multi method unique:&with! )

Creates a sequence of unique elements either of the object or of values in the case it's called as a sub.

<1 2 2 3 3 3>.unique.say# OUTPUT: «(1 2 3)␤» 
say unique <1 2 2 3 3 3># OUTPUT: «(1 2 3)␤»

The :as and :with parameters receive functions that are used for transforming the item before checking equality, and for checking equality, since by default the === operator is used:

("1"1""2).uniqueas => Intwith => &[==] ).say#OUTPUT: «(1 2)␤»

Please see unique for additional examples that use its sub form.

method repeated

Defined as:

multi method repeated()
multi method repeated:&as!:&with! )
multi method repeated:&as! )
multi method repeated:&with! )

Similarly to unique, finds repeated elements in values (as a routine) or in the object, using the :as associative argument as a normalizing function and :with as equality function.

<1 -1 2 -2 3>.repeated(:as(&abs),:with(&[==])).say# OUTPUT: «(-1 -2)␤» 
(3+3i, 3+2i, 2+1i).repeated(as => *.re).say;        # OUTPUT: «(3+2i)␤»

It returns the last repeated element before normalization, as shown in the example above. See repeated for more examples that use its sub form.

method squish

Defined as:

multi method squish:&as!:&with = &[===] )
multi method squish:&with = &[===] )

Similar to .repeated, returns the sequence of first elements of contiguous sequences of equal elements, after normalization by the function :as, if present, and using as an equality operator the :with argument or === by default.

"aabbccddaa".comb.squish.say;             # OUTPUT: «(a b c d a)␤» 
"aABbccdDaa".comb.squish:as(&lc) ).say# OUTPUT: «(a B c d a)␤» 
(3+2i,3+3i,4+0i).squishas => *.rewith => &[==]).put#OUTPUT: «3+2i 4+0i␤» 

As shown in the last example, a sequence can contain a single element. See squish for additional sub examples.

method permutations

Defined as:

method permutations(|c)

Coerces the invocant to a list by applying its .list method and uses List.permutations on it.

say <a b c>.permutations;
# OUTPUT: «((a b c) (a c b) (b a c) (b c a) (c a b) (c b a))␤» 
say set(1,2).permutations;
# OUTPUT: «((2 => True 1 => True) (1 => True 2 => True))␤»

method join

Defined as

method join($separator = ''is nodal

Converts the object to a list by calling self.list, and calls .join on the list. Can take a separator, which is an empty string by default.

(1..3).join.say;       # OUTPUT: «123␤» 
<a b c>.join("").put# OUTPUT: «a❧b❧c␤»

method categorize

Defined as:

multi method categorize()
multi method categorize(Whatever)
multi method categorize($test:$into!:&as)
multi method categorize($test:&as)
multi sub categorize($test+items:$into!*%named )
multi sub categorize($test+items*%named )

The two first forms fail with an error message.

In its simplest form, it uses a $test whose result will be used as a key; the values of the key will be an array of the elements that produced that key as a result of the test.

say (1..13).categorize* %% 3);
say categorize* %% 31..13)
# OUTPUT: «{False => [1 2 4 5 7 8 10 11 13], True => [3 6 9 12]}␤» 

The :as argument will normalize before categorizing

say categorize* %% 3-5..5as => &abs )
# OUTPUT: «{False => [5 4 2 1 1 2 4 5], True => [3 0 3]}␤» 

The $into associative argument can be used to put the result instead of returning a new Hash

my %leap-years;
my @years = (2002..2009).map{ Date.new$_~"-01-01" ) } );
@years.categorize*.is-leap-year , into => %leap-years );
say %leap-years
# OUTPUT: 
# «{ False 
# => [2002-01-01 2003-01-01 2005-01-01 2006-01-01 2007-01-01 2009-01-01], 
#    True => [2004-01-01 2008-01-01]}␤» 

The function used to categorize can return an array indicating all possible bins their argument can be put into:

sub divisible-byInt $n --> Array(Seq) ) {
    gather {
        for <2 3 5 7> {
            take $_ if $n %% $_;
        }
    }
}
 
say (3..13).categorize&divisible-by );
# OUTPUT: 
# «{2 => [4 6 8 10 12], 3 => [3 6 9 12], 5 => [5 10], 7 => [7]}␤» 

In this case, every number in the range is classified in as many bins as it can be divided by.

method classify

Defined as:

multi method classify()
multi method classify(Whatever)
multi method classify($test:$into!:&as)
multi method classify($test:&as)
multi sub classify($test+items:$into!*%named )
multi sub classify($test+items*%named )

The two first forms will fail. The rest include a $test, which is a function that will return a scalar for every input; these will be used as keys of a hash whose values will be arrays with the elements that output that key for the test function.

my @years = (2003..2008).map{ Date.new$_~"-01-01" ) } );
@years.classify*.is-leap-year , into => my %leap-years );
say %leap-years;
# OUTPUT: «{False => [2003-01-01 2005-01-01 2006-01-01 2007-01-01], 
#           True => [2004-01-01 2008-01-01]}␤» 

Similarly to .categorize, elements can be normalized by the Callable passed with the :as argument, and it can use the :into named argument to pass a Hash the results will be classified into; in the example above, it's defined on the fly.

From version 6.d, .classify will also work with Junctions.

method reduce

Defined as:

multi method reduce(Any:U: & --> Nil)
multi method reduce(Any:D: &with)
multi sub reduce (&with+list)

Applying it to a class will always produce Nil. Applies its argument (or first argument, in case it's a sub) as an operator to all the elements in the object (or second argument), producing a single result. The argument must be an infix operator or take, in any case, two positional arguments.

(1..13).reduce( &[*] ).say# OUTPUT: «6227020800␤»

method produce

Defined as:

multi method produce(Any:U: & --> Nil)
multi method produce(Any:D: &with)
multi sub produce (&with+list)

This is similar to reduce, but returns a list with the accumulated values instead of a single result.

<10 5 3>.reduce( &[*] ).say ; # OUTPUT: «150␤» 
<10 5 3>.produce( &[*] ).say# OUTPUT: «(10 50 150)␤» 

The last element of the produced list would be the output produced by the .reduce method.

If it's a class, it will simply return Nil.

method pairs

Defined as:

multi method pairs(Any:U:)
multi method pairs(Any:D:)

Returns an empty List if the invocant is a type object:

say Num.pairs# OUTPUT: «()␤»

For a value object, it converts the invocant to a List via the list method and returns the result of List.pairs on it.

<1 2 2 3 3 3>.Bag.pairs.say;# OUTPUT: «(1 => 1 3 => 3 2 => 2)␤»

In this case, every element (with weight) in a bag is converted to a pair.

method antipairs

Defined as:

multi method antipairs(Any:U:)
multi method antipairs(Any:D:)

Returns an empty List if the invocant is a type object

Range.antipairs.say# OUTPUT: «()␤»

If it's a value object, it returns the inverted list of pairs after converting it to a list of pairs; the values will become keys and the other way round.

%(=> 1t=> 2=> 3).antipairs.say ;# OUTPUT: «(2 => t 1 => s 3 => u)␤»

method invert

Defined as:

multi method invert(Any:U:)
multi method invert(Any:D:)

Applied to a type object will return an empty list; applied to an object will convert it to a list and apply List.invert to it, that is, interchange key with value in every Pair. The resulting list needs to be a list of Pairs.

"aaabbcccc".comb.Bag.invert.say# OUTPUT: «(4 => c 3 => a 2 => b)␤»

In this case, a Bag can be converted to a list of Pairs. If the result of converting the object to a list is not a list of pairs, the method will fail.

method kv

Defined as:

multi method kv(Any:U:)
multi method kv(Any:D:)
multi sub    kv($x)

Returns an empty List if the invocant is a type object:

Sub.kv.say ;# OUTPUT: «()␤»

It calls list on the invocant for value objects and returns the result of List.kv on it as a list where keys and values will be ordered and contiguous

<1 2 3>.kv.say# OUTPUT: «(0 1 1 2 2 3)␤»

In the case of Positionals, the indices will be considered keys.

method toggle

Defined as:

method toggle(Any:D: *@conditions where .all ~~ Callable:DBool :$off  --> Seq:D)

Iterates over the invocant, producing a Seq, toggling whether the received values are propagated to the result on and off, depending on the results of calling Callables in @conditions:

say (1..15).toggle(* < 5, * > 10* < 15); # OUTPUT: «(1 2 3 4 11 12 13 14)␤» 
say (1..15).toggle(:off* > 2* < 5, * > 10* < 15); # OUTPUT: «(3 4 11 12 13 14)␤» 

Imagine a switch that's either on or off (True or False), and values are produced if it's on. By default, the initial state of that switch is in "on" position, unless :$off is set to a true value, in which case the initial state will be "off".

A Callable from the head of @conditions is taken (if any are available) and it becomes the current tester. Each value from the original sequence is tested by calling the tester Callable with that value. The state of our imaginary switch is set to the return value from the tester: if it's truthy, set switch to "on", otherwise set it to "off".

Whenever the switch is toggled (i.e. switched from "off" to "on" or from "on" to "off"), the current tester Callable is replaced by the next Callable in @conditions, if available, which will be used to test any further values. If no more tester Callables are available, the switch will remain in its current state until the end of iteration.

# our original sequence of elements: 
say list ^10# OUTPUT: «(0 1 2 3 4 5 6 7 8 9)␤» 
# toggled result: 
say ^10 .toggle: * < 4* %% 2&is-prime# OUTPUT: «(0 1 2 3 6 7)␤» 
 
# First tester Callable is `* < 4` and initial state of switch is "on". 
# As we iterate over our original sequence: 
# 0 => 0 < 4 === True  switch is on, value gets into result, switch is 
#                      toggled, so we keep using the same Callable: 
# 1 => 1 < 4 === True  same 
# 2 => 2 < 4 === True  same 
# 3 => 3 < 4 === True  same 
# 4 => 4 < 4 === False switch is now off, "4" does not make it into the 
#                      result. In addition, our switch got toggled, so 
#                      we're switching to the next tester Callable 
# 5 => 5 %% 2 === False  switch is still off, keep trying to find a value 
# 6 => 6 %% 2 === True   switch is now on, take "6" into result. The switch 
#                        toggled, so we'll use the next tester Callable 
# 7 => is-prime(7) === True  switch is still on, take value and keep going 
# 8 => is-prime(8) === False switch is now off, "8" does not make it into 
#                            the result. The switch got toggled, but we 
#                            don't have any more tester Callables, so it 
#                            will remain off for the rest of the sequence. 

Since the toggle of the switch's state loads the next tester Callable, setting :$off to a True value affects when first tester is discarded:

# our original sequence of elements: 
say <0 1 2># OUTPUT: «(0 1 2)␤» 
# toggled result: 
say <0 1 2>.toggle: * > 1# OUTPUT: «()␤» 
 
# First tester Callable is `* > 1` and initial state of switch is "on". 
# As we iterate over our original sequence: 
# 0 => 0 > 1 === False  switch is off, "0" does not make it into result. 
#                      In addition, switch got toggled, so we change the 
#                      tester Callable, and since we don't have any more 
#                      of them, the switch will remain "off" until the end 

The behavior changes when :off is used:

# our original sequence of elements: 
say <0 1 2># OUTPUT: «(0 1 2)␤» 
# toggled result: 
say <0 1 2>.toggle: :off* > 1# OUTPUT: «(2)␤» 
 
# First tester Callable is `* > 1` and initial state of switch is "off". 
# As we iterate over our original sequence: 
# 0 => 0 > 1 === False  switch is off, "0" does not make it into result. 
#                       The switch did NOT get toggled this time, so we 
#                       keep using our current tester Callable 
# 1 => 1 > 1 === False  same 
# 2 => 2 > 1 === True   switch is on, "2" makes it into the result 

method head

Defined as:

multi method head(Any:D:is raw
multi method head(Any:D: Callable:D $w)
multi method head(Any:D: $n)

Returns either the first element in the object, or the first $n if that's used.

"aaabbc".comb.Mix.head.put# OUTPUT: «c␉1␤» 
"aaabbc".comb.Mix.head.put# OUTPUT: «a␉3␤» 
say ^10 .head(5);           # OUTPUT: «(0 1 2 3 4)␤» 
say ^∞ .head(5);            # OUTPUT: «(0 1 2 3 4)␤» 
say ^10 .head;              # OUTPUT: «0␤» 
say ^∞ .head;               # OUTPUT: «0␤»

In the first two cases, the results are different since there's no defined order in Mixes. In the other cases, it returns a Seq. A Callable can be used to return all but the last elements:

say (^10).head* - 3 );# OUTPUT: «(0 1 2 3 4 5 6)␤»

method tail

Defined as:

multi method tail() is raw
multi method tail($n)

Returns the last or the list of the $n last elements of an object. $n can be a Callable, usually a WhateverCode, which will be used to get all but the first n elements of the object.

say (^12).reverse.tail ;     # OUTPUT: «0␤» 
say (^12).reverse.tail(3);   # OUTPUT: «(2 1 0)␤» 
say (^12).reverse.tail(*-7); # OUTPUT: «(4 3 2 1 0)␤» 

method tree

Defined as:

multi method tree(Any:U:)
multi method tree(Any:D:)
multi method tree(Any:D: Whatever )
multi method tree(Any:D: Int(Cool$count)
multi method tree(Any:D: @ [&first*@rest])
multi method tree(Any:D: &first*@rest)

Returns the class if it's undefined or if it's not Iterable, returns the result of applying the tree method to its invocant otherwise.

say Any.tree# OUTPUT: «Any␤»

.tree has different prototypes for Iterable elements.

my @floors = ( 'A', ('B','C', ('E','F','G')));
say @floors.tree(1).flat.elems# OUTPUT: «6␤» 
say @floors.tree(2).flat.elems# OUTPUT: «2␤» 
say @floors.tree*.join("-"),*.join(""),*.join("|"));# OUTPUT: «A-B—C—E|F|G␤» 

With a number, it iteratively applies tree to every element in the lower level; the first instance will apply .tree(0) to every element in the array, and likewise for the next example.

The second prototype applies the Whatever code passed as arguments to every level in turn; the first argument will go to level 1 and so on. tree can, thus, be a great way to process complex all levels of complex, multi-level, data structures.

method nl-out

Defined as:

method nl-out(--> Str)

Returns Str with the value of "\n". See IO::Handle.nl-out for the details.

Num.nl-out.print;     # OUTPUT: «␤» 
Whatever.nl-out.print;# OUTPUT: «␤» 
33.nl-out.print;      # OUTPUT: «␤»

method combinations

Defined as:

method combinations(|c)

Coerces the invocant to a list by applying its .list method and uses List.combinations on it.

say (^3).combinations# OUTPUT: «(() (0) (1) (2) (0 1) (0 2) (1 2) (0 1 2))␤» 

method grep

Defined as:

method grep(Mu $matcher:$k:$kv:$p:$v --> Seq)

Coerces the invocant to a list by applying its .list method and uses List.grep on it.

Based on $matcher value can be either ((Any)) or empty List.

my $a;
say $a.grep({ True }); # OUTPUT: «((Any))␤» 
say $a.grep({ $_ });   # OUTPUT: «()␤»

method append

Defined as:

multi method append(Any:U \SELF: |values --> Array)

In the case the instance is not a positional-thing, it instantiates it as a new Array, otherwise clone the current instance. After that, it appends the values passed as arguments to the array obtained calling Array.append on it.

my $a;
say $a.append# OUTPUT: «[]␤» 
my $b;
say $b.append((1,2,3)); # OUTPUT: «[1 2 3]␤»

method values

Defined as:

multi method values(Any:U:)
multi method values(Any:D:)

Will return an empty list for undefined or class arguments, and the object converted to a list otherwise.

say (1..3).values# OUTPUT: «(1 2 3)␤» 
say List.values;   # OUTPUT: «()␤»

method collate

Defined as:

method collate()

Collate sorts taking into account Unicode grapheme characteristics; that is, sorting more or less as one would expect instead of using the order in which their codepoints appear. collate will behave this way if the object it is applied to is Iterable.

say ('a''Z').sort# (Z a) 
say ('a''Z').collate# (a Z) 
say <ä a o ö>.collate# (a ä o ö) 
my %hash = 'aa' => 'value''Za' => 'second';
say %hash.collate# (aa => value Za => second); 

This method is affected by the $*COLLATION variable, which configures the four collation levels. While the Primary, Secondary and Tertiary mean different things for different scripts, for the Latin script used in English they mostly correspond with Primary being Alphabetic, Secondary being Diacritics and Tertiary being Case.

In the example below you can see how when we disable tertiary collation which in Latin script generally is for case, and also disable quaternary which breaks any ties by checking the codepoint values of the strings, we get Same back for A and a:

$*COLLATION.set(:quaternary(False), :tertiary(False));
say 'a' coll 'A'#OUTPUT: «Same␤» 
say ('a','A').collate == ('A','a').collate# OUTPUT: «True␤»

The variable affects the coll operator as shown as well as this method.

method cache

Defined as:

method cache()

Provides a List representation of the object itself, calling the method list on the instance.

method batch

Defined as:

multi method batch(Int:D $batch)
multi method batch(Int:D :$elems!)

Coerces the invocant to a list by applying its .list method and uses List.batch on it.

method rotor

Defined as:

multi method rotor(Any:D: Int:D $batch:$partial)
multi method rotor(Any:D: *@cycle:$partial)

Groups the elements of the object in lists of $batch elements.

say (3..9).rotor(3); # OUTPUT: «((3 4 5) (6 7 8))␤»

With the :partial named argument, it will also include lists that do not get to be the $batch size:

say (3..10).rotor(3:partial); # OUTPUT: «((3 4 5) (6 7 8) (9 10))␤»

.rotor can be called with an array of integers and pairs, which will be applied in turn. While integers will establish the batch size, as above, Pairs will use the key as batch size and the value as number of elements to skip if it's positive, or overlap if it's negative.

say (3..11).rotor(32 => 13 => -2:partial);
# OUTPUT: «((3 4 5) (6 7) (9 10 11) (10 11))␤»

In this case, the first batch (ruled by an integer) has 3 elements; the second one has 2 elements (key of the pair), but skips one (the number 8); the third one has size 2 (because partials are allowed), and an overlap of 2 also.

Please see also list.rotor for examples applied to lists.

method sum

Defined as:

method sum() is nodal

If the content is iterable, it returns the sum of the values after pulling them one by one.

(3,2,1).sum# OUTPUT: «6␤» 
say 3.sum;   # OUTPUT: «3␤» 

It will fail if any of the elements cannot be converted to a number.

Type Graph

Type relations for Any
perl6-type-graph cluster: Mu children cluster: Pod:: top level cluster: Date/time handling cluster: Collection roles Any Any Mu Mu Any->Mu Junction Junction Junction->Mu Pod::Config Pod::Config Pod::Config->Any Pod::Block Pod::Block Pod::Block->Any Date Date Date->Any Dateish Dateish Date->Dateish DateTime DateTime DateTime->Any DateTime->Dateish DateTime-local-timezone DateTime-local-timezone Positional Positional Associative Associative Baggy Baggy QuantHash QuantHash Baggy->QuantHash AST AST AST->Any Cool Cool Cool->Any Iterable Iterable List List List->Positional List->Cool List->Iterable Array Array Array->List Attribute Attribute Attribute->Any Backtrace Backtrace Backtrace->Any Backtrace::Frame Backtrace::Frame Backtrace::Frame->Any QuantHash->Associative Bag Bag Bag->Any Bag->Baggy BagHash BagHash BagHash->Any BagHash->Baggy Stringy Stringy Blob Blob Blob->Positional Blob->Stringy Callable Callable Code Code Code->Any Code->Callable Block Block Block->Code Numeric Numeric Real Real Real->Numeric Int Int Int->Cool Int->Real Bool Bool Bool->Int Buf Buf Buf->Blob Exception Exception Exception->Any CX::Done CX::Done CX::Done->Exception X::Control X::Control CX::Done->X::Control CX::Emit CX::Emit CX::Emit->Exception CX::Emit->X::Control CX::Last CX::Last CX::Last->Exception CX::Last->X::Control CX::Next CX::Next CX::Next->Exception CX::Next->X::Control CX::Proceed CX::Proceed CX::Proceed->Exception CX::Proceed->X::Control CX::Redo CX::Redo CX::Redo->Exception CX::Redo->Exception CX::Redo->X::Control CX::Redo->X::Control CX::Return CX::Return CX::Return->Exception CX::Return->X::Control CX::Succeed CX::Succeed CX::Succeed->Exception CX::Succeed->X::Control CX::Take CX::Take CX::Take->Exception CX::Take->X::Control CX::Warn CX::Warn CX::Warn->Exception CX::Warn->X::Control CallFrame CallFrame CallFrame->Any Cancellation Cancellation Cancellation->Any Capture Capture Capture->Any Channel Channel Channel->Any Collation Collation Collation->Any CompUnit CompUnit CompUnit->Any CompUnit::Repository CompUnit::Repository CompUnit::Repository::Locally CompUnit::Repository::Locally CompUnit::Repository::FileSystem CompUnit::Repository::FileSystem CompUnit::Repository::FileSystem->Any CompUnit::Repository::FileSystem->CompUnit::Repository CompUnit::Repository::FileSystem->CompUnit::Repository::Locally CompUnit::Repository::Installable CompUnit::Repository::Installable CompUnit::Repository::Installation CompUnit::Repository::Installation CompUnit::Repository::Installation->Any CompUnit::Repository::Installation->CompUnit::Repository::Locally CompUnit::Repository::Installation->CompUnit::Repository::Installable Systemic Systemic Compiler Compiler Compiler->Any Compiler->Systemic Complex Complex Complex->Cool Complex->Numeric Str Str Str->Cool Str->Stringy ComplexStr ComplexStr ComplexStr->Complex ComplexStr->Str Scheduler Scheduler CurrentThreadScheduler CurrentThreadScheduler CurrentThreadScheduler->Any CurrentThreadScheduler->Scheduler Deprecation Deprecation Deprecation->Any Distribution Distribution Distribution::Locally Distribution::Locally Distribution::Locally->Distribution Distribution::Hash Distribution::Hash Distribution::Hash->Any Distribution::Hash->Distribution::Locally Distribution::Path Distribution::Path Distribution::Path->Any Distribution::Path->Distribution::Locally Distro Distro Distro->Any Duration Duration Duration->Cool Duration->Real Encoding Encoding Encoding->Any Encoding::Registry Encoding::Registry Encoding::Registry->Any Endian Endian Endian->Int Enumeration Enumeration Nil Nil Nil->Cool Failure Failure Failure->Nil Rational Rational Rational->Real FatRat FatRat FatRat->Cool FatRat->Rational ForeignCode ForeignCode ForeignCode->Any ForeignCode->Callable Match Match Match->Cool Match->Capture Grammar Grammar Grammar->Match Map Map Map->Associative Map->Cool Map->Iterable Hash Hash Hash->Map Sequence Sequence HyperSeq HyperSeq HyperSeq->Any HyperSeq->Iterable HyperSeq->Sequence HyperWhatever HyperWhatever HyperWhatever->Any IO IO IO::Handle IO::Handle IO::Handle->Any IO::CatHandle IO::CatHandle IO::CatHandle->IO::Handle IO::ArgFiles IO::ArgFiles IO::ArgFiles->IO::CatHandle IO::Notification IO::Notification IO::Notification->Any IO::Path IO::Path IO::Path->Cool IO::Path->IO IO::Path::Cygwin IO::Path::Cygwin IO::Path::Cygwin->IO::Path IO::Path::QNX IO::Path::QNX IO::Path::QNX->IO::Path IO::Path::Unix IO::Path::Unix IO::Path::Unix->IO::Path IO::Path::Win32 IO::Path::Win32 IO::Path::Win32->IO::Path IO::Pipe IO::Pipe IO::Pipe->IO::Handle IO::Socket IO::Socket IO::Socket::Async IO::Socket::Async IO::Socket::Async->Any IO::Socket::INET IO::Socket::INET IO::Socket::INET->Any IO::Socket::INET->IO::Socket IO::Spec IO::Spec IO::Spec->Any IO::Spec::Unix IO::Spec::Unix IO::Spec::Unix->IO::Spec IO::Spec::Cygwin IO::Spec::Cygwin IO::Spec::Cygwin->IO::Spec::Unix IO::Spec::QNX IO::Spec::QNX IO::Spec::QNX->IO::Spec::Unix IO::Spec::Win32 IO::Spec::Win32 IO::Spec::Win32->IO::Spec::Unix IO::Special IO::Special IO::Special->Any IO::Special->IO Instant Instant Instant->Cool Instant->Real IntStr IntStr IntStr->Int IntStr->Str Iterator Iterator Kernel Kernel Kernel->Any Label Label Label->Any Lock Lock Lock->Any Lock::Async Lock::Async Lock::Async->Any MOP MOP MOP->Any Routine Routine Routine->Block Macro Macro Macro->Routine Metamodel::Archetypes Metamodel::Archetypes Metamodel::Archetypes->Any Metamodel::AttributeContainer Metamodel::AttributeContainer Metamodel::BUILDPLAN Metamodel::BUILDPLAN Metamodel::BaseDispatcher Metamodel::BaseDispatcher Metamodel::BaseDispatcher->Any Metamodel::BaseType Metamodel::BaseType Metamodel::BoolificationProtocol Metamodel::BoolificationProtocol Metamodel::C3MRO Metamodel::C3MRO Metamodel::Naming Metamodel::Naming Metamodel::Documenting Metamodel::Documenting Metamodel::Versioning Metamodel::Versioning Metamodel::Stashing Metamodel::Stashing Metamodel::Finalization Metamodel::Finalization Metamodel::MethodContainer Metamodel::MethodContainer Metamodel::PrivateMethodContainer Metamodel::PrivateMethodContainer Metamodel::MultiMethodContainer Metamodel::MultiMethodContainer Metamodel::RoleContainer Metamodel::RoleContainer Metamodel::MultipleInheritance Metamodel::MultipleInheritance Metamodel::DefaultParent Metamodel::DefaultParent Metamodel::MROBasedMethodDispatch Metamodel::MROBasedMethodDispatch Metamodel::MROBasedTypeChecking Metamodel::MROBasedTypeChecking Metamodel::Trusting Metamodel::Trusting Metamodel::Mixins Metamodel::Mixins Metamodel::ClassHOW Metamodel::ClassHOW Metamodel::ClassHOW->Any Metamodel::ClassHOW->Metamodel::AttributeContainer Metamodel::ClassHOW->Metamodel::BUILDPLAN Metamodel::ClassHOW->Metamodel::BoolificationProtocol Metamodel::ClassHOW->Metamodel::C3MRO Metamodel::ClassHOW->Metamodel::Naming Metamodel::ClassHOW->Metamodel::Documenting Metamodel::ClassHOW->Metamodel::Versioning Metamodel::ClassHOW->Metamodel::Stashing Metamodel::ClassHOW->Metamodel::Finalization Metamodel::ClassHOW->Metamodel::MethodContainer Metamodel::ClassHOW->Metamodel::PrivateMethodContainer Metamodel::ClassHOW->Metamodel::MultiMethodContainer Metamodel::ClassHOW->Metamodel::RoleContainer Metamodel::ClassHOW->Metamodel::MultipleInheritance Metamodel::ClassHOW->Metamodel::DefaultParent Metamodel::ClassHOW->Metamodel::MROBasedMethodDispatch Metamodel::ClassHOW->Metamodel::MROBasedTypeChecking Metamodel::ClassHOW->Metamodel::Trusting Metamodel::ClassHOW->Metamodel::Mixins Metamodel::ConcreteRoleHOW Metamodel::ConcreteRoleHOW Metamodel::ConcreteRoleHOW->Any Metamodel::ConcreteRoleHOW->Metamodel::AttributeContainer Metamodel::ConcreteRoleHOW->Metamodel::Naming Metamodel::ConcreteRoleHOW->Metamodel::Versioning Metamodel::ConcreteRoleHOW->Metamodel::MethodContainer Metamodel::ConcreteRoleHOW->Metamodel::PrivateMethodContainer Metamodel::ConcreteRoleHOW->Metamodel::MultiMethodContainer Metamodel::ConcreteRoleHOW->Metamodel::RoleContainer Metamodel::ConcreteRoleHOW->Metamodel::MultipleInheritance Metamodel::ContainerDescriptor Metamodel::ContainerDescriptor Metamodel::ContainerDescriptor->Any Metamodel::RolePunning Metamodel::RolePunning Metamodel::TypePretense Metamodel::TypePretense Metamodel::CurriedRoleHOW Metamodel::CurriedRoleHOW Metamodel::CurriedRoleHOW->Any Metamodel::CurriedRoleHOW->Metamodel::RolePunning Metamodel::CurriedRoleHOW->Metamodel::TypePretense Metamodel::EnumHOW Metamodel::EnumHOW Metamodel::EnumHOW->Any Metamodel::EnumHOW->Metamodel::AttributeContainer Metamodel::EnumHOW->Metamodel::BUILDPLAN Metamodel::EnumHOW->Metamodel::BaseType Metamodel::EnumHOW->Metamodel::BoolificationProtocol Metamodel::EnumHOW->Metamodel::Naming Metamodel::EnumHOW->Metamodel::Stashing Metamodel::EnumHOW->Metamodel::MethodContainer Metamodel::EnumHOW->Metamodel::MultiMethodContainer Metamodel::EnumHOW->Metamodel::RoleContainer Metamodel::EnumHOW->Metamodel::MROBasedMethodDispatch Metamodel::EnumHOW->Metamodel::MROBasedTypeChecking Metamodel::GenericHOW Metamodel::GenericHOW Metamodel::GenericHOW->Any Metamodel::GenericHOW->Metamodel::Naming Metamodel::GrammarHOW Metamodel::GrammarHOW Metamodel::GrammarHOW->Metamodel::DefaultParent Metamodel::GrammarHOW->Metamodel::ClassHOW Metamodel::MethodDelegation Metamodel::MethodDelegation Metamodel::MethodDispatcher Metamodel::MethodDispatcher Metamodel::MethodDispatcher->Metamodel::BaseDispatcher Metamodel::ModuleHOW Metamodel::ModuleHOW Metamodel::ModuleHOW->Any Metamodel::ModuleHOW->Metamodel::Naming Metamodel::ModuleHOW->Metamodel::Documenting Metamodel::ModuleHOW->Metamodel::Versioning Metamodel::ModuleHOW->Metamodel::Stashing Metamodel::ModuleHOW->Metamodel::TypePretense Metamodel::ModuleHOW->Metamodel::MethodDelegation Metamodel::MultiDispatcher Metamodel::MultiDispatcher Metamodel::MultiDispatcher->Metamodel::BaseDispatcher Metamodel::NativeHOW Metamodel::NativeHOW Metamodel::NativeHOW->Any Metamodel::NativeHOW->Metamodel::C3MRO Metamodel::NativeHOW->Metamodel::Naming Metamodel::NativeHOW->Metamodel::Documenting Metamodel::NativeHOW->Metamodel::Versioning Metamodel::NativeHOW->Metamodel::Stashing Metamodel::NativeHOW->Metamodel::MultipleInheritance Metamodel::NativeHOW->Metamodel::MROBasedMethodDispatch Metamodel::NativeHOW->Metamodel::MROBasedTypeChecking Metamodel::PackageHOW Metamodel::PackageHOW Metamodel::PackageHOW->Any Metamodel::PackageHOW->Metamodel::Naming Metamodel::PackageHOW->Metamodel::Documenting Metamodel::PackageHOW->Metamodel::Stashing Metamodel::PackageHOW->Metamodel::TypePretense Metamodel::PackageHOW->Metamodel::MethodDelegation Metamodel::ParametricRoleGroupHOW Metamodel::ParametricRoleGroupHOW Metamodel::ParametricRoleGroupHOW->Any Metamodel::ParametricRoleGroupHOW->Metamodel::BoolificationProtocol Metamodel::ParametricRoleGroupHOW->Metamodel::Naming Metamodel::ParametricRoleGroupHOW->Metamodel::Stashing Metamodel::ParametricRoleGroupHOW->Metamodel::RolePunning Metamodel::ParametricRoleGroupHOW->Metamodel::TypePretense Metamodel::ParametricRoleHOW Metamodel::ParametricRoleHOW Metamodel::ParametricRoleHOW->Any Metamodel::ParametricRoleHOW->Metamodel::AttributeContainer Metamodel::ParametricRoleHOW->Metamodel::Naming Metamodel::ParametricRoleHOW->Metamodel::Documenting Metamodel::ParametricRoleHOW->Metamodel::Versioning Metamodel::ParametricRoleHOW->Metamodel::Stashing Metamodel::ParametricRoleHOW->Metamodel::MethodContainer Metamodel::ParametricRoleHOW->Metamodel::PrivateMethodContainer Metamodel::ParametricRoleHOW->Metamodel::MultiMethodContainer Metamodel::ParametricRoleHOW->Metamodel::RoleContainer Metamodel::ParametricRoleHOW->Metamodel::MultipleInheritance Metamodel::ParametricRoleHOW->Metamodel::RolePunning Metamodel::ParametricRoleHOW->Metamodel::TypePretense Metamodel::Primitives Metamodel::Primitives Metamodel::Primitives->Any Metamodel::StaticLexPad Metamodel::StaticLexPad Metamodel::StaticLexPad->Any Metamodel::SubsetHOW Metamodel::SubsetHOW Metamodel::SubsetHOW->Any Metamodel::SubsetHOW->Metamodel::Naming Metamodel::SubsetHOW->Metamodel::Documenting Metamodel::WrapDispatcher Metamodel::WrapDispatcher Metamodel::WrapDispatcher->Metamodel::BaseDispatcher Method Method Method->Routine Mixy Mixy Mixy->Baggy Mix Mix Mix->Any Mix->Mixy MixHash MixHash MixHash->Any MixHash->Mixy Uni Uni Uni->Any Uni->Positional Uni->Stringy NFC NFC NFC->Uni NFD NFD NFD->Uni NFKC NFKC NFKC->Uni NFKD NFKD NFKD->Uni Num Num Num->Cool Num->Real NumStr NumStr NumStr->Str NumStr->Num NumericEnumeration NumericEnumeration ObjAt ObjAt ObjAt->Any Order Order Order->Int Pair Pair Pair->Any Pair->Associative Parameter Parameter Parameter->Any Perl Perl Perl->Any Perl->Systemic Pod::Block::Code Pod::Block::Code Pod::Block::Code->Pod::Block Pod::Block::Comment Pod::Block::Comment Pod::Block::Comment->Pod::Block Pod::Block::Declarator Pod::Block::Declarator Pod::Block::Declarator->Pod::Block Pod::Block::Named Pod::Block::Named Pod::Block::Named->Pod::Block Pod::Block::Para Pod::Block::Para Pod::Block::Para->Pod::Block Pod::Block::Table Pod::Block::Table Pod::Block::Table->Pod::Block Pod::Defn Pod::Defn Pod::Defn->Pod::Block Pod::FormattingCode Pod::FormattingCode Pod::FormattingCode->Pod::Block Pod::Heading Pod::Heading Pod::Heading->Pod::Block Pod::Item Pod::Item Pod::Item->Pod::Block PositionalBindFailover PositionalBindFailover PredictiveIterator PredictiveIterator PredictiveIterator->Iterator Proc Proc Proc->Any Proc::Async Proc::Async Proc::Async->Any Promise Promise Promise->Any PromiseStatus PromiseStatus PromiseStatus->Int Proxy Proxy Proxy->Any PseudoStash PseudoStash PseudoStash->Map RaceSeq RaceSeq RaceSeq->Any RaceSeq->Iterable RaceSeq->Sequence Range Range Range->Positional Range->Cool Range->Iterable Rat Rat Rat->Cool Rat->Rational RatStr RatStr RatStr->Str RatStr->Rat Regex Regex Regex->Method Routine::WrapHandle Routine::WrapHandle Routine::WrapHandle->Any Scalar Scalar Scalar->Any Semaphore Semaphore Semaphore->Any Seq Seq Seq->Cool Seq->Iterable Seq->PositionalBindFailover Setty Setty Setty->QuantHash Set Set Set->Any Set->Setty SetHash SetHash SetHash->Any SetHash->Setty Signal Signal Signal->Int Signature Signature Signature->Any Slip Slip Slip->List Stash Stash Stash->Hash StrDistance StrDistance StrDistance->Cool StringyEnumeration StringyEnumeration Sub Sub Sub->Routine Submethod Submethod Submethod->Routine Supplier Supplier Supplier->Any Supplier::Preserving Supplier::Preserving Supplier::Preserving->Supplier Supply Supply Supply->Any Tap Tap Tap->Any Telemetry Telemetry Telemetry->Any Telemetry::Instrument::Thread Telemetry::Instrument::Thread Telemetry::Instrument::Thread->Any Telemetry::Instrument::ThreadPool Telemetry::Instrument::ThreadPool Telemetry::Instrument::ThreadPool->Any Telemetry::Instrument::Usage Telemetry::Instrument::Usage Telemetry::Instrument::Usage->Any Telemetry::Period Telemetry::Period Telemetry::Period->Associative Telemetry::Period->Telemetry Telemetry::Sampler Telemetry::Sampler Telemetry::Sampler->Any Test Test Test->Any Thread Thread Thread->Any ThreadPoolScheduler ThreadPoolScheduler ThreadPoolScheduler->Any ThreadPoolScheduler->Scheduler UInt UInt UInt->Any VM VM VM->Any VM->Systemic ValueObjAt ValueObjAt ValueObjAt->ObjAt Variable Variable Variable->Any Version Version Version->Any Whatever Whatever Whatever->Any WhateverCode WhateverCode WhateverCode->Code atomicint atomicint atomicint->Int int int int->Int utf8 utf8 utf8->Any utf8->Blob

Expand above chart

Routines supplied by class Mu

Any inherits from class Mu, which provides the following routines:

(Mu) method iterator

Defined as:

method iterator(--> Iterator)

Coerces the invocant to a list by applying its .list method and uses iterator on it.

my $it = Mu.iterator;
say $it.pull-one# OUTPUT: «(Mu)␤» 
say $it.pull-one# OUTPUT: «IterationEnd␤»

(Mu) method defined

Declared as

multi method defined(   --> Bool:D)

Returns False on a type object, and True otherwise.

say Int.defined;                # OUTPUT: «False␤» 
say 42.defined;                 # OUTPUT: «True␤»

A few types (like Failure) override defined to return False even for instances:

sub fails() { fail 'oh noe' };
say fails().defined;            # OUTPUT: «False␤»

(Mu) routine defined

Declared as

multi sub defined(Mu --> Bool:D)

invokes the .defined method on the object and returns its result.

(Mu) routine isa

multi method isa(Mu $type     --> Bool:D)
multi method isa(Str:D $type  --> Bool:D)

Returns True if the invocant is an instance of class $type, a subset type or a derived class (through inheritance) of $type. does is similar, but includes roles.

my $i = 17;
say $i.isa("Int");   # OUTPUT: «True␤» 
say $i.isa(Any);     # OUTPUT: «True␤» 
role Truish {};
my $but-true = 0 but Truish;
say $but-true.^name;        # OUTPUT: «Int+{Truish}␤» 
say $but-true.does(Truish); # OUTPUT: «True␤» 
say $but-true.isa(Truish);  # OUTPUT: «False␤»

(Mu) routine does

method does(Mu $type --> Bool:D)

Returns True if and only if the invocant conforms to type $type.

my $d = Date.new('2016-06-03');
say $d.does(Dateish);             # True    (Date does role Dateish) 
say $d.does(Any);                 # True    (Date is a subclass of Any) 
say $d.does(DateTime);            # False   (Date is not a subclass of DateTime) 

Unlike isa, which returns True only for superclasses, does includes both superclasses and roles.

say $d.isa(Dateish); # OUTPUT: «False␤» 

Using the smartmatch operator ~~ is a more idiomatic alternative.

my $d = Date.new('2016-06-03');
say $d ~~ Dateish;                # OUTPUT: «True␤» 
say $d ~~ Any;                    # OUTPUT: «True␤» 
say $d ~~ DateTime;               # OUTPUT: «False␤»

(Mu) routine Bool

multi sub    Bool(Mu --> Bool:D)
multi method Bool(   --> Bool:D)

Returns False on the type object, and True otherwise.

Many built-in types override this to be False for empty collections, the empty string or numerical zeros

say Mu.Bool;                    # OUTPUT: «False␤» 
say Mu.new.Bool;                # OUTPUT: «True␤» 
say [123].Bool;             # OUTPUT: «True␤» 
say [].Bool;                    # OUTPUT: «False␤» 
say %hash => 'full' ).Bool;   # OUTPUT: «True␤» 
say {}.Bool;                    # OUTPUT: «False␤» 
say "".Bool;                    # OUTPUT: «False␤» 
say 0.Bool;                     # OUTPUT: «False␤» 
say 1.Bool;                     # OUTPUT: «True␤» 
say "0".Bool;                   # OUTPUT: «True␤»

(Mu) method Capture

Declared as:

method Capture(Mu:D: --> Capture:D)

Returns a Capture with named arguments corresponding to invocant's public attributes:

class Foo {
    has $.foo = 42;
    has $.bar = 70;
    method bar { 'something else' }
}.new.Capture.say# OUTPUT: «\(:bar("something else"), :foo(42))␤»

(Mu) method Str

multi method Str(--> Str)

Returns a string representation of the invocant, intended to be machine readable. Method Str warns on type objects, and produces the empty string.

say Mu.Str;   # Use of uninitialized value of type Mu in string context. 
my @foo = [2,3,1];
say @foo.Str  # OUTPUT: «2 3 1␤»

(Mu) routine gist

multi sub    gist(+args --> Str)
multi method gist(   --> Str)

Returns a string representation of the invocant, optimized for fast recognition by humans. As such lists will be truncated at 100 elements. Use .perl to get all elements.

The default gist method in Mu re-dispatches to the perl method for defined invocants, and returns the type name in parenthesis for type object invocants. Many built-in classes override the case of instances to something more specific that may truncate output.

gist is the method that say calls implicitly, so say $something and say $something.gist generally produce the same output.

say Mu.gist;        # OUTPUT: «(Mu)␤» 
say Mu.new.gist;    # OUTPUT: «Mu.new␤»

(Mu) routine perl

multi method perl(--> Str)

Returns a Perlish representation of the object (i.e., can usually be re-evaluated with EVAL to regenerate the object). The exact output of perl is implementation specific, since there are generally many ways to write a Perl expression that produces a particular value.

(Mu) method item

method item(Mu \item:is raw

Forces the invocant to be evaluated in item context and returns the value of it.

say [1,2,3].item.perl;          # OUTPUT: «$[1, 2, 3]␤» 
say %apple => 10 ).item.perl# OUTPUT: «${:apple(10)}␤» 
say "abc".item.perl;            # OUTPUT: «"abc"␤»

(Mu) method self

method self(--> Mu)

Returns the object it is called on.

(Mu) method clone

multi method clone(Mu:U: *%twiddles)
multi method clone(Mu:D: *%twiddles)

This method will clone type objects, or die if it's invoked with any argument.

say Num.clone:yes )
# OUTPUT: «(exit code 1) Cannot set attribute values when cloning a type object␤  in block <unit>␤␤» 

If invoked with value objects, it creates a shallow clone of the invocant, including shallow cloning of private attributes. Alternative values for public attributes can be provided via named arguments with names matching the attributes' names.

class Point2D {
    has ($.x$.y);
    multi method gist(Point2D:D:{
        "Point($.x$.y)";
    }
}
 
my $p = Point2D.new(x => 2=> 3);
 
say $p;                     # OUTPUT: «Point(2, 3)␤» 
say $p.clone(=> -5);      # OUTPUT: «Point(2, -5)␤» 

Note that .clone does not go the extra mile to shallow-copy @. and %. sigiled attributes and, if modified, the modifications will still be available in the original object:

class Foo {
    has $.foo is rw = 42;
    has &.boo is rw = { say "Hi" };
    has @.bar       = <a b>;
    has %.baz       = <a b c d>;
}
 
my $o1 = Foo.new;
with my $o2 = $o1.clone {
    .foo = 70;
    .bar = <Z Y>;
    .baz = <Z Y X W>;
    .boo = { say "Bye" };
}
 
# Hash and Array attribute modifications in clone appear in original as well: 
say $o1;
# OUTPUT: «Foo.new(foo => 42, bar => ["Z", "Y"], baz => {:X("W"), :Z("Y")}, …␤» 
say $o2;
# OUTPUT: «Foo.new(foo => 70, bar => ["Z", "Y"], baz => {:X("W"), :Z("Y")}, …␤» 
$o1.boo.(); # OUTPUT: «Hi␤» 
$o2.boo.(); # OUTPUT: «Bye␤» 

To clone those, you could implement your own .clone that clones the appropriate attributes and passes the new values to Mu.clone, for example, via nextwith.

class Bar {
    has $.quux;
    has @.foo = <a b>;
    has %.bar = <a b c d>;
    method clone { nextwith :foo(@!foo.clone), :bar(%!bar.clone), |%_  }
}
 
my $o1 = Bar.new:42quux );
with my $o2 = $o1.clone {
    .foo = <Z Y>;
    .bar = <Z Y X W>;
}
 
# Hash and Array attribute modifications in clone do not affect original: 
say $o1;
# OUTPUT: «Bar.new(quux => 42, foo => ["a", "b"], bar => {:a("b"), :c("d")})␤» 
say $o2;
# OUTPUT: «Bar.new(quux => 42, foo => ["Z", "Y"], bar => {:X("W"), :Z("Y")})␤» 

The |%_ is needed to slurp the rest of the attributes that would have been copied via shallow copy.

(Mu) method new

multi method new(*%attrinit)
multi method new($*@)

Default method for constructing (create + initialize) new objects of a class. This method expects only named arguments which are then used to initialize attributes with accessors of the same name.

Classes may provide their own new method to override this default.

new triggers an object construction mechanism that calls submethods named BUILD in each class of an inheritance hierarchy, if they exist. See the documentation on object construction for more information.

(Mu) method bless

method bless(*%attrinit --> Mu:D)

Low-level object construction method, usually called from within new, implicitly from the default constructor, or explicitly if you create your own constructor. bless creates a new object of the same type as the invocant, using the named arguments to initialize attributes and returns the created object.

It is usually invoked within custom new method implementations:

class Point {
    has $.x;
    has $.y;
    multi method new($x$y{
        self.bless(:$x:$y);
    }
}
my $p = Point.new(-11);

In this case we are declaring new as a multi method so that we can still use the default constructor like this: Point.new( x => 3, y => 8 ). In this case we are declaring this new method simply to avoid the extra syntax of using pairs when creating the object. self.bless returns the object, which is in turn returned by new.

However, in general, implementing a customized new method might not be the best way of initializing a class, even more so if the default constructor is disabled, since it can make it harder to correctly initialize the class from a subclass. For instance, in the above example, the new implementation takes two positional arguments that must be passed from the subclass to the superclass in the exact order. That is not a real problem if it's documented, but take into account bless will eventually be calling BUILD in the class that is being instantiated. This might result in some unwanted problems, like having to create a BUILD submethod to serve it correctly:

class Point {
    has Int $.x;
    has Int $.y;
    multi method new($x$y{
        self.bless(:$x:$y);
    }
}
 
class Point-with-ID is Point {
    has Int $.ID  is rw = 0;
 
    submethod BUILD*%args ) {
        say %args;                # OUTPUT: «{x => 1, y => 2}␤» 
        for self.^attributes -> $attr {
            if $attr.Str ~~ /ID/ {
                $attr.set_valueself"*" ~ %args<x> ~ "-" ~ %args<y> ) ;
            }
        }
    }
}
 
my $p = Point-with-ID.new(1,2);
say $p.perl;
# OUTPUT: «Point-with-ID.new(ID => "*1-2", x => 1, y => 2)␤» 

In this code, bless, called within Point.new, is eventually calling BUILD with the same parameters. We have to create a convoluted way of using the $.ID attribute using the metaobject protocol so that we can instantiate it and thus serve that new constructor, which can be called on Point-with-ID since it is a subclass.

We might have to use something similar if we want to instantiate superclasses. bless will help us with that, since it is calling across all the hierarchy:

class Str-with-ID is Str {
    my $.counter = 0;
    has Int $.ID  is rw = 0;
 
    multi method new$str ) {
        self.blessvalue => $strID => $.counter++ );
    }
 
    submethod BUILD*%args ) {
        for self.^attributes -> $attr {
            if $attr.Str ~~ /ID/ {
                $attr.set_valueself%args<ID> ) ;
            }
        }
    }
}
 
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 are enriching Str with an auto-incrementing ID. We create a new since we want to initialize it with a string and, besides, we need to instantiate the superclass. We do so using bless from within new. bless is going to call Str.BUILD. It will *capture* the value it's looking for, the pair value = $str> and initialize itself. But we have to initialize also the properties of the subclass, which is why within BUILD we use the previously explained method to initialize $.ID with the value that is in the %args variable. As shown in the output, the objects will be correctly initialized with its ID, and will correctly behave as Str, converting themselves in just the string in the say statement, and including the ID property as required.

For more details see the documentation on object construction.

(Mu) method CREATE

method CREATE(--> Mu:D)

Allocates a new object of the same type as the invocant, without initializing any attributes.

say Mu.CREATE.defined;  # OUTPUT: «True␤»

(Mu) method print

multi method print(--> Bool:D)

Prints value to $*OUT after stringification using .Str method without adding a newline at end.

"abc\n".print;          # RESULT: «abc␤»

(Mu) method put

multi method put(--> Bool:D)

Prints value to $*OUT, adding a newline at end, and if necessary, stringifying non-Str object using the .Str method.

"abc".put;              # RESULT: «abc␤»

(Mu) method say

multi method say()

Will say to standard output.

say 42;                 # OUTPUT: «42␤»

What say actually does is, thus, deferred to the actual subclass. In most cases it calls .gist on the object, returning a compact string representation.

In non-sink context, say will always return True.

say (1,[1,2],"foo",Mu).map: so *.say ;
# OUTPUT: «1␤[1 2]␤foo␤(Mu)␤(True True True True)␤»

However, this behavior is just conventional and you shouldn't trust it for your code. It's useful, however, to explain certain behaviors.

say is first printing out in *.say, but the outermost say is printing the True values returned by the so operation.

(Mu) method ACCEPTS

multi method ACCEPTS(Mu:U: $other)

ACCEPTS is the method that smartmatching with the infix ~~ operator and given/when invokes on the right-hand side (the matcher).

The Mu:U multi performs a type check. Returns True if $other conforms to the invocant (which is always a type object or failure).

say 42 ~~ Mu;           # OUTPUT: «True␤» 
say 42 ~~ Int;          # OUTPUT: «True␤» 
say 42 ~~ Str;          # OUTPUT: «False␤»

Note that there is no multi for defined invocants; this is to allow autothreading of junctions, which happens as a fallback mechanism when no direct candidate is available to dispatch to.

(Mu) method WHICH

multi method WHICH(--> ObjAt:D)

Returns an object of type ObjAt which uniquely identifies the object. Value types override this method which makes sure that two equivalent objects return the same return value from WHICH.

say 42.WHICH eq 42.WHICH;       # OUTPUT: «True␤»

(Mu) method WHERE

method WHERE(--> Int)

Returns an Int representing the memory address of the object.

(Mu) method WHY

multi method WHY(--> Pod::Block::Declarator)

Returns the attached Pod::Block::Declarator.

For instance:

#| Initiate a specified spell normally 
sub cast(Spell $s{
  do-raw-magic($s);
}
#= (do not use for class 7 spells) 
say &cast.WHY;
# OUTPUT: «Initiate a specified spell normally␤(do not use for class 7 spells)␤» 

See Pod declarator blocks for details about attaching Pod to variables, classes, functions, methods, etc.

(Mu) trait is export

multi sub trait_mod:<is>(Mu:U \type:$export!)

Marks a type as being exported, that is, available to external users.

my class SomeClass is export { }

A user of a module or class automatically gets all the symbols imported that are marked as is export.

See Exporting and Selective Importing Modules for more details.

(Mu) method return

method return()

The method return will stop execution of a subroutine or method, run all relevant phasers and provide invocant as a return value to the caller. If a return type constraint is provided it will be checked unless the return value is Nil. A control exception is raised and can be caught with CONTROL.

sub f { (1|2|3).return };
say f(); # OUTPUT: «any(1, 2, 3)␤»

(Mu) method return-rw

Same as method return except that return-rw returns a writable container to the invocant (see more details here: return-rw).

(Mu) method emit

method emit()

Emits the invocant into the enclosing supply or react block.

react { whenever supply { .emit for "foo"42.5 } {
    say "received {.^name} ($_)";
}}
 
# OUTPUT: 
# received Str (foo) 
# received Int (42) 
# received Rat (0.5)

(Mu) method take

method take()

Returns the invocant in the enclosing gather block.

sub insert($sep+@list{
    gather for @list {
        FIRST .takenext;
        take slip $sep.item
    }
}
 
say insert ':', <a b c>;
# OUTPUT: «(a : b : c)␤»

(Mu) routine take

sub take(\item)

Takes the given item and passes it to the enclosing gather block.

#| randomly select numbers for lotto 
my $num-selected-numbers = 6;
my $max-lotto-numbers = 49;
gather for ^$num-selected-numbers {
    take (1 .. $max-lotto-numbers).pick(1);
}.say;    # six random values

(Mu) routine take-rw

sub take-rw(\item)

Returns the given item to the enclosing gather block, without introducing a new container.

my @a = 1...3;
sub f(@list){ gather for @list { take-rw $_ } };
for f(@a{ $_++ };
say @a;
# OUTPUT: «[2 3 4]␤»

(Mu) method so

method so()

Evaluates the item in boolean context (and thus, for instance, collapses Junctions), and returns the result. It is the opposite of not, and equivalent to the ? operator.

One can use this method similarly to the English sentence: "If that is so, then do this thing". For instance,

my @args = <-a -e -b -v>;
my $verbose-selected = any(@argseq '-v' | '-V';
if $verbose-selected.so {
    say "Verbose option detected in arguments";
} # OUTPUT: «Verbose option detected in arguments␤»

The $verbose-selected variable in this case contains a Junction, whose value is any(any(False, False), any(False, False), any(False, False), any(True, False)). That is actually a truish value; thus, negating it will yield False. The negation of that result will be True. so is performing all those operations under the hood.

(Mu) method not

method not()

Evaluates the item in boolean context (leading to final evaluation of Junctions, for instance), and negates the result. It is the opposite of so and its behavior is equivalent to the ! operator.

my @args = <-a -e -b>;
my $verbose-selected = any(@argseq '-v' | '-V';
if $verbose-selected.not {
    say "Verbose option not present in arguments";
} # OUTPUT: «Verbose option not present in arguments␤»

Since there is also a prefix version of not, this example reads better as:

my @args = <-a -e -b>;
my $verbose-selected = any(@argseq '-v' | '-V';
if not $verbose-selected {
    say "Verbose option not present in arguments";
} # OUTPUT: «Verbose option not present in arguments␤»