class Date

Calendar date

class Date { }

A Date is an immutable object identifying a day in the Gregorian calendar.

Date objects support addition and subtraction of integers, where an integer is interpreted as the number of days. You can compare Date objects with the numeric comparison operators ==, <, <=, >, >=, != . Their stringification in YYYY-MM-DD format means that comparing them with the string operators eq, lt, le etc. also gives the right result. creates an object the current day according to the system clock.

my $d =; # Christmas Eve! 
say $d;                         # OUTPUT: «2015-12-24␤» 
say $d.year;                    # OUTPUT: «2015␤» 
say $d.month;                   # OUTPUT: «12␤» 
say $;                     # OUTPUT: «24␤» 
say $;             # OUTPUT: «1␤», that is Monday 
say $d.later(days => 20);       # OUTPUT: «2016-01-13␤» 
my $n ='2015-12-31'); # New Year's Eve 
say $n - $d;                    # OUTPUT: «7␤», 7 days between New Years/Christmas Eve 
say $n + 1;                     # OUTPUT: «2016-01-01␤» 


method new

Defined as:

multi method new($year$month$day:&formatter --> Date:D)
multi method new(:$year!:$month = 1:$day = 1  --> Date:D)
multi method new(Str $date                        --> Date:D)
multi method new(Instant:D $dt                    --> Date:D)
multi method new(DateTime:D $dt                   --> Date:D)

Creates a new Date object, either from a triple of (year, month, day) that can be coerced to integers, or from a string of the form YYYY-MM-DD (ISO 8601), or from an Instant or DateTime object. Optionally accepts a formatter as a named parameter.

my $date =;
$date = => 2042month => 1day => 1);
$date ="2042-01-01");
$date = 1482155532);
$date =;

method new-from-daycount

Defined as:

method new-from-daycount($daycount,:&formatter --> Date:D)

Creates a new Date object given $daycount which is the number of days from epoch Nov. 17, 1858, i.e. the Modified Julian Day. Optionally accepts a formatter as a named parameter.

say;          # OUTPUT: «1995-09-27␤» 

method clone

Defined as:

method clone(:$year:$month:$day)

Creates a new Date object based on the invocant, but with the given arguments overriding the values from the invocant.

say'2015-11-24').clone(month => 12);    # OUTPUT: «2015-12-24␤» 

method today

Defined as:

method today(:&formatter --> Date:D)

Returns a Date object for the current day. Optionally accepts a formatter named parameter.


method later

Defined as:

method later(Date:D: *%unit)

Returns a Date object based on the current one, but with a date delta applied. The date delta can be passed as a named argument where the argument name is the unit.

Allowed units are day, days, week, weeks, month, months, year, years. Please note that the plural forms can only be used with the later method.

Please note that the special ":2nd" named parameter syntax can be a compact and self-documenting way of specifying the delta

say'2015-12-24').later(:2years);  # OUTPUT: «2017-12-24␤» 

Since addition of several different time units is not commutative, only one unit may be passed.

my $d ='2015-02-27');
say $d.later(month => 1).later(:2days);  # OUTPUT: «2015-03-29␤» 
say $d.later(days => 2).later(:1month);  # OUTPUT: «2015-04-01␤» 
say $d.later(days => 2).later(:month);   # same, as +True === 1 

Negative offsets are allowed, though method earlier is more idiomatic for that.

method earlier

Defined as:

method earlier(Date:D: *%unit)

Returns a Date object based on the current one, but with a date delta towards the past applied. See method later for usage.

my $d ='2015-02-27');
say $d.earlier(month => 5).earlier(:2days);  # OUTPUT: «2014-09-25␤» 

method truncated-to

Defined as:

method truncated-to(Date:D: Cool $unit)

Returns a Date truncated to the first day of its year, month or week. For example

my $c ='2012-12-24');
say $c.truncated-to('year');     # OUTPUT: «2012-01-01␤» 
say $c.truncated-to('month');    # OUTPUT: «2012-12-01␤» 
say $c.truncated-to('week');     # OUTPUT: «2012-12-24␤», because it's Monday already 

method succ

Defined as:

method succ(Date:D: --> Date:D)

Returns a Date of the following day. "succ" is short for "successor".

