class Exception

Anomalous event capable of interrupting normal control-flow

class Exception { ... }

All exceptions that are placed into the $! variable (or into $_ in CATCH blocks) inherit from Exception. When you call die or fail with a non-Exception argument, it is wrapped into an X::AdHoc object, which also inherits from Exception.

User-defined exception classes should inherit from Exception too, and define at least a method message.

class X::YourApp::SomeError is Exception {
    method message() {
        "A YourApp-Specific error occurred: out of coffee!";
    }
}

Methods

method message

method message(Exception:D:) returns Str:D

This is a stub that must be overwritten by subclasses, and should return the exception message.

Special care should be taken that this method does not produce an exception itself.

method backtrace

method backtrace(Exception:D:) returns Backtrace:D

Returns the backtrace associated with the exception. Only makes sense on exceptions that have been thrown at least once.

method throw

method throw(Exception:D:)

Throws the exception.

method rethrow

method rethrow(Exception:D:)

Rethrows an exception that has already been thrown at least once. This is different from throw in that it preserves the original backtrace.

method fail

sub    fail(*@text)
sub    fail(Exception $e)
method fail(Exception:D $e:)

Exits the calling Routine and returns a Failure object wrapping the exception $e - or, for the *@text form, an X::AdHoc exception constructed from the concatenation of @text.

sub copy-directory-tree ($dir) {
    fail "$dir is not a directory" if !$dir.IO.d;
    ...
}

method gist

multi method gist(Exception:D:)

Returns whatever the exception printer should produce for this exception. The default implementation returns message and backtrace separated by a newline.

Type graph

Below you should see a clickable image showing the type relations for Exception that links to the documentation pages for the related types. If not, try the PNG version instead.

