FAQ

Frequently Asked Questions about Perl 6

General

What's the difference between Rakudo and Perl 6?

Rakudo is an implementation of Perl 6. It's currently the most developed, but there have been other implementations in the past and should be others in the future. Perl 6 is the definition of the language. Many times the two names will be used loosely and interchangeably.

Is there going to be a Perl 6 version 6.0.0?

The version of the first stable language version is called v6.c, not 6.0.0. The different naming scheme makes it unlikely that there'll ever be a release of the language with the exact version 6.0.0.

You can check your Rakudo compiler is at least the current release version (note this may not be true of vendor binaries) with the following:

perl6 -e 'say q[too old] if $*PERL.version before Version.new(q[6.c])'

It was first implemented by the Rakudo Perl 6 compiler version 2015.12 and is likely to be supported by subsequent releases for the foreseeable future by use of the 'use 6.c' pragma. The next language version (no release date) is to be v6.d.

As a Perl 6 beginner what should I install?

Mac users can use the latest Rakudo Star DMG binary installer at http://rakudo.org/downloads/star

Windows users can use the Rakudo Star MSI binary installer. You will need Windows Git and Strawberry Perl 5 to use panda to install library modules.

Linux users probably want to download Rakudo Star and follow the compilation instructions at http://www.perl6.org/downloads/

There should be Linux and Mac binaries available shortly from vendors and third parties. Although vendor versions may be outdated.

Or there is an official rakudo star docker image at https://hub.docker.com/_/rakudo-star/

As an intermediate to advanced user I want to track Rakudo development.

Install rakudobrew which resembles Perl 5's perlbrew and the equivalent Python and Ruby tools.

Where can I find good documentation on Perl 6?

The most reliable information is to be found either under the perl6.org domains or directly linked from it.

https://www.perl6.org/documentation/ with https://docs.perl6.org/ as the canonical technical reference.

There is much good recent material on YouTube but be careful to check any dates on webpages since much of the Perl 6 information on random websites found by Google is often outdated.

You could also try searching the Freenode #perl6 IRC channel log via Google

What is the Perl 6 spec?

The "spec" refers to the official test suite for Perl 6. It's called roast and hosted on github. It is the measure of how complete a Perl 6 implementation is.

Yes, see glossary.

I'm a Perl 5 programmer. Where is a list of differences between Perl 5 and Perl 6?

See the '5to6-nutshell' pod under https://docs.perl6.org/language/5to6-nutshell and related pages.

I'm a Ruby programmer looking for quickstart type docs?

See the 'rb-nutshell' pod under https://docs.perl6.org/language/rb-nutshell

Modules

Is there a CPAN for Perl 6?

There isn't yet a module repository for Perl 6 as sophisticated as CPAN. But modules.perl6.org has a list of known Perl 6 modules called the "ecosystem" hosted on github, and panda can install those that work with rakudo.

Support for installing Perl 6 modules from the Perl 5 CPAN is on its way.

Can I use Perl 5 modules from Perl 6?

Yes, with Inline::Perl5, which works well with most Perl 5 modules. It can even run Perl 5 Catalyst and DBI.

Can I use C and C++ from Perl 6?

Nativecall makes this particularly easy.

Nativecall can't find libfoo.so and I only have libfoo.so.1.2!

This is commonly seen on Debian-like systems. You need to install "libfoo-dev" to set a sym link for the missing file.

Where have all the traditional UNIX library functions gone?

It's very easy to use Nativecall to access them.

A ecosystem module POSIX is also available.

Does Rakudo have a core standard library?

Rakudo is a compiler release with minimal batteries included (Test and Nativecall etc.) rather like the linux kernel itself.

Rakudo Star is a distribution of rakudo which ships with some useful modules and many more can be installed from the ecosystem.

Is there something like B::Deparse/how can I get hold of the AST?

Use perl6 --target=ast -e 'very-short-example()' to get hold of the AST of a compilation unit.

Language Features

How can I dump Perl 6 data structures (like Perl 5 Data::Dumper and similar)?

Examples:

my $foo="bar"
dd $foo # Str $foo = "bar"
say :$foo.perl # :foo("bar")
say :$foo.gist # foo => bar

There are also modules in the ecosystem to do this, like Data::Dump, which uses color.

How can I get command line history in the Perl 6 prompt (REPL)?

Install Linenoise from the ecosystem.

An alternative on UNIX like systems is to install rlwrap. This can be done on Debian-ish systems by "apt-get install rlwrap".

Why is the Rakudo compiler sometimes more apologetic?

If SORRY! is present in the output the error is a compile time error otherwise it's runtime.

Example:

say 1/0 # Attempt to divide 1 by zero using div

sub foo( Int $a, Int $b ) {...}
foo(1) # ===SORRY!=== Error while compiling ...

What is (Any)?

Any is a top level class used as a default superclass for new classes. It is often seen in a context where a variable has been defined but not assigned where it loosely resembles the undef or null values in other languages.

Example:

my $foo
say $foo # (Any) note the parens indicate type object
say $foo.^name # Any

(Any) shouldn't be used to check for definedness. In Perl 6, definedness is a property of an object. Usually instances are defined and type objects are undefined.

say 1.defined # True
say (Any).defined # False

What is so?

so is a loose precedence operator that coerces to Bool.

It has the same semantics as the ? prefix operator, just like and is the low-precedence version of &&.

Example usage:

say so 1|2 == 2;    # Bool::True

In this example, the result of the comparison (which is a Junction), is converted to Bool before being printed.

What are those :D and :U things in signatures?

In Perl 6, classes and other types are objects, and pass type checks of their own type.

For example if you declare a variable

my Int $x = 42;

then not only can you assign integers (that is, instances of class Int) to it, but the Int type object itself:

$x = Int

If you want to exclude type objects, you can append the :D type smiley, which stands for "definite":

my Int:D $x = 42;
$x = Int;   # dies with:
            # Type check failed in assignment to $x;
            # expected Int:D but got Int

Likewise :U constrains to undefined values, that is, type objects.

To explicitly allow either type objects or instances, you can use :_.

What is the --> thing in the signature?

--> is a return constraint, either a type or a definite value.

Example of a type constraint:

sub divide-to-int( Int $a, Int $b --> Int ) {
        return ($a / $b).narrow;
}

divide-to-int(3, 2)
# Type check failed for return value; expected Int but got Rat

Example of a definite return value:

sub discard-random-number( --> 42 ) { rand }
say discard-random-number
# 42

In this case the final value is thrown away because the return value is already specified.

How can I extract the values from a Junction?

If you want to extract the values (eigenstates) from a Junction, you are probably doing something wrong, and should be using a Set instead.

Junctions are meant as matchers, not for doing algebra with them.

If you want to do it anyway, you can abuse autothreading for that:

sub eigenstates(Mu $j) {
    my @states;
    -> Any $s { @states.push: $s }.($j);
    @states;
}

say eigenstates(1|2|3).join(', ');
# prints 1, 2, 3 or a permutation thereof

If Str is immutable, how does s/// work? if Int is immutable, how does $i++ work?

In Perl 6, values of many basic types are immutable, but the variables holding them are not. The s/// operator works on a variable, into which it puts a newly created string object. Likewise $i++ works on the $i variable, not just on the value in it.

See the documentation on containers for more information.

What's up with array references and automatic dereferencing? Do I still need the @ sigil?

In Perl 6, nearly everything is a reference, so talking about taking references doesn't make much sense. Unlike Perl 5, scalar variables can also contain arrays directly:

my @a = 1, 2, 3;
say @a;                 # "1 2 3\n"
say @a.WHAT;            # (Array)

my $scalar = @a;
say $scalar;            # "1 2 3\n"
say $scalar.WHAT;       # (Array)

The big difference is that arrays inside a scalar act as one value in list context, whereas arrays will be happily iterated over.

my @a = 1, 2, 3;
my $s = @a;

for @a { ... }          # loop body executed 3 times
for $s { ... }          # loop body executed only once

my @flat = flat @a, @a;
say @flat.elems;        # 6

my @nested = flat $s, $s;
say @nested.elems;      # 2