say"2016-02-28").succ;   # OUTPUT: «2016-02-29␤» 

method pred

Defined as:

method pred(Date:D: --> Date:D)

Returns a Date of the previous day. "pred" is short for "predecessor".

say"2016-01-01").pred;   # OUTPUT: «2015-12-31␤» 

method Str

Defined as:

multi method Str(Date:D: --> Str:D)

Returns a string representation of the invocant, as specified by the the formatter. If no formatter was specified, an (ISO 8601) date will be returned.

say'2015-12-24').Str;                     # OUTPUT: «2015-12-24␤» 
my $fmt = { sprintf "%02d/%02d/%04d" };
say'2015-12-24'formatter => $fmt).Str;  # OUTPUT: «12/24/2015␤» 

method gist

Defined as:

multi method gist(Date:D: --> Str:D)

Returns the date in YYYY-MM-DD format (ISO 8601)

say'2015-12-24').gist;                    # OUTPUT: «2015-12-24␤» 

method Date

Defined as:

method Date(--> Date)

Returns the invocant.

say'2015-12-24').Date;  # OUTPUT: «2015-12-24␤» 
say Date.Date;                    # OUTPUT: «(Date)␤» 

method DateTime

Defined as:

multi method DateTime(Date:U --> DateTime:U)
multi method DateTime(Date:D --> DateTime:D)

Converts the invocant to DateTime

say'2015-12-24').DateTime# OUTPUT: «2015-12-24T00:00:00Z␤» 
say Date.DateTime;                   # OUTPUT: «(DateTime)␤» 


sub sleep

sub sleep($seconds = Inf --> Nil)

Attempt to sleep for the given number of $seconds. Returns Nil on completion. Accepts Int, Num, Rat, or Duration types as an argument since all of these also do Real.

sleep 5;                # Int 
sleep 5.2;              # Num 
sleep (5/2);            # Rat 
sleep (now - now + 5);  # Duration 

It is thus possible to sleep for a non-integer amount of time. For instance, the following code shows that sleep (5/2) sleeps for 2.5 seconds and sleep 5.2 sleeps for 5.2 seconds:

my $before = now;
sleep (5/2);
my $after = now;
say $after-$before;  # OUTPUT: «2.502411561␤» 
$before = now;
sleep 5.2;
$after = now;
say $after-$before;  # OUTPUT: «5.20156987␤» 

sub sleep-timer

sub sleep-timer(Real $seconds = Inf --> Duration)

This function is just like sleep, but returns the amount of time remaining to sleep as a Duration (which will be 0 if the call was not interrupted).

say sleep-timer 3.14;  # OUTPUT: «0␤» 

sub sleep-until

sub sleep-until(Instant $until --> Bool)

Works just like sleep but checks the current time and goes back to sleep if accidentally woken up early, to guarantee waiting until the specified time. Returns True if the function actually waited, or if the specified time happens to be the present moment. Returns False if you asked to sleep until a time in the past.

To sleep until 10 seconds into the future, one could write something like this:

say sleep-until now+10;   # OUTPUT: «True␤» 

Trying to sleep until a time in the past doesn't work:

my $instant = now - 5;
say sleep-until $instant# OUTPUT: «False␤» 

However if we put the instant sufficiently far in the future, the sleep should run:

my $instant = now + 30;
# assuming the two commands are run within 30 seconds of one another... 
say sleep-until $instant# OUTPUT: «True␤» 

To specify an exact instant in the future, first create a DateTime at the appropriate point in time, and cast to an Instant.

my $instant =
    year => 2020,
    month => 9,
    day => 1,
    hour => 22,
    minute => 5);
say sleep-until $instant.Instant# True (eventually...) 

This could be be used as a primitive kind of alarm clock. For instance, say you need to get up at 7am on the 4th of September 2015, but for some reason your usual alarm clock is broken and you only have your laptop. You can specify the time to get up (being careful about timezones, since uses UTC by default) as an Instant and pass this to sleep-until, after which you can play an mp3 file to wake you up instead of your normal alarm clock. This scenario looks roughly like this:

# uses UTC by default, so get timezone from current time 
my $timezone =;
my $instant =
    year => 2015,
    month => 9,
    day => 4,
    hour => 7,
    minute => 0,
    timezone => $timezone