perl6-type-graph X::Control X::Control Exception Exception X::Control->Exception X::AdHoc X::AdHoc X::AdHoc->Exception X::Comp X::Comp X::Comp->Exception X::Anon::Augment X::Anon::Augment X::Anon::Augment->X::Comp X::Anon::Augment->Exception X::Anon::Multi X::Anon::Multi X::Anon::Multi->X::Comp X::Anon::Multi->Exception X::Assignment::RO X::Assignment::RO X::Assignment::RO->Exception X::Attribute::NoPackage X::Attribute::NoPackage X::Attribute::NoPackage->X::Comp X::Attribute::NoPackage->Exception X::Attribute::Package X::Attribute::Package X::Attribute::Package->X::Comp X::Attribute::Package->Exception X::Undeclared X::Undeclared X::Undeclared->X::Comp X::Undeclared->Exception X::Attribute::Undeclared X::Attribute::Undeclared X::Attribute::Undeclared->X::Undeclared X::Augment::NoSuchType X::Augment::NoSuchType X::Augment::NoSuchType->X::Comp X::Augment::NoSuchType->Exception X::Syntax X::Syntax X::Syntax->X::Comp X::Syntax->Exception X::Backslash::NonVariableDollar X::Backslash::NonVariableDollar X::Backslash::NonVariableDollar->X::Syntax X::Backslash::NonVariableDollar->Exception X::Backslash::UnrecognizedSequence X::Backslash::UnrecognizedSequence X::Backslash::UnrecognizedSequence->X::Syntax X::Backslash::UnrecognizedSequence->Exception X::Bind X::Bind X::Bind->Exception X::Bind::NativeType X::Bind::NativeType X::Bind::NativeType->X::Comp X::Bind::NativeType->Exception X::Bind::Slice X::Bind::Slice X::Bind::Slice->Exception X::Bind::ZenSlice X::Bind::ZenSlice X::Bind::ZenSlice->X::Bind::Slice X::Buf::AsStr X::Buf::AsStr X::Buf::AsStr->Exception X::Buf::Pack X::Buf::Pack X::Buf::Pack->Exception X::Buf::Pack::NonASCII X::Buf::Pack::NonASCII X::Buf::Pack::NonASCII->Exception X::Comp::AdHoc X::Comp::AdHoc X::Comp::AdHoc->X::AdHoc X::Comp::AdHoc->X::Comp X::Comp::AdHoc->Exception X::Comp::Group X::Comp::Group X::Comp::Group->Exception X::NYI X::NYI X::NYI->Exception X::Comp::NYI X::Comp::NYI X::Comp::NYI->X::Comp X::Comp::NYI->X::NYI X::Comp::NYI->Exception X::Trait::NotOnNative X::Trait::NotOnNative Any Any X::Trait::NotOnNative->Any X::Comp::Trait::NotOnNative X::Comp::Trait::NotOnNative X::Comp::Trait::NotOnNative->X::Comp X::Comp::Trait::NotOnNative->X::Trait::NotOnNative X::Comp::Trait::NotOnNative->Exception X::Trait::Scope X::Trait::Scope X::Trait::Scope->Any X::Comp::Trait::Scope X::Comp::Trait::Scope X::Comp::Trait::Scope->X::Comp X::Comp::Trait::Scope->X::Trait::Scope X::Comp::Trait::Scope->Exception X::Trait::Unknown X::Trait::Unknown X::Trait::Unknown->Any X::Comp::Trait::Unknown X::Comp::Trait::Unknown X::Comp::Trait::Unknown->X::Comp X::Comp::Trait::Unknown->X::Trait::Unknown X::Comp::Trait::Unknown->Exception X::Composition::NotComposable X::Composition::NotComposable X::Composition::NotComposable->Exception X::Constructor::Positional X::Constructor::Positional X::Constructor::Positional->Exception X::ControlFlow X::ControlFlow X::ControlFlow->Exception X::ControlFlow::Return X::ControlFlow::Return X::ControlFlow::Return->X::ControlFlow X::Temporal X::Temporal X::Temporal->Exception X::DateTime::TimezoneClash X::DateTime::TimezoneClash X::DateTime::TimezoneClash->X::Temporal X::Declaration::Scope X::Declaration::Scope X::Declaration::Scope->X::Comp X::Declaration::Scope->Exception X::Declaration::Scope::Multi X::Declaration::Scope::Multi X::Declaration::Scope::Multi->X::Declaration::Scope X::Does::TypeObject X::Does::TypeObject X::Does::TypeObject->Exception X::EXPORTHOW::Conflict X::EXPORTHOW::Conflict X::EXPORTHOW::Conflict->X::Comp X::EXPORTHOW::Conflict->Exception X::EXPORTHOW::InvalidDirective X::EXPORTHOW::InvalidDirective X::EXPORTHOW::InvalidDirective->X::Comp X::EXPORTHOW::InvalidDirective->Exception X::EXPORTHOW::NothingToSupersede X::EXPORTHOW::NothingToSupersede X::EXPORTHOW::NothingToSupersede->X::Comp X::EXPORTHOW::NothingToSupersede->Exception X::Eval::NoSuchLang X::Eval::NoSuchLang X::Eval::NoSuchLang->Exception X::Export::NameClash X::Export::NameClash X::Export::NameClash->Exception X::Hash::Store::OddNumber X::Hash::Store::OddNumber X::Hash::Store::OddNumber->Exception X::HyperOp::NonDWIM X::HyperOp::NonDWIM X::HyperOp::NonDWIM->Exception X::OS X::OS X::OS->Exception X::IO X::IO X::IO->X::OS X::IO->Exception X::IO::Chdir X::IO::Chdir X::IO::Chdir->X::IO X::IO::Chdir->Exception X::IO::Chmod X::IO::Chmod X::IO::Chmod->X::IO X::IO::Chmod->Exception X::IO::Copy X::IO::Copy X::IO::Copy->X::IO X::IO::Copy->Exception X::IO::Cwd X::IO::Cwd X::IO::Cwd->X::IO X::IO::Cwd->Exception X::IO::Dir X::IO::Dir X::IO::Dir->X::IO X::IO::Dir->Exception X::IO::Mkdir X::IO::Mkdir X::IO::Mkdir->X::IO X::IO::Mkdir->Exception X::IO::Rename X::IO::Rename X::IO::Rename->X::IO X::IO::Rename->Exception X::IO::Rmdir X::IO::Rmdir X::IO::Rmdir->X::IO X::IO::Rmdir->Exception X::IO::Rmdir->Exception X::IO::Unlink X::IO::Unlink X::IO::Unlink->X::IO X::IO::Unlink->Exception X::IO::Unlink->Exception X::Import::MissingSymbols X::Import::MissingSymbols X::Import::MissingSymbols->Exception X::Import::OnlystarProto X::Import::OnlystarProto X::Import::OnlystarProto->X::Comp X::Import::OnlystarProto->Exception X::Import::Redeclaration X::Import::Redeclaration X::Import::Redeclaration->X::Comp X::Import::Redeclaration->Exception X::Inheritance::NotComposed X::Inheritance::NotComposed X::Inheritance::NotComposed->Exception X::Inheritance::Unsupported X::Inheritance::Unsupported X::Inheritance::Unsupported->Exception X::Localizer::NoContainer X::Localizer::NoContainer X::Localizer::NoContainer->Exception X::Method::InvalidQualifier X::Method::InvalidQualifier X::Method::InvalidQualifier->Exception X::Method::NotFound X::Method::NotFound X::Method::NotFound->Exception X::Method::Private::Permission X::Method::Private::Permission X::Method::Private::Permission->X::Comp X::Method::Private::Permission->Exception X::Method::Private::Unqualified X::Method::Private::Unqualified X::Method::Private::Unqualified->X::Comp X::Method::Private::Unqualified->Exception X::Mixin::NotComposable X::Mixin::NotComposable X::Mixin::NotComposable->Exception X::NoDispatcher X::NoDispatcher X::NoDispatcher->Exception X::Numeric::Real X::Numeric::Real X::Numeric::Real->Exception X::Obsolete X::Obsolete X::Obsolete->X::Comp X::Obsolete->X::Comp X::Obsolete->Exception X::Obsolete->Exception X::OutOfRange X::OutOfRange X::OutOfRange->Exception X::Package::Stubbed X::Package::Stubbed X::Package::Stubbed->X::Comp X::Package::Stubbed->Exception X::Parameter::Default X::Parameter::Default X::Parameter::Default->X::Comp X::Parameter::Default->Exception X::Parameter::InvalidType X::Parameter::InvalidType X::Parameter::InvalidType->X::Comp X::Parameter::InvalidType->Exception X::Parameter::MultipleTypeConstraints X::Parameter::MultipleTypeConstraints X::Parameter::MultipleTypeConstraints->X::Comp X::Parameter::MultipleTypeConstraints->Exception X::Parameter::Placeholder X::Parameter::Placeholder X::Parameter::Placeholder->X::Comp X::Parameter::Placeholder->Exception X::Parameter::Twigil X::Parameter::Twigil X::Parameter::Twigil->X::Comp X::Parameter::Twigil->Exception X::Parameter::WrongOrder X::Parameter::WrongOrder X::Parameter::WrongOrder->X::Comp X::Parameter::WrongOrder->Exception X::Phaser::Multiple X::Phaser::Multiple X::Phaser::Multiple->X::Comp X::Phaser::Multiple->Exception X::Phaser::PrePost X::Phaser::PrePost X::Phaser::PrePost->Exception X::Placeholder::Block X::Placeholder::Block X::Placeholder::Block->X::Comp X::Placeholder::Block->Exception X::Placeholder::Mainline X::Placeholder::Mainline X::Placeholder::Mainline->X::Placeholder::Block X::Placeholder::NonPlaceholder X::Placeholder::NonPlaceholder X::Placeholder::NonPlaceholder->X::Comp X::Placeholder::NonPlaceholder->Exception X::Pod X::Pod X::PoisonedAlias X::PoisonedAlias X::PoisonedAlias->X::Comp X::PoisonedAlias->Exception X::Proc::Async X::Proc::Async X::Proc::Async->Exception X::Proc::Async::AlreadyStarted X::Proc::Async::AlreadyStarted X::Proc::Async::AlreadyStarted->X::Proc::Async X::Proc::Async::AlreadyStarted->Exception X::Proc::Async::CharsOrBytes X::Proc::Async::CharsOrBytes X::Proc::Async::CharsOrBytes->X::Proc::Async X::Proc::Async::CharsOrBytes->Exception X::Proc::Async::MustBeStarted X::Proc::Async::MustBeStarted X::Proc::Async::MustBeStarted->X::Proc::Async X::Proc::Async::MustBeStarted->Exception X::Proc::Async::OpenForWriting X::Proc::Async::OpenForWriting X::Proc::Async::OpenForWriting->X::Proc::Async X::Proc::Async::OpenForWriting->Exception X::Proc::Async::TapBeforeSpawn X::Proc::Async::TapBeforeSpawn X::Proc::Async::TapBeforeSpawn->X::Proc::Async X::Proc::Async::TapBeforeSpawn->Exception X::Promise::CauseOnlyValidOnBroken X::Promise::CauseOnlyValidOnBroken X::Promise::CauseOnlyValidOnBroken->Exception X::PseudoPackage::InDeclaration X::PseudoPackage::InDeclaration X::PseudoPackage::InDeclaration->X::Comp X::PseudoPackage::InDeclaration->Exception X::Redeclaration X::Redeclaration X::Redeclaration->X::Comp X::Redeclaration->Exception X::Redeclaration::Outer X::Redeclaration::Outer X::Redeclaration::Outer->X::Comp X::Redeclaration::Outer->Exception X::Role::Initialization X::Role::Initialization X::Role::Initialization->Exception X::Routine::Unwrap X::Routine::Unwrap X::Routine::Unwrap->Exception X::SemicolonForm::Invalid X::SemicolonForm::Invalid X::SemicolonForm::Invalid->X::Syntax X::SemicolonForm::Invalid->Exception X::SemicolonForm::TooLate X::SemicolonForm::TooLate X::SemicolonForm::TooLate->X::Syntax X::SemicolonForm::TooLate->Exception X::Sequence::Deduction X::Sequence::Deduction X::Sequence::Deduction->Exception X::Set::Coerce X::Set::Coerce X::Set::Coerce->Exception X::Signature::NameClash X::Signature::NameClash X::Signature::NameClash->X::Comp X::Signature::NameClash->Exception X::Signature::Placeholder X::Signature::Placeholder X::Signature::Placeholder->X::Comp X::Signature::Placeholder->Exception X::Str::Match::x X::Str::Match::x X::Str::Match::x->Exception X::Str::Numeric X::Str::Numeric X::Str::Numeric->Exception X::Str::Trans::IllegalKey X::Str::Trans::IllegalKey X::Str::Trans::IllegalKey->Exception X::Str::Trans::InvalidArg X::Str::Trans::InvalidArg X::Str::Trans::InvalidArg->Exception X::StubCode X::StubCode X::StubCode->Exception X::Syntax::AddCategorial::MissingSeparator X::Syntax::AddCategorial::MissingSeparator X::Syntax::AddCategorial::MissingSeparator->X::Syntax X::Syntax::AddCategorial::MissingSeparator->Any X::Syntax::Argument::MOPMacro X::Syntax::Argument::MOPMacro X::Syntax::Argument::MOPMacro->X::Syntax X::Syntax::Argument::MOPMacro->Exception X::Syntax::Augment::Illegal X::Syntax::Augment::Illegal X::Syntax::Augment::Illegal->X::Syntax X::Syntax::Augment::Illegal->Exception X::Syntax::Augment::Role X::Syntax::Augment::Role X::Syntax::Augment::Role->X::Syntax X::Syntax::Augment::Role->Exception X::Syntax::Augment::WithoutMonkeyTyping X::Syntax::Augment::WithoutMonkeyTyping X::Syntax::Augment::WithoutMonkeyTyping->X::Syntax X::Syntax::Augment::WithoutMonkeyTyping->Exception X::Syntax::BlockGobbled X::Syntax::BlockGobbled X::Syntax::BlockGobbled->X::Syntax X::Syntax::BlockGobbled->Exception X::Syntax::Can'tMeta X::Syntax::Can'tMeta X::Syntax::Can'tMeta->X::Syntax X::Syntax::Can'tMeta->Exception X::Syntax::Comment::Embedded X::Syntax::Comment::Embedded X::Syntax::Comment::Embedded->X::Syntax X::Syntax::Comment::Embedded->Exception X::Syntax::Confused X::Syntax::Confused X::Syntax::Confused->X::Syntax X::Syntax::Confused->Exception X::Syntax::Extension::Category X::Syntax::Extension::Category X::Syntax::Extension::Category->X::Syntax X::Syntax::Extension::Category->Exception X::Syntax::Extension::Null X::Syntax::Extension::Null X::Syntax::Extension::Null->X::Syntax X::Syntax::Extension::Null->Exception X::Syntax::InfixInTermPosition X::Syntax::InfixInTermPosition X::Syntax::InfixInTermPosition->X::Syntax X::Syntax::InfixInTermPosition->Exception X::Syntax::KeywordAsFunction X::Syntax::KeywordAsFunction X::Syntax::KeywordAsFunction->X::Syntax X::Syntax::KeywordAsFunction->Exception X::Syntax::Malformed X::Syntax::Malformed X::Syntax::Malformed->X::Syntax X::Syntax::Malformed->Exception X::Syntax::Malformed::Elsif X::Syntax::Malformed::Elsif X::Syntax::Malformed::Elsif->X::Syntax X::Syntax::Malformed::Elsif->Exception X::Syntax::Missing X::Syntax::Missing X::Syntax::Missing->X::Syntax X::Syntax::Missing->Any X::Syntax::Name::Null X::Syntax::Name::Null X::Syntax::Name::Null->X::Syntax X::Syntax::Name::Null->Exception X::Syntax::NegatedPair X::Syntax::NegatedPair X::Syntax::NegatedPair->X::Syntax X::Syntax::NegatedPair->Any X::Syntax::NoSelf X::Syntax::NoSelf X::Syntax::NoSelf->X::Syntax X::Syntax::NoSelf->Exception X::Syntax::NonAssociative X::Syntax::NonAssociative X::Syntax::NonAssociative->X::Syntax X::Syntax::NonAssociative->Any X::Syntax::Number::RadixOutOfRange X::Syntax::Number::RadixOutOfRange X::Syntax::Number::RadixOutOfRange->X::Syntax X::Syntax::Number::RadixOutOfRange->Exception X::Syntax::P5 X::Syntax::P5 X::Syntax::P5->X::Syntax X::Syntax::P5->Exception X::Syntax::Perl5Var X::Syntax::Perl5Var X::Syntax::Perl5Var->X::Syntax X::Syntax::Perl5Var->Exception X::Syntax::Pod::BeginWithoutEnd X::Syntax::Pod::BeginWithoutEnd X::Syntax::Pod::BeginWithoutEnd->X::Syntax X::Syntax::Pod::BeginWithoutEnd->X::Pod X::Syntax::Pod::BeginWithoutEnd->Exception X::Syntax::Pod::BeginWithoutIdentifier X::Syntax::Pod::BeginWithoutIdentifier X::Syntax::Pod::BeginWithoutIdentifier->X::Syntax X::Syntax::Pod::BeginWithoutIdentifier->X::Pod X::Syntax::Pod::BeginWithoutIdentifier->Exception X::Syntax::Regex::Adverb X::Syntax::Regex::Adverb X::Syntax::Regex::Adverb->X::Syntax X::Syntax::Regex::Adverb->Exception X::Syntax::Regex::MalformedRange X::Syntax::Regex::MalformedRange X::Syntax::Regex::MalformedRange->X::Syntax X::Syntax::Regex::MalformedRange->Exception X::Syntax::Regex::NullRegex X::Syntax::Regex::NullRegex X::Syntax::Regex::NullRegex->X::Syntax X::Syntax::Regex::NullRegex->Any X::Syntax::Regex::SolitaryQuantifier X::Syntax::Regex::SolitaryQuantifier X::Syntax::Regex::SolitaryQuantifier->X::Syntax X::Syntax::Regex::SolitaryQuantifier->Exception X::Syntax::Regex::SpacesInBareRange X::Syntax::Regex::SpacesInBareRange X::Syntax::Regex::SpacesInBareRange->X::Syntax X::Syntax::Regex::SpacesInBareRange->Exception X::Syntax::Regex::UnrecognizedMetachar X::Syntax::Regex::UnrecognizedMetachar X::Syntax::Regex::UnrecognizedMetachar->X::Syntax X::Syntax::Regex::UnrecognizedMetachar->Any X::Syntax::Regex::Unspace X::Syntax::Regex::Unspace X::Syntax::Regex::Unspace->X::Syntax X::Syntax::Regex::Unspace->Exception X::Syntax::Regex::Unterminated X::Syntax::Regex::Unterminated X::Syntax::Regex::Unterminated->X::Syntax X::Syntax::Regex::Unterminated->Any X::Syntax::Reserved X::Syntax::Reserved X::Syntax::Reserved->X::Syntax X::Syntax::Reserved->Exception X::Syntax::Self::WithoutObject X::Syntax::Self::WithoutObject X::Syntax::Self::WithoutObject->X::Syntax X::Syntax::Self::WithoutObject->Exception X::Syntax::SigilWithoutName X::Syntax::SigilWithoutName X::Syntax::SigilWithoutName->X::Syntax X::Syntax::SigilWithoutName->Any X::Syntax::Signature::InvocantMarker X::Syntax::Signature::InvocantMarker X::Syntax::Signature::InvocantMarker->X::Syntax X::Syntax::Signature::InvocantMarker->Exception X::Syntax::Term::MissingInitializer X::Syntax::Term::MissingInitializer X::Syntax::Term::MissingInitializer->X::Syntax X::Syntax::Term::MissingInitializer->Exception X::Syntax::UnlessElse X::Syntax::UnlessElse X::Syntax::UnlessElse->X::Syntax X::Syntax::UnlessElse->Exception X::Syntax::Variable::IndirectDeclaration X::Syntax::Variable::IndirectDeclaration X::Syntax::Variable::IndirectDeclaration->X::Syntax X::Syntax::Variable::IndirectDeclaration->Any X::Syntax::Variable::Match X::Syntax::Variable::Match X::Syntax::Variable::Match->X::Syntax X::Syntax::Variable::Match->Exception X::Syntax::Variable::Numeric X::Syntax::Variable::Numeric X::Syntax::Variable::Numeric->X::Syntax X::Syntax::Variable::Numeric->Exception X::Syntax::Variable::Twigil X::Syntax::Variable::Twigil X::Syntax::Variable::Twigil->X::Syntax X::Syntax::Variable::Twigil->Exception X::Syntax::VirtualCall X::Syntax::VirtualCall X::Syntax::VirtualCall->X::Syntax X::Syntax::VirtualCall->Any X::Temporal::InvalidFormat X::Temporal::InvalidFormat X::Temporal::InvalidFormat->X::Temporal X::Temporal::Truncation X::Temporal::Truncation X::Temporal::Truncation->X::Temporal X::TypeCheck X::TypeCheck X::TypeCheck->Exception X::TypeCheck::Assignment X::TypeCheck::Assignment X::TypeCheck::Assignment->X::TypeCheck X::TypeCheck::Binding X::TypeCheck::Binding X::TypeCheck::Binding->X::TypeCheck X::TypeCheck::Return X::TypeCheck::Return X::TypeCheck::Return->X::TypeCheck X::TypeCheck::Splice X::TypeCheck::Splice X::TypeCheck::Splice->X::TypeCheck X::Undeclared::Symbols X::Undeclared::Symbols X::Undeclared::Symbols->X::Comp X::Undeclared::Symbols->Exception X::Value::Dynamic X::Value::Dynamic X::Value::Dynamic->X::Comp X::Value::Dynamic->Exception Exception->Any Mu Mu Any->Mu

