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:

method list(--> List:D)

Interprets the invocant as a list, and returns that List.

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

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;
dd %h<a>;      # Any (and therefore undefined) 
%h<a>.push(1); # .push on Any 
dd %h;         # «Hash %h = {:a($[1])}␤» # please note the Array 

routine reverse

Defined as:

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

Returns a list 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

Sorts iterables with infix:<cmp> or given code object and returns a new List.

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(\SELF: &block;; :$label:$item)
multi method map(HyperIterable:D: &block;; :$label)

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.

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.

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

method duckmap

Defined as:

method duckmap(&blockis rw is nodal

duckmap will apply &block on each element and return a new list with defined return values of the block. For undefined return values, duckmap will try to descend into the element if that element implements Iterable.

my @a = [1,[2,3],4];
dd @a.duckmap({ $_ ~~ Int ?? $_++ !! Any });
# OUTPUT: «(1, (2, 3), 4)␤» 

method flat

Defined as:

method flat(--> Seq:Dis nodal

Interprets the invocant as a list, flattens it, and returns that list. Please note that .flat will not solve the halting problem for you. If you flat an infinite list .flat may return that infinite list, eating all your RAM in the process.

say ((12), (3)).elems;        # OUTPUT: «2␤» 
say ((12), (3)).flat.elems;   # OUTPUT: «3␤» 

Please note that flat does not recurse into sub lists. You have to recurse by hand or reconsider your data structures. A single level of nesting can often be handled with destructuring in signatures. For deeper structures you may consider gather/take to create a lazy list.

my @a = [[1,2,3],[[4,5],6,7]];
say gather deepmap *.take@a# OUTPUT: «(1 2 3 4 5 6 7)␤» 

method eager

Defined as:

method eager(--> Seq:Dis nodal

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

say (1..10).eager;              # OUTPUT: «(1 2 3 4 5 6 7 8 9 10)␤» 

method elems

Defined as:

method elems(--> Int:Dis nodal

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␤» 

method end

method end(--> Any:Dis nodal

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:

method pairup(--> Seq:Dis nodal

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 is passed through, and the next list item, if any, is considered to be a key again).

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

sub exit

Defined as:

sub exit(Int() $status = 0)

Exits the current process with return code $status.

sub item

Defined as:

proto sub item(|) is pure
multi sub item(\x)
multi sub item(|c)
multi sub 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

Coerce the invocant to Array.

method List

Defined as:

method List(--> List:Dis nodal

Coerce the invocant to List.

method Hash

Defined as:

method Hash(--> Hash:Dis nodal

Coerce the invocant to Hash.

method hash

Defined as:

method hash(--> Hash:Dis nodal

Coerce the invocant to Hash.

method Slip

Defined as:

method Slip(--> Slip:Dis nodal

Coerce the invocant to Slip.

method Map

Defined as:

method Map(--> Map:Dis nodal

Coerce the invocant to Map.

method Bag

Defined as:

method Bag(--> Bag:Dis nodal

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

method BagHash

Defined as:

method BagHash(--> BagHash:Dis nodal

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

method Set

Defined as:

method Set(--> Set:Dis nodal

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

method SetHash

Defined as:

method SetHash(--> SetHash:Dis nodal

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

method Mix

Defined as:

method Mix(--> Mix:Dis nodal

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

method MixHash

Defined as:

method MixHash(--> MixHash:Dis nodal

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

method Supply

Defined as:

method Supply(--> Supply:Dis nodal

Coerce the invocant first to a List and then to a Supply.

method min

Defined As:

multi method min(--> Any:D)
multi method min(&by --> Any:D)

Coerces to Iterable and returns the numerically smallest element. If a Callable is provided it is called with each element and its smallest return values is returned.

method max

Defined As:

multi method max(--> Any:D)
multi method min(&by --> Any:D)

Coerces to Iterable and returns the numerically biggest element. If a Callable is provided it is called with each element and its biggest return values is returned.

method minmax

Defined As:

multi method minmax(--> List:D)
multi method minmax(&by --> List:D)

Returns a list containing the smallest and the biggest element. If a Callable is provided each element is filtered and then numerically compared.

TODO

method minpairs

Defined As:

    method minpairs(--> TODO)

TODO

method maxpairs

Defined As:

    method maxpairs(--> TODO)

TODO

method sum

Defined As:

    method sum(--> TODO)

TODO

method keys

Defined As:

    method keys(--> TODO)

TODO

method flatmap

Defined As:

    method flatmap(--> TODO)

TODO

method roll

Defined As:

    method roll(--> TODO)

TODO

method pick

Defined As:

    method pick(--> TODO)

TODO

method head

Defined As:

    method head(--> TODO)

TODO

method tail

Defined As:

    method tail(--> TODO)

TODO

method skip

Defined As:

    method skip(--> TODO)

TODO

method prepend

Defined As:

    method prepend(--> TODO)

TODO

method unshift

Defined As:

    method unshift(--> TODO)

TODO

method first

Defined As:

    method first(--> TODO)

TODO

method unique

Defined As:

    method unique(--> TODO)

TODO

method repeated

Defined As:

    method repeated(--> TODO)

TODO

method squish

Defined As:

    method squish(--> TODO)

TODO

method reduce

Defined As:

    method reduce(--> TODO)

TODO

method permutations

Defined As:

    method permutations(--> TODO)

TODO

method categorize

Defined As:

    method categorize(--> TODO)

TODO

method classify

Defined As:

    method classify(--> TODO)

TODO

method produce

Defined As:

    method produce(--> TODO)

TODO

method rotor

Defined As:

    method rotor(--> TODO)

TODO

method pairs

Defined As:

    method pairs(--> TODO)

TODO

method antipairs

Defined As:

    method antipairs(--> TODO)

TODO

method kv

Defined As:

    method kv(--> TODO)

TODO

method tree

Defined As:

    method tree(--> TODO)

TODO

method nl-out

Defined As:

    method nl-out(--> TODO)

TODO

method invert

Defined As:

    method invert(--> TODO)

TODO

method combinations

Defined As:

    method combinations(--> TODO)

TODO

method print-nl

Defined As:

    method print-nl(--> TODO)

TODO

method nodemap

Defined As:

    method nodemap(--> TODO)

TODO

method iterator

Defined As:

    method iterator(--> TODO)

TODO

method grep

Defined As:

    method grep(--> TODO)

TODO

method match

Defined As:

    method match(--> TODO)

TODO

method append

Defined As:

    method append(--> TODO)

TODO

method join

Defined As:

    method join(--> TODO)

TODO

method values

Defined As:

    method values(--> TODO)

TODO

method collate

Defined As:

    method collate(--> TODO)

TODO

method batch

Defined As:

    method batch(--> TODO)

TODO

method cache

Defined As:

    method cache(--> TODO)

TODO

method lazy-if

Defined As:

    method lazy-if(--> TODO)

TODO

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->List 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::Last CX::Last CX::Last->Exception X::Control X::Control 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->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 CompUnit CompUnit CompUnit->Any CompUnitRepo CompUnitRepo CompUnitRepo->Any CompUnitRepo::Locally CompUnitRepo::Locally CompUnitRepo::Local::File CompUnitRepo::Local::File CompUnitRepo::Local::File->Any CompUnitRepo::Local::File->CompUnitRepo::Locally CompUnitRepo::Local::Installation CompUnitRepo::Local::Installation CompUnitRepo::Local::Installation->Any CompUnitRepo::Local::Installation->CompUnitRepo::Locally 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 Cursor Cursor Cursor->Any Deprecation Deprecation Deprecation->Any Distribution Distribution Distribution->Any Duration Duration Duration->Cool Duration->Real Enumeration Enumeration Failure Failure Failure->Any Rational Rational Rational->Real FatRat FatRat FatRat->Cool FatRat->Rational ForeignCode ForeignCode ForeignCode->Any ForeignCode->Callable Grammar Grammar Grammar->Cursor Map Map Map->Associative Map->Cool Map->Iterable Hash Hash Hash->Map IO IO IO::Handle IO::Handle IO::Handle->Any IO::Handle->IO IO::ArgFiles IO::ArgFiles IO::ArgFiles->IO::Handle IO::Notification IO::Notification IO::Notification->Any IO::Path IO::Path IO::Path->Cool 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->IO 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 Instant Instant Instant->Cool Instant->Real IntStr IntStr IntStr->Int IntStr->Str Iterator Iterator Label Label Label->Any Lock Lock Lock->Any Routine Routine Routine->Block Macro Macro Macro->Routine Match Match Match->Cool Match->Capture 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 Nil Nil Nil->Cool 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 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::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 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 Range Range Range->Positional Range->Cool Range->Iterable Rat Rat Rat->Cool Rat->Rational RatStr RatStr RatStr->Str RatStr->Rat Regex Regex Regex->Method 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 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 Thread Thread Thread->Any ThreadPoolScheduler ThreadPoolScheduler ThreadPoolScheduler->Any ThreadPoolScheduler->Scheduler Variable Variable Variable->Any Version Version Version->Any Whatever Whatever Whatever->Any WhateverCode WhateverCode WhateverCode->Code int int int->Int

Stand-alone image: vector

Routines supplied by class Mu

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

(Mu) routine defined

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

Returns False on the type object, and True otherwise.

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

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

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

(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.

my $i = 17;
say $i.isa("Int");   # OUTPUT: «True␤» 
say $i.isa(Any);     # OUTPUT: «True␤» 

A more idiomatic way to do this is to use the smartmatch operator ~~ instead.

my $s = "String";
say $s ~~ Str;       # OUTPUT: «True␤» 

(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) 

Using the smart match 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 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. 

(Mu) routine gist

multi sub    gist(Mu --> 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 sub    perl(Mu --> Str)
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

method clone(*%twiddles)

Creates a shallow clone of the invocant. 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)␤» 

(Mu) method new

multi method new(*%attrinit)

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)

Lower-level object construction method than new.

Creates a new object of the same type as the invocant, uses the named arguments to initialize attributes, and returns the created object.

You can use this method when writing custom constructors:

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

(Though each time you write a custom constructor, remember that it makes subclassing harder).

(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(--> Bool:D)

Prints value to $*OUT after stringification using .gist method with newline at end. To produce machine readable output use .put.

say 42;                 # OUTPUT: «42␤» 

(Mu) method ACCEPTS

multi method ACCEPTS(Mu:U: $other)

ACCEPTS is the method that smart matching 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()

Returns the attached Pod value. For instance,

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

prints

Initiate a specified spell normally (do not use for class 7 spells)

See the documentation specification 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 };
dd 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()

Returns a Bool value representing the logical non-negation of an expression. 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␤» 

(Mu) method not

method not()

Returns a Bool value representing the logical negation of an expression. Thus it is the opposite of so.

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, the above code reads better like so:

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␤»