=begin pod

=TITLE FAQ

=SUBTITLE Frequently Asked Questions about Perl 6

=head1 General

=head2 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.

=head2 Is there going to be a Perl 6 version 6.0.0?

"Perl 6" is a language, not an implementation of that language.  Think of
"Perl 6" as being like "C", "C++", "Javascript", etc., where the language is
separate from the (many) implementations of that language.

There are two key points to make:

1.  Language specification should follow implementations, not precede them.
This has been found to be true for many programming languages, and it's the
way things work in the Internet RFC/STD process.  An update to a language
spec recognizes and ratifies the features that have been largely agreed upon
by implementations and users, as opposed to prescribing what the next version
of the language ought to look like.  First is rough consensus, then running
code, and *then* formalization into a specification.

So, if language specification follows implementation, it's not possible for
Rakudo or other implementations to use language version numbers as their
primary versioning scheme.  To take an example from the C language:  a
recent gcc compiler may say it's version 5.2.1, but there's not a version
"5.2.1" of the C Programming Language.  Similarly, one doesn't speak of the
"C89", "C99", or "C11" release of GCC.

2.  It doesn't make a lot of sense to think of major/minor version numbers
such as 6.x.y when discussing a language specification.  Compiler releases
happen often, incorporating new features, bug fixes, and small incremental
changes.  Language specification changes tend to happen on longer timescales
-- there's not really a notion of a "minor release" on such timescales.  So,
the language specifications are being versioned as "6.a", "6.b", "6.c", etc.,
instead of a scheme incorporating minor version increments.

This separation of language specification and implementation can be unnerving
to those that are so used to Perl 5's tight coupling of the two, including
using a common "version number" for both.  But that tight coupling is partly
what led to several of Perl 5's evolutionary dead ends and roadblocks, and
we're trying to avoid repeating that mistake with Perl 6.

=head2 As a Perl 6 beginner what should I install?

Linux or Mac users probably want to download Rakudo Star and
install via compilation (a simple process) the MoarVM based version available
from L<http://rakudo.org/downloads/star/|http://rakudo.org/downloads/star>.

Compilation needs a C compiler and Perl 5 installed.

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

If you are a Windows 32 or 64 bit user then Rakudo Star binaries are also
available at the rakudo site. You will need Windows Git to use panda.

To use panda (see below) to install library modules you will need git and Perl
5's Test::Harness.

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

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

Install L<rakudobrew|https://github.com/tadzik/rakudobrew> which resembles
Perl 5's perlbrew and the equivalent Python and Ruby tools.

=head2 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.

L<https://www.perl6.org/documentation/|https://www.perl6.org/documentation/> with
L<https://doc.perl6.org/|https://doc.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
L<Google|https://www.google.co.uk/search?q=site:irclog.perlgeek.de+inurl:perl6>

=head2 What is the Perl 6 spec?

The "spec" refers to the official test suite for Perl 6.  It's called
roast and L<hosted on github|https://github.com/perl6/roast>. It
is the measure of how complete a Perl 6 implementation is.

=head2 Is there a glossary of Perl 6 related terms?

See L<S99|https://design.perl6.org/S99.html>

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

See the pod with the 5to6- prefix under L<https://doc.perl6.org/language.html|https://doc.perl6.org/language.html>

=head1 Modules

=head2 Is there a CPAN for Perl 6?

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

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

=head2 Can I use Perl 5 modules from Perl 6?

Yes, with L<Inline::Perl5|https://github.com/niner/Inline-Perl5/>, which works
well with most Perl 5 modules. It can even run Perl 5 Catalyst and DBI.

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

L<Nativecall|https://docs.perl6.org/language/nativecall> makes this particularly easy.

=head2 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.

=head2 Where have all the traditional UNIX library functions gone?

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

A ecosystem module L<POSIX|https://github.com/cspencer/perl6-posix> is
also available.

=head2 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.

=head1 Language Features