Routines supplied by class Any

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

method ACCEPTS

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

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

Many built-in types override this for more specific comparisons

method any

method any() returns Junction:D

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

say so 2 == <1 2 3>.any;        # True
say so 5 == <1 2 3>.any;        # False

method all

method all() returns Junction:D

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

say so 1 < <2 3 4>.all;         # True
say so 3 < <2 3 4>.all;         # False

method one

method one() returns Junction:D

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

say so 1 == (1, 2, 3).one;      # True
say so 1 == (1, 2, 1).one;      # False

method none

method none() returns Junction:D

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

say so 1 == (1, 2, 3).none;     # False
say so 4 == (1, 2, 3).none;     # True

method list

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

say so 42.list.^name;           # List
say so 42.list.elems;           # 1

method flat

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

say ((1, 2), (3)).elems;        # 2
say ((1, 2), (3)).flat.elems;   # 3

method eager

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

say (1..10).eager;              # 1 2 3 4 5 6 7 8 9 10

method elems

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

say 42.elems;                   # 1
say <a b c>.elems;              # 3

method end

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

say 6.end;                      # 0
say <a b c>.end;                # 2

method pairup

method pairup() returns List

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 (a => 1, 'b', 'c').pairup.perl;     # ("a" => 1, "b" => "c").list

