Intro    Chapter:   0. History   1. Design   2. Basic   3. Var   4. Op   5. IO   6. Block   7. Sub   8. OOP   9. Regex   10. Meta
Overview   Appendix:   A. Index   B. Grouped   C. Classtree   D. Delta   E. Exciting   F. FAQ   G. Glossary   H. Href

"The most basic building blocks of a programming language are it's nouns, the chunks of data that get sucked in, pushed around, altered in various ways, and spat out to some new location." -- Allison Randal

Variable Types

Perl 6 (as Perl 5) knows 3 basic types of variables: Scalars (single values), Arrays (ordered and indexed lists of several values) and Hashes (2 column table, with ID and associated value pairs). They can be easily distinguished, because in front of their name is a special character called sigil (latin for sign). It's the $ (similar to S) for Scalars, @ (like an a) for Arrays and a % (kv pair icon) for a Hash. They are now invariant (not changing), which means for instance, an array vaiable starts always with an @, even if you just want a slice of the content.

$scalar
@array
@array[1] ####### $array[1] in Perl 5
@array[1,2]###### @array[1,2] in Perl 5
%hash
%hash{'ba'} ######### $hash{'ba'} in Perl 5
%hash{'ba','da','bim'} ### @hash{'ba','da','bim'} in Perl 5

The sigils also mark distinct namespaces, meaning: in one lexical scope you can have 3 different variables named $stuff, @stuff and %stuff. These sigils can also be used as an operator to enforce a context in which the following data will be seen.

The fourth namespace is for subroutines and similar, even if you don't usually think of them as variables. It's sigil & is used to refer to subroutines without calling them.

All special namespaces from Perl 5 (often marked with special syntax), like tokens (__PACKAGE__), formats, file or dir handles, or builtins are now regular variables or routines.

Because all variables contain objects, they have methods. In fact, all operators, including square or curly bracket subscripts, are just methods of an object with a fancy name.

The primary sigil can be followed by a secondary sigil, called a twigil, which indicates a special scope for that variable.

Scalar

This type stores one value, usually a reference to something: a value of a data type, a code object, an object or a compound of values like a pair, junction, array, hash or capture. The scalar context is now called item context, hence the scalar instruction from Perl 5 was renamed to item.

$CHAPTER = 3; # first comment!
$bin = 0b11; # same value in binary format
$pi = 3.14159_26535_89793; # the underscores just ease reading
$float = 6.02e-23; # floating number in scientific notation
$text = 'Welcome all!'; # single quoted string
# double quoted string, does eval $pi to it's content
$text = " What is $pi?";
$text = q:to'EOT'; # heredoc string

    handy for multiline text
    like HTML templates or email

EOT
$handle = open $file_name; # file handle
# an object from a class with a nested namespace
$object = Class::Name.new();
$condition = 3|5|7; # a junction, a logical conjunction of values
$arrayref = [0,1,1,2,3,5,8,13,21]; # an array stored as a single item
# a hash stored as a single item
$hashref = {'audreyt'=>'pugs',
            'pm'=>'pct',
            'damian'=>'larrys evil henchman'};
# pointing to a callable
$coderef = sub { do_something_completely_diffenent(@_) };

(For info on some of those terms: comment, binary format, the underscores ease reading, scientific notation, single-quoted string, double-quoted string, heredoc string, file handle, class, junction, list of values, hash, callable.)

Unlike Perl 5, references are automatically dereferenced to a fitting context. So you could use these $arrayrefs and $hashrefs similarly to an array or hash, making $ the universal variable prefix, pretty much like in PHP. The primary difference is that $ prefixed lists are not flattened in lists.

my $a = (1, 2, 3);
my @a = 1, 2, 3;
for $a { }          # just one iteration
for @a { }          # three iterations

Scalar Methods

my $chapter = 3;
undefine $chapter;
defined $a; # false, returns 0

Array

An array is an ordered and indexed list of scalars. If not specified otherwise, they can be changed, expanded and shortened anytime and used as a list, stack, queue and much more. As in Haskell, lists are processed lazily, which means: the compiler looks only at the part it currently needs. This way Perl 6 can handle infinite lists or do computation on lists that have not been computed yet. The lazy command enforces this and the eager command forces all values to be computed.

The list context is forced with a @() operator or list() command. That's not autoflattening like in Perl 5 (automatically convert a List of Lists into one List). If you still want that, say flat(). Or say lol() to explicitly prevent autoflattening.