You can force flattening with @( ... ) or by calling the .list method on an expression, and item context (not flattening) with $( ... ) or by calling the .item method on an expression.

Why sigils? Couldn't you do without them?

There are several reasons:

"Type Str does not support associative indexing."

You likely tried to mix string interpolation and HTML.

my $foo = "abc";
say "$foo<html-tag>";

Perl 6 thinks $foo to be a Hash and <html-tag> to be a string literal hash key. Use a closure to help it to understand you.

my $foo = "abc";
say "{$foo}<html-tag>";

Does Perl 6 have coroutines? What about yield?

Perl 6 has no yield statement like python does, but it does offer similar functionality through lazy lists. There are two popular ways to write routines that return lazy lists:

# first method, gather/take
my @values = gather while have_data() {
    # do some computations
    take some_data();
    # do more computations
}

# second method, use .map or similar method
# on a lazy list
my @squares = (1..*).map(-> \x {  });

Why can't I initialize private attributes from the new method, and how can I fix this?

Code like

class A {
    has $!x;
    method show-x {
        say $!x;
    }
}
A.new(x => 5).show-x;

does not print 5. Private attributes are private, which means invisible to the outside. If the default constructor could initialize them, they would leak into the public API.

If you still want it to work, you can add a submethod BUILD that initializes them:

class B {
    has $!x;
    submethod BUILD(:$!x) { }
    method show-x {
        say $!x;
    }
}
A.new(x => 5).show-x;

BUILD is called by the default constructor (indirectly, see Object Construction for more details) with all the named arguments that the user passes to the constructor. :$!x is a named parameter with name x, and when called with a named argument of name x, its value is bound to the attribute $!x.

But don't do that. If the name is public, there is no downside to declaring it that way with $.x since the external view is readonly by default, and you can still access it internally with $!x.

How and why do say, put and print differ?

The most obvious difference is that say and put append a newline at the end of the output, and print does not.

But there is another difference: print and put converts its arguments to a string by calling the Str method on each item passed to, say uses the gist method instead. The former is meant for computers, the latter for human interpretation.

Or phrased differently, $obj.Str gives a string representation, $obj.gist a short summary of that object suitable for fast recognition by the programmer, and $obj.perl gives a Perlish representation.