sub exit

sub exit(Int() $status = 0)

Exits the current process with return code $status.

Routines supplied by class Mu

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

routine defined

multi sub    defined(Mu) returns Bool:D
multi method defined()   returns Bool:D

Returns False on the type object, and True otherwise.

say Int.defined;                # False
say 42.defined;                 # True

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

sub fails() { fail 'oh noe' };
say fails().defined;            # False

routine Bool

multi sub    Bool(Mu) returns Bool:D
multi method Bool()   returns 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;                    # False
say Mu.new.Bool;                # True
say [1, 2, 3].Bool;             # True
say [].Bool;                    # False
say { 'hash' => 'full'}.Bool;   # True
say {}.Bool;                    # False

method Str

multi method Str()   returns 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

routine gist

multi sub    gist(Mu) returns Str
multi method gist()   returns Str

Returns a string representation of the invocant, optimized for fast recognition by humans.

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.

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

say Mu.gist;        # (Mu)
say Mu.new.gist;    # Mu.new()

routine perl

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

method clone

method clone(*%twiddles)

Creates a shallow clone of the invocant. If named arguments are passed to it, their values are used in every place where an attribute name matches the name of a named argument.

class Point2D {
    has ($.x, $.y);
    multi method gist(Point2D:D:) {
        "Point($.x, $.y)";
    }
}