sleep-until $instant;
qqx{mplayer wake-me-up.mp3};

sub infix:<->

multi sub infix:<-> (Date:DInt:D --> Date:D)
multi sub infix:<-> (Date:DDate:D --> Int:D)

Takes a date to subtract from and either an Int, representing the number of days to subtract, or another Date object. Returns a new Date object or the number of days between the two dates, respectively.

say'2016-12-25'-'2016-12-24'); # OUTPUT: «1␤» 
say'2015-12-25'-'2016-11-21'); # OUTPUT: «-332␤» 
say'2016-11-21'- 332;                    # OUTPUT: «2015-12-25␤» 

sub infix:<+>

multi sub infix:<+> (Date:DInt:D --> Date:D)
multi sub infix:<+> (Int:DDate:D --> Date:D)

Takes an Int and adds that many days to the given Date object.

say'2015-12-25'+ 332# OUTPUT: «2016-11-21␤» 
say 1 +'2015-12-25');   # OUTPUT: «2015-12-26␤» 

Type graph

Type relations for Date
perl6-type-graph Date Date Any Any Date->Any Dateish Dateish Date->Dateish Mu Mu Any->Mu

Stand-alone image: vector

Routines supplied by role Dateish

Date does role Dateish, which provides the following methods:

(Dateish) method year

Defined as:

method year(Date:D: --> Int:D)

Returns the year of the date.

say'2015-12-31').year;                                  # OUTPUT: «2015␤» 
say =>'2015-12-24'), hour => 1).year# OUTPUT: «2015␤» 

(Dateish) method month

Defined as:

method month(Date:D: --> Int:D)

Returns the month of the date (1..12).

say'2015-12-31').month;                                  # OUTPUT: «12␤» 
say =>'2015-12-24'), hour => 1).month# OUTPUT: «12␤» 

(Dateish) method day

Defined as:

method day(Date:D: --> Int:D)

Returns the day of the month of the date (1..31).

say'2015-12-31').day;                                  # OUTPUT: «31␤» 
say =>'2015-12-24'), hour => 1).day# OUTPUT: «24␤» 

(Dateish) method formatter

Defined as:

method formatter(Dateish:D:)

Returns the formatting function which is used for conversion to Str. If none was provided at object construction, a default formatter is used. In that case the method will return a Callable type object.

The formatting function is called by DateTime method Str with the invocant as its only argument.

my $dt ='2015-12-31');  # (no formatter specified) 
say $dt.formatter.WHAT;           # OUTPUT: «(Callable)␤» 
my $us-format = sub ($self{ sprintf "%02d/%02d/%04d" given $self};
$dt ='2015-12-31'formatter => $us-format);
say $dt.formatter.WHAT;           # OUTPUT: «(Sub)␤» 
say $dt;                          # OUTPUT: «12/31/2015␤» 

(Dateish) method is-leap-year

Defined as:

method is-leap-year(--> Bool:D)

Returns True if the year of the Dateish object is a leap year.

say<2016>).is-leap-year# OUTPUT: «True␤» 
say"1900-01-01").is-leap-year;    # OUTPUT: «False␤» 

(Dateish) method day-of-month

Defined as:

method day-of-month(Date:D: --> Int:D)

Returns the day of the month of the date (1..31). Synonymous to the day method.

say'2015-12-31').day-of-month;                                  # OUTPUT: «31␤» 
say =>'2015-12-24'), hour => 1).day-of-month# OUTPUT: «24␤» 

(Dateish) method day-of-week

Defined as:

method day-of-week(Date:D: --> Int:D)

Returns the day of the week, where 1 is Monday, 2 is Tuesday and Sunday is 7.

say'2015-12-31').day-of-week;                                  # OUTPUT: «4␤» 
say =>'2015-12-24'), hour => 1).day-of-week# OUTPUT: «4␤» 

(Dateish) method day-of-year

Defined as:

method day-of-year(Date:D: --> Int:D)

Returns the day of the year (1..366).

say'2015-12-31').day-of-year;                                  # OUTPUT: «365␤» 
say =>'2015-03-24'), hour => 1).day-of-year# OUTPUT: «83␤» 