=head2 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
L<Data::Dump|https://github.com/tony-o/perl6-data-dump/>, which uses color.

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

Install  L<Linenoise|https://github.com/hoelzro/p6-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".

=head2 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 ...

=head2 What is C<(Any)>?

L<Any|type/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

=head2 What is C<so>?

C<so> is a loose precedence operator that coerces to L<Bool|/type/Bool>.

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

Example usage:

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

In this example, the result of the comparison (which is a
L<Junction|/type/Junction>), is
converted to Bool before being printed.

=head2 What are those C<:D> and C<: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 C<Int> type object itself:

    $x = Int

If you want to exclude type objects, you can append the C<: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 C<:U> constrains to undefined values, that is, type objects.

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

=head2 What is the C<< --> >> thing in the signature?

C<< --> >> 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.

=head2 How can I extract the values from a Junction?

If you want to extract the values (eigenstates) from a
L<Junction|/type/Junction>, you are probably doing something wrong, and
should be using a L<Set|/type/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

=head2 If Str is immutable, how does C<s///> work? if Int is immutable, how does C<$i++> work?

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

See the documentation on L<containers|/language/containers> for more
information.

=head2 What's up with array references and automatic dereferencing? Do I still need the C<@> 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 C<@( ... )> or by calling the C<.list> method
on an expression, and item context (not flattening) with C<$( ... )>
or by calling the C<.item> method on an expression.


=head2 Why sigils? Couldn't you do without them?

There are several reasons:

=item they make it easy to interpolate variables into strings

=item they form micro-namespaces for different variables and twigils, thus avoiding name clashes

=item they allow easy single/plural distinction

=item they work like natural languages that use mandatory noun markers, so our brains are built to handle it

=item they aren't mandatory, since you can declare sigilless names (if you don't mind the ambiguity)


=head2 Does Perl 6 have coroutines? What about C<yield>?

Perl 6 has no C<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 { x² });

=head2 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 I<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 C<submethod BUILD> that
initializes them:

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

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

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

=head2 How and why do C<say>, C<put> and C<print> differ?

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

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

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

Example: type objects, also known as "undefined values", stringify
to an empty string and warn, whereas the C<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 C<say> is optimized for debugging and display to people, C<print>
and C<put> is more suitable for producing output for other programs
to consume.

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

=head2 What's the difference between C<token> and C<rule> ?

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

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

C<rule> implies both the C<:ratchet> and C<:sigspace> (short C<:s>)
modifier, which means a rule doesn't backtrace, and it treats
whitespace in the text of the regex as C«<.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.

C<regex> declares a plain regex without any implied modifiers.

=head2 What's the difference between C<die> and C<fail>?

C<die> throws an exception.

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

A C<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 C<Failure>
as an ordinary object, or ignore it in sink context.

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

=head2 Why is C<wantarray> or C<want> gone? Can I return different things in different contexts?

Perl 5 has the L<C<wantarray>|/language/5to6-perlfunc#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 C<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 L<lot easier|/language/5to6-perlfunc#wantarray>
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 L<Match objects that know how to respond
to list indexing, hash indexing, and that can turn into the matched
string|/type/Match>.

=head1 Meta Questions and Advocacy

=head2 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 6c (Christmas 2015) is the first official release of Perl 6
as a language, along with a validation suite and a compiler that passes it.

=head2 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.

=item Perl 6 offers procedural, object-oriented AND functional programming methodologies.

=item Easy to use consistent syntax, using invariable sigils for data-structures.

=item Full grapheme based Unicode support, including Annex #29.

=item Regular expressions are cleaned up, made more readable, taken to the next level of usability, with a lot more functionality.  Named regular expressions are made possible for ease of use.

=item Junctions allowing easy checking of multiple possibilities, e.g. $a == 1|3|42 (meaning is $a equal to 1 or 3 or 42).

=item Dynamic variables provide a lexically scoped alternative to global variables.

=item Emphasis on composability and lexical scoping to prevent “action at a distance”.  For example, imports are always lexically scoped.