@primes = (2,3,5,7,11,13,17,19,23); # an array gets filled like in Perl 5
@primes =  2,3,5,7,11,13,17,19,23 ; # same thing, since unlike P5 round braces just do group
@primes = <2 3 5 7 11 13 17 19 23>; # ditto, <> is the new qw()
$primes = (2,3,5,7,11,13,17,19,23); # same array object just sits in $primes, $primes[0] is 2
$primes = item @primes;             # same thing, more explicit
$primes = 2,;                       # just 2, first element of the Parcel
@primes = 2;                        # array with one element
@primes = [2,3,5,7,11,13,17,19,23]; # array with one element (List of Lists - LoL)
@dev    = {'dan' => 'parrot'};      # array with one element (a Hash)
@data   = [1..5],[6..10],[11..15];  # Array of Arrays (LoL)
@list   = lol @data;                # no change
@list   = flat @data;               # returns 1..15

Array Slices

@primes                       # all values as list
@primes.values                # same thing
@primes.keys                  # list of all indices
"@primes[]"                   # insert all values in a string, uses [] to distinguish from mail adresses
$prime = @primes[0];          # get the first prime
$prime = @primes[*-1];        # get the last one
@some = @primes[2..5];        # get several
$cell = @data[1][2];          # get 8, third value of second value (list)
$cell = @data[1;2];           # same thing, shorten syntax
@numbers = @data[1];          # get a copy of the second subarray (6..10)
@copy = @data;                # shallow copy of the array

Array Methods

Some of the more important things you can do with lists. All the methods can also used like ops in "elems @rray;"

? @rray;              # boolean context, Bool::True if array has any value in it, even if it's a 0
+ @rray;              # numeric context, number of elements (like in Perl 5 scalar @a)
~ @rray;              # string context, you get content of all cells, stringified and joined, same as "@primes[]"

@rray.elems;          # same as + @rray
@rray.end;            # number of the last element, equal to @rray.elems-1
@rray.cat;            # same ~ @rray
@rray.join('');       # also same result, you can put another string as parameter that gets between all values
@rray.unshift;        # prepend one value to the array
@rray.shift;          # remove the first value and return it
@rray.push;           # add one value on the end
@rray.pop;            # remove one value from the end and return it
@rray.splice($pos,$n);# starting at $pos remove $n values and replace them with values that follow those two parameters
@rray.delete(@ind); # delete all cells with indices in @ind
@rray.exists(@ind); # Bool::True if all indices of @ind have a value (can be 0 or '')
@rray.pick([$n]);     # return $n (default is 1) randomly selected values, without duplication
@rray.roll([$n]);     # return $n (default is 1) randomly selected values, duplication possible (like roll dice)
@rray.reverse;        # all elements in reversed order
# returns a list where $n times first item is taken to last
# position if $n is positive, if negative the other way around
@rray.rotate($n);

@rray.sort($coderef); # returns a list sorted by a user-defined criteria, default is alphanumerical sorting
@rray.min;            # numerical smallest value of that array
@rray.max;            # numerical largest value of that array
$a,$b= @rray.minmax;  # both at once, like in .sort,  .min, or .max, a sorting algorithm can be provided

@rray.map($coderef);  # high oder map function, runs $coderef with every value as $_ and returns the list or results
@rray.classify($cr);  # kind of map, but creates a hash, where keys are the results of $cr and values are from @rray
@rray.categorize($cr);# kind of classify, but closure can have no (Nil) or several results, so a key can have a list of values
@rray.grep({$_>1});   # high order grep, returns only these elements that pass a condition ($cr returns something positive)
@rray.first($coder);  # kind of grep, return just the first matching value
@rray.zip;            # join arrays by picking first element left successively from here and then there

There is even a whole class of metaoperators that work upon lists.

Hash

In Perl 6 a Hash is an unordered list of Pairs. A Pair is a single key => value association and appears in many places of the language syntax. A hash allows lookup of values by key using {} or <> syntax.

%dev =  'pugs'=>'audreyt', 'pct'=>'pm', "STD"=>'larry';
%dev = :rakudo('jnthn'), :testsuite('moritz');            # adverb (pair) syntax works as well
%dev = ('audreyt', 'pugs', 'pm', 'pct', 'larry', "STD");  # lists get autoconverted in hash context
%compiler = Parrot => {Rakudo => 'jnthn'}, SMOP => {Mildew => 'ruoso'};       # hash of hashes (HoH)

Hash Slices