(Dateish) method days-in-month

Defined as:

method days-in-month(Dateish:D: --> Int:D)

Returns the number of days in the month represented by the Dateish object:

say"2016-01-02").days-in-month;                # OUTPUT: «31␤» 
say<10000>:month<2>).days-in-month# OUTPUT: «29␤» 

(Dateish) method week

Defined as:

method week()

Returns a list of two integers: the year, and the week number. This is because at the start or end of a year, the week may actually belong to the other year.

my ($year$week="2014-12-31").week;
say $year;                       # OUTPUT: «2015␤» 
say $week;                       # OUTPUT: «1␤» 
say'2015-01-31').week# OUTPUT: «(2015 5)␤» 

(Dateish) method week-number

Defined as:

method week-number(Date:D: --> Int:D)

Returns the week number (1..53) of the date specified by the invocant. The first week of the year is defined by ISO as the one which contains the fourth day of January. Thus, dates early in January often end up in the last week of the prior year, and similarly, the final few days of December may be placed in the first week of the next year.

say"2014-12-31").week-number;   # 1  (first week of 2015) 
say"2016-01-02").week-number;   # 53 (last week of 2015) 

(Dateish) method week-year

Defined as:

method week-year(Date:D: --> Int:D)

Returns the week year of the date specified by the invocant. Normally week-year is equal to Date.year. Note however that dates early in January often end up in the last week of the prior year, and similarly, the final few days of December may be placed in the first week of the next year.

say"2015-11-15").week-year;   # 2015 
say"2014-12-31").week-year;   # 2015 (date belongs to the first week of 2015) 
say"2016-01-02").week-year;   # 2015 (date belongs to the last week of 2015) 

(Dateish) method weekday-of-month

Defined as:

method weekday-of-month(Date:D: --> Int:D)

Returns a number (1..5) indicating the number of times a particular day-of-week has occurred so far during that month, the day itself included.

say"2003-06-09").weekday-of-month;  # 2  (second Monday of the month) 

(Dateish) method yyyy-mm-dd

Defined as:

method yyyy-mm-dd(Date:D: --> Str:D)

Returns the date in YYYY-MM-DD format (ISO 8601)

say"2015-11-15").yyyy-mm-dd;   # OUTPUT: «2015-11-15␤» 
say OUTPUT: «2016-08-10␤» 

(Dateish) method daycount

Defined as:

method daycount(Dateish:D: --> Int:D)

Returns the number of days from the epoch Nov. 17, 1858 to the day of the invocant. The daycount returned by this method is the MJD, i.e. the Modified Julian Day, which is used routinely by e.g. astronomers, geodesists, scientists and others. The MJD convention is designed to facilitate simplified chronological calculations.

say'1995-09-27').daycount;    # OUTPUT: «49987␤» 

(Dateish) method IO

Defined as:

method IO(Dateish:D: --> IO::Path:D)

Returns an IO::Path object representing the stringified value of the Dateish object:;   # OUTPUT: «"2016-10-03".IO␤» OUTPUT: «"2016-10-03T11:14:47.977994-04:00".IO␤» 

PORTABILITY NOTE: some operating systems (e.g. Windows) do not permit colons (:) in filenames, which would be present in IO::Path created from a DateTime object.

Routines supplied by class Any

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

(Any) method ACCEPTS

Defined as:

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

(Any) 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␤» 

(Any) 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␤» 

(Any) 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␤» 

(Any) 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␤» 

(Any) 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␤» 

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

(Any) routine reverse

Defined as:

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

Returns a Seq say reverse ^10; # OUTPUT: «(9 8 7 6 5 4 3 2 1 0)␤»

(Any) method sort

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


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

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

(Any) 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]]␤» 

(Any) 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)␤» 

(Any) 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)␤» 

(Any) 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)␤» 

(Any) 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␤» 

(Any) 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␤» 

(Any) 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␤» 

(Any) sub exit

Defined as:

sub exit(Int() $status = 0)

Exits the current process with return code $status.

(Any) 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"␤» 

(Any) method Array

Defined as:

method Array(--> Array:Dis nodal

Coerce the invocant to Array.

(Any) method List

Defined as:

method List(--> List:Dis nodal

Coerce the invocant to List.

(Any) method Hash

Defined as:

method Hash(--> Hash:Dis nodal

Coerce the invocant to Hash.

(Any) method hash

Defined as:

method hash(--> Hash:Dis nodal

Coerce the invocant to Hash.

(Any) method Slip

Defined as:

method Slip(--> Slip:Dis nodal

Coerce the invocant to Slip.

(Any) method Map

Defined as:

method Map(--> Map:Dis nodal

Coerce the invocant to Map.

(Any) method Bag

Defined as:

method Bag(--> Bag:Dis nodal

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

(Any) method BagHash

Defined as:

method BagHash(--> BagHash:Dis nodal

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

(Any) method Set

Defined as:

method Set(--> Set:Dis nodal

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

(Any) method SetHash

Defined as:

method SetHash(--> SetHash:Dis nodal

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

(Any) method Mix

Defined as:

method Mix(--> Mix:Dis nodal

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

(Any) method MixHash

Defined as:

method MixHash(--> MixHash:Dis nodal

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

(Any) method Supply

Defined as:

method Supply(--> Supply:Dis nodal

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

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

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

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


(Any) method minpairs

Defined As:

multi method minpairs(Any:D: --> Seq: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␤» 

(Any) method maxpairs

Defined As:

multi method maxpairs(Any:D: --> Seq: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␤» 

(Any) method sum

Defined As:

    method sum(--> TODO)


(Any) method keys

Defined As:

    method keys(--> TODO)


(Any) method flatmap

Defined As:

    method flatmap(--> TODO)


(Any) method roll

Defined As:

    method roll(--> TODO)


(Any) method pick

Defined As:

    method pick(--> TODO)


(Any) method head

Defined As:

    method head(--> TODO)


(Any) method tail

Defined As:

    method tail(--> TODO)


(Any) method skip

Defined As:

    method skip(--> TODO)


(Any) method prepend

Defined As:

    method prepend(--> TODO)


(Any) method unshift

Defined As:

    method unshift(--> TODO)


(Any) method first

Defined As:

    method first(--> TODO)


(Any) method unique

Defined As:

    method unique(--> TODO)


(Any) method repeated

Defined As:

    method repeated(--> TODO)


(Any) method squish

Defined As:

    method squish(--> TODO)


(Any) method reduce

Defined As:

    method reduce(--> TODO)


(Any) method permutations

Defined As:

    method permutations(--> TODO)


(Any) method categorize

Defined As:

    method categorize(--> TODO)


(Any) method classify

Defined As:

    method classify(--> TODO)


(Any) method produce

Defined As:

    method produce(--> TODO)


(Any) method rotor

Defined As:

    method rotor(--> TODO)


(Any) method pairs

Defined As:

    method pairs(--> TODO)


(Any) method antipairs

Defined As:

    method antipairs(--> TODO)


(Any) method kv

Defined As:

    method kv(--> TODO)


(Any) method tree

Defined As:

    method tree(--> TODO)


(Any) method nl-out

Defined As:

    method nl-out(--> TODO)


(Any) method invert

Defined As:

    method invert(--> TODO)


(Any) method combinations

Defined As:

    method combinations(--> TODO)


(Any) method print-nl

Defined As:

    method print-nl(--> TODO)


(Any) method nodemap

Defined As:

    method nodemap(--> TODO)


(Any) method iterator

Defined As:

    method iterator(--> TODO)


(Any) method grep

Defined As:

    method grep(--> TODO)


(Any) method match

Defined As:

    method match(--> TODO)


(Any) method append

Defined As:

    method append(--> TODO)


(Any) method join

Defined As:

    method join(--> TODO)


(Any) method values

Defined As:

    method values(--> TODO)


(Any) method collate

Defined As:

    method collate(--> TODO)


(Any) method batch

Defined As:

    method batch(--> TODO)


(Any) method cache

Defined As:

    method cache(--> TODO)


Routines supplied by class Mu

Date 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 ='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 ='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;                # 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;    # OUTPUT: «␤» 

(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:{
my $p = => 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{
my $p =;

(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) 
say &cast.WHY;


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} ($_)";
# 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 $ {
    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␤»