=item Easy to understand consistent scoping rules and closures.

=item Powerful object orientation, with classes and roles (everything can be seen as an object). Inheritance. Subtyping. Code-reuse.

=item Introspection into objects and meta-objects (turtles all the way down).

=item Meta Object Protocol allowing for meta-programming without needing to generate / parse code.

=item Subroutine and method signatures for easy unpacking of positional and named parameters.

=item Multi dispatch on identically named subroutines/methods with different signatures, based on arity, types and optional additional code.

=item Compile time error reporting on unknown subroutines / impossible dispatch.

=item Optional gradual type-checking at no additional runtime cost.  With optional type annotations.

=item Advanced error reporting based on introspection of the compiler/runtime state.  This means more useful, more precise error messages.

=item Phasers (like BEGIN / END) allow code to be executed at scope entry / exit, loop first / last / next and many more special contexts.

=item High level concurrency model, both for implicit as well as explicit multi-processing, which goes way beyond primitive threads and locks.  Perl 6's concurrency offers a rich set of (composable) tools.

=item Multiple-core computers are getting used more and more, and with Perl 6 these can be used thanks to parallelism, both implicit (e.g. with the >>. method) and explicit ( start { code } ).  This is important, because Moore's Law is ending.

=item Structured language support is provided to enable programming for asynchronous execution of code.

=item Supplies allow code to be executed when something happens (like a timer, or a signal, or a file-system event).

=item react / whenever / supply keywords allows easy construction of interactive, event driven applications.

=item Lazy evaluation when possible, eager evaluation when wanted or necessary.   This means, for example, lazy lists, and even infinite lazy lists, like the Fibonacci sequence, or all prime numbers.

=item Native data types for faster, closer to the metal, processing.

=item Interfacing to external libraries in C / C++ are trivially simple with NativeCall.

=item Interfacing with Perl 5 (CPAN) / Python modules trivially simple with Inline::Perl5 resp. Inline::Python.

=item Can have multiple versions of a module installed and loaded simultaneously.

=item System administration simplified due to simpler update/upgrade policies.

=item Simple numeric computation without precision loss because of Rats (rational numbers).

=item Extensible grammars for parsing data or code (which Perl 6 uses to parse itself).

=item Perl 6 is a very mutable language (define your own functions, operators, traits and data-types, which modify the parser for you).

=item Large selection of data-types, plus the possibility to create your own types.

=item Multi-dimensional shaped and/or native arrays with proper bounds checking.

=item Execute code at any time during parsing of a grammar, or when a certain match occurred.

=item Adding a custom operator or adding a trait is as simple as writing a subroutine.

=item Automatic generation of hyper-operators on any operator (system or custom added).

=item Runs on a variety of back-ends.  Currently MoarVM & JVM, JavaScript in development, more may follow.

=item Runtime optimization of hot code paths during execution (JIT).

=item Runs on small (e.g. Raspberry Pi) and large multi-processor hardware.

=item Garbage collect based: no timely destruction, so no ref-counting necessary.  Use phasers for timely actions.

=item Methods can be mixed into any instantiated object at runtime, e.g. to allow adding out-of-band data.

=item Easy command-line interface accessible by MAIN subroutine with multiple dispatch and automated usage message generation.

=item Fewer lines of code allow for more compact program creation.  Huffman-coding of names allows for better readability.

=item Lazy lists defined with a simple iterator interface, which any class can supply by minimally supplying a single method.

=item Perl 6's motto's remain the same as they have been for Perl all along: “Perl is different. In a nutshell, Perl is designed to make the easy jobs easy, without making the hard jobs impossible.” and “There Is More Than One Way To Do It”.  Now with even more -Ofun added.

Please see the L<feature comparison
matrix|https://perl6.org/compilers/features> for an overview of implemented
features.

=head2 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.  After the Christmas 2015 release stabilizes
the definition of the language, we'll be 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;

=end pod