$value = %dev{'key'};      # just give me the value related to that key, like in P5
$value = %dev<pm>;         # <> autoquotes like qw() in P5
$value = %dev<<$name>>;    # same thing, just with eval
@values = %dev{'key1', 'key2'};
@values = %dev<key1 key2>;
@values = %dev<<key1 key2 $key3>>;
%compiler<Parrot><Rakudo>; # value in a HoH, returns 'jnthn'
%compiler<SMOP>;           # returns the Pair: Mildew => 'ruoso'

%dev   {'audrey'};         # error, spaces between varname and braces (postcircumfix operator) are no longer allowed
%dev\  {'allison'};        # works, quote the space
%dev   .<dukeleto>;        # error
%dev\ .{'patrick'};        # works too, "long dot style", because it's an object in truth

Hash Methods

? %dev                    # bool context, true if hash has any pairs
+ %dev                    # numeric context, returns number of pairs(keys)
~ %dev                    # string context, nicely formatted 2 column table using \t and \n

$table = %dev;             # same as ~ %dev
%dev.say;                  # stringified, but only $key and $value are separated by \t
@pairs = %dev;             # list of all containing pairs
%dev.pairs                 # same thing in all context
%dev.elems                 # same as + %dev or + %dev.pairs
%dev.keys                  # returns a list of all keys
%dev.values                # list of all values
%dev.kv                    # flat list with key1, value1, key 2 ...
%dev.invert                # reverse all key => value relations
%dev.push (@pairs)         # inserts a list of pairs, if a key is already present in %dev, both values gets added to an array

Callable

Internally subroutines, methods and alike are variables with the sigil & and stored in a fourth namespace. Unlike Perl 5, all subroutines can be overwritten or augmented with user defined routines. Of course scalars can also contain routines.

&function = sub { ... };         # store subroutine in callable namespace
function();                      # call/run it

$coderef = sub { ... };          # store it in a scalar
$coderef($several, $parameter);  # run that code

Data Types

In contrast to variable types (container types) every value has a type too. These are organized internally as classes or roles and can be categorized into 3 piles: the undefined, immutable, and the mutable types.

You can assign one of these types to scalar, array, or hash variables, which enforces the contents to be that type.

my Int $a;
my Int @a;  # array of Int

Pair

Pairs are new and their syntax is used nearly everywhere in the language where there is an association between a name and a value.

$pair = 'jakub' => 'helena';  # "=>" is the pair constructor
$pair = :jakub('helena');     # same in adverbial notation
$pair = :jakub<helena>;       # same using <>, the new qw()
$pair.key                     # returns 'jakub'
$pair.value                   # returns 'helena'
$pair.isa(Pair)               # Bool::True

Enumeration

enum

Capture

Captures are also a new type, which holds the parameters a routine gets. Because Perl now knows both positional and named parameters, it is a mixture of a list and array.

$cap = \(@a,$s,%h,'a'=>3);    # creating a capture, "\" was free since there are no references anymore
|$cap                         # flatten into argument list (without |, it will pass it as a single value)
||$cap                        # flatten into semicolon list (meant for variadic functions that take list of lists)

One important difference between a capture and a compound structure of lists and hashes: While assignments with = will copy the complete content of the named variables, this is not so in the case of a capture. When I change $s in the last example, the content of $cap changes too, because when parameters to a routine are variables, they are also interpolated in the moment the routine is called, not when it's defined.

Properties and Traits

Properties

xxx

Traits

xxx

Scoping

scope declarator, scopes

my $var;
state
temp
let
our $var;
$*var;

Twigils

xxx

Assignment and Binding

Assignment

As rightfully expected, assignments are done with the equal sign. But unlike Perl 5 you always get a copy of the right side data assigned to the left, no matter how nested the data structure was (lists of lists eg). You never get in Perl 6 a reference with =. The only exception may be seen captures.

my @original = [1,2],[3,4];
my $copy = @original[0]; # $copy points to [1,2]
@original[0][0] = 'fresh stuff'; # $copy[0] holds still 1

Binding

Since every variable in Perl 6 is a reference, programmers can use binding to get 2 variables that point to the same memory location.

$original = 5;
$original := $mirror;       # normal binding, done on runtime
$original ::= $mirror;      # same thing, but done during compile time
$original = 3;
say $mirror;                # prints 3
$original =:= $mirror       # true, because they're bound together
$original === $mirror       # also true, because content and type are equal

Special Variables

are listed in Index B. To understand their secondary sigil click here.


Intro    Chapter:   0. History   1. Design   2. Basic   3. Var   4. Op   5. IO   6. Block   7. Sub   8. OOP   9. Regex   10. Meta
Overview   Appendix:   A. Index   B. Grouped   C. Classtree   D. Delta   E. Exciting   F. FAQ   G. Glossary   H. Href