my $p = Point2D.new(x => 2, y => 3);

say $p;                     # Point(2, 3)
say $p.clone(y => -5);      # Point(2, -5)

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.

method bless

method bless(*%attrinit) returns 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(-1, 1);

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

method CREATE

method CREATE() returns Mu:D

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

say Mu.CREATE.defined;  # True

method print

multi method print() returns Bool:D

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

"abc\n".print;          # abc

method say

multi method say() returns Bool:D

Prints value to $*OUT after stringification using .gist method with newline at end.

say 42;                 # 42

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;           # True
say 42 ~~ Int;          # True
say 42 ~~ Str;          # 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.

method WHICH

multi method WHICH() returns 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;       # True

method WHERE

method WHERE() returns Int

Returns an Int representing the memory address of the object.

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.

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.

method take

method take()

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;    #-> 32 22 1 17 32 9  (for example)

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(@args) eq '-v' | '-V';
if $verbose-selected.so {
    say "Verbose option detected in arguments";
} #-> Verbose option detected in arguments

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(@args) eq '-v' | '-V';
if $verbose-selected.not {
    say "Verbose option not present in arguments";
} #-> 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(@args) eq '-v' | '-V';
if not $verbose-selected {
    say "Verbose option not present in arguments";
} #-> Verbose option not present in arguments