Example: type objects, also known as "undefined values", stringify to an empty string and warn, whereas the gist method returns the name of the type, followed by an empty pair of parenthesis (to indicate there's nothing in that value except the type).

my Date $x;     # $x now contains the Date type object
print $x;       # empty string plus warning
say $x;         # (Date)\n

So say is optimized for debugging and display to people, print and put is more suitable for producing output for other programs to consume.

put is thus sort of a hybrid between print and say; like print, its output is suitable for other programs, and like say, it adds a newline at the end of the output.

What's the difference between token and rule ?

regex, token and rule all three introduce regexes, but with slightly different semantics.

token implies the :ratchet or :r modifier, which prevents the rule from backtracking.

rule implies both the :ratchet and :sigspace (short :s) modifier, which means a rule doesn't backtrace, and it treats whitespace in the text of the regex as <.ws> calls (ie matches whitespace, which is optional except between two word characters). Whitespace at the start of the regex and at the start of each branch of an alternation is ignored.

regex declares a plain regex without any implied modifiers.

What's the difference between die and fail?

die throws an exception.

fail returns a Failure object. (If the caller has declared use fatal; in the calling lexical scope, fail throws an exception instead of returning.)

A Failure is an "unthrown" or "lazy" exception. It is an object that contains the exception, and throws the exception if you try to use the Failure as an ordinary object, or ignore it in sink context.

A Failure returns False from a defined check, and you can extract the exception with the exception method.

Why is wantarray or want gone? Can I return different things in different contexts?

Perl 5 has the wantarray function that tells you whether it is called in void, scalar or list context. Perl 6 has no equivalent construct, because context does not flow inwards, i.e. a routine would need time travel to know which context it is called in because context is lazy, known only when the results are used later.

For example, Perl 6 has multiple dispatch, so in a code example like

multi w(Int $x) { say 'Int' }
multi w(Str $x) { say 'Str' }
w(f());

there is no way to determine if the caller of sub f wants a string or an integer, because it is not yet known what the caller is. In general this requires solving the halting problem, which even Perl 6 compiler writers have trouble with.

One way to achieve context sensitivity in Perl 6 is to return an object that knows how to respond to method calls that are typical for a context. In Perl 6 this is actually a lot easier than it may sound, and other features of the language either mitigate the need to do so in the first place, or make it possible to cover most of the use cases of wantarray.

For example regex matches return Match objects that know how to respond to list indexing, hash indexing, and that can turn into the matched string.

What's the difference between Pointer and OpaquePointer?

OpaquePointer is deprecated and has been replaced with Pointer.

Perl 6 Implementation

What Perl 6 Implementations are available?

Currently the best developed is Rakudo (using multiple Virtual Machine backends). Historic implementations include Niecza (.NET) and Pugs (Haskell). Others are listed at Perl 6 Compilers

What language is Rakudo written in?

A short answer is that Rakudo is written almost entirely in Perl 6. A more detailed answer is that Rakudo is written in a mixture of Perl 6 and NQP ("Not Quite Perl"). NQP is a lightweight Perl 6-like environment for virtual machines; it's designed to be a high-level way to create compilers and libraries for virtual machines (such as MoarVM and JVM) using Perl 6 syntax.

What language is NQP written in?

NQP is a mixture of (1) NQP code, (2) whatever language the underlying virtual machine is using, (3) some third-party C and Java libraries, and (4) some bootstrapping files created by earlier runs of the build process.

Meta Questions and Advocacy

When will Perl 6 be ready? Is it ready now?

Readiness of programming languages and their compilers is not a binary decision. As they (both the language and the implementations) evolve, they grow steadily more usable. Depending on your demands on a programming language, Perl 6 and its compilers might or might not be ready for you.

That said, version 6.c (Christmas 2015) is the first official release of Perl 6 as a language, along with a validation suite and a compiler that passes it.

Why should I learn Perl 6? What's so great about it?

Perl 6 unifies many great ideas that aren't usually found in other programming languages. While several other languages offer some of these features, none of them offer all.

Please see the feature comparison matrix for an overview of implemented features.

Is Perl 6 fast enough for me?

That depends on what you are doing. Rakudo has been developed with the philosophy of "make it work right then make it work fast". It's fast for some things already but needs work on others. Since the Christmas 2015 release stabilized the definition of the language, we're spending much of our effort on optimizing in 2016. Since Perl 6 provides lots of clues to the JIT that other dynamic languages don't, we think we'll have a lot of headroom for performance improvements. Some things already run faster than Perl 5.

Perl 5 programmers should be aware that Perl 6 comes with more built-in functionality. Simple benchmarks will be misleading unless you include things like Moose, type checking modules etc. in your Perl 5 script.

The following crude benchmarks, with all the usual caveats about such things, can show Perl 6 can be faster than Perl 5 for some similar common tasks if the big weaponry is included, but at the same time Perl 5 can be much faster if only the bare bones are included.

Try it on your system you may be pleasantly surprised!

Examples:

# Perl 6 version
use v6;

class Foo { has $.i is rw };

for (1..1_000_000) -> $i {
    my $obj = Foo.new;
    $obj.i = $i;
}

# Perl 5 version
package Foo;
use Moose;

has i => (is => 'rw');

__PACKAGE__->meta->make_immutable;

for my $i (1..1_000_000) {
    my $obj = Foo->new;
    $obj->i($i);
}

1;

# Another Perl 5 version that offers bare-bones set of features
# compared to Moose/Perl 6's version but those are not needed in this
# specific, simple program anyway.
package Foo;
use Mojo::Base -base;

has 'i';

for my $i (1..1_000_000) {
    my $obj = Foo->new;
    $obj->i($i);
}

1;

# A perl program which works under both perl5 (with perl -Mbigint)
# and perl6

my ($prev, $current) = (1, 0);

for (0..100_000) {
    ($prev, $current) = ($current, $prev + $current);
}
print $current;