Raku Books / Perl 6 at a Glance / Appendix

Whatever (*)

In Perl 6, the star character * can be associated with one of the predefined classes, Whatever and WhateverCode.

We’ll start with an object of the Whatever class.

say *.WHAT; # (Whatever)

The construction like 1 .. * creates a Range object, where its upper limit is not fixed to any particular number.

say (1 .. *).WHAT; # (Range)

Here is an example with a loop that prints the numbers from 5 to 10 line by line:

for (5 .. *) {
    .say;
    last if $_ == 10;
}

Now, try array indices and ask to take all the elements starting from the fourth one:

my @a = <2 4 6 8 10 12>;
say @a[3 .. *]; # (8 10 12)

The “three dots” operator in combination with a star creates a sequence.

say (1 ... *).WHAT; # (Seq)

You can use it when you need a lazy and potentially infinite list. A lazy list is a list whose elements are evaluated only when they are necessary for the execution of the programme.

In the following example, an array does not know its size, but you can read infinitely from it; the lazy list will supply new elements:

my @a = (100 ... *);

for (0 .. 5) {
    say "Element $_ is @a[$_]";
}

This programme will print five lines corresponding to the first five elements of the @a array, which contain values from 100 to 105, including 105. If you change the range in the for loop from 0 .. 5 to 0 .. *, you will get a programme that prints infinitely.

CodeBlockPlaceholder7raku my @a = (1, 2 … *); # step by 1 say @a [1..5]; # (2 3 4 5 6)

my @b = (2, 4 … *); # even numbers say @b [1..5]; # (4 6 8 10 12)

my @c = (2, 4, 8 … ); # powers of two say @c [1..5]; # (4 8 16 32 64) CodeBlockPlaceholder8raku-static my @default_values = ‘NULL’ xx ; CodeBlockPlaceholder9raku my $f = * ** 2; # square say $f(16); # 256

my $xy = * ** *; # power of any say $xy(3, 4); # 81 CodeBlockPlaceholder10raku # An anonymous code block with one argument $x my $f = -> $x {$x ** 2}; say $f(16); # 256

A block with two arguments; names are alphabetically sorted

my $xy = {$^a ** $^b}; say $xy(3, 4); # 81 CodeBlockPlaceholder11raku my @a = <2 4 6 8 10 12>; say @a[3 .. *-2]; # (8 10) CodeBlockPlaceholder12raku-static

Unsupported use of a negative -1 subscript to index from the end; in Perl 6 please use a function such as -1 CodeBlockPlaceholder13raku-static say @a[*-1]; # 12 CodeBlockPlaceholder14raku-static @a [@a.elems - 1] CodeBlockPlaceholder15raku my @f = 0, 1, + * … *; say @f [1..7].join(‘,’); # 1, 1, 2, 3, 5, 8, 13 CodeBlockPlaceholder16

```

Course navigation

Unicode   |   Files