=begin pod

=for comment
This is a rather 1:1 "translation" from Perl 5's perlintro to Perl 6 - feel free
to adopt any changes. Big chunks have been kept literaly.

=TITLE perlintro -- A brief introduction and overview of Perl 6

=begin DESCRIPTION

This document is intended to give you a quick overview of the Perl programming
language as of version 6, along with pointers to further documentation.  It is
intended as a "bootstrap" guide for those who are new to the language, and
provides just enough information for you to be able to read other peoples'
Perl and understand roughly what it's doing, or write your own simple
scripts.

This introductory document does not aim to be complete.  It does not
even aim to be entirely accurate.  In some cases perfection has been
sacrificed in the goal of getting the general idea across.  You are
B<strongly> advised to follow this introduction with more information from
the full Perl manual, the table of contents to which can be found in
L<doc:perltoc>.

Throughout this document you'll see references to other parts of the
Perl documentation.  You can read that documentation using the K<grok>
command or whatever method you're using to read this document.

=head2 What is Perl?

Perl is a general-purpose programming language originally developed for
text manipulation and now used for a wide range of tasks including system
administration, web development, network programming, GUI development, and
more.

The language is intended to be practical (easy to use, efficient, complete).
rather than beautiful (tiny, elegant, minimal).  Its major features are that 
it's easy to learn and use, supports procedural, object-oriented (OO) and a
bit of functional programming, and has powerful built-in support for text
processing. It can also use the large collection of Perl 5 modules, and,
depending on the implementation, possibly modules from other languages (see
Parrot).

=head2 Running Perl Programs

Currently, the main interpreter is Rakudo, available at L<http://rakudo.org>.
This is the most complete interpreter so far, but is kind of slow.

Assuming your code is in a file named K<foo.pl>, you can invoke your program as:

=input rakudo foo.pl

You can also write one-liners with the K<-e> option:

=input rakudo -e '"Hello World".say'

=head2 Basic syntax overview

A Perl script or program consists of one or more statements.  These
statements are simply written in the script in a straightforward fashion.  
There is no need to have a C<main()> function or anything of that kind.

Perl statements end with a semi-colon:

    say "Hello, world";

Comments start with a hash symbol and run to the end of the line. You can
also have comments that are in the middle of a line by enclosing the comment
with a pair of bracketing characters. You can not put space between the bracket
and the hash:

    # This is a comment
    say #(this is a comment too) "Hello World";

Whitespace is irrelevant, for the most part. However, there are some places
where space is required or not allowed:

    say
        "Hello, world"
       ;    # this works
    "foo" .say; # this is a syntax error, no space allowed.
    "foo"\   .say; # this is a "long dot", allowed. backslashed whitespace is ignored.

... except inside quoted strings:

    # this would print with a linebreak in the middle
    say "Hello
    world";

Double quotes or single quotes may be used around literal strings:

    say "Hello, world";
    say 'Hello, world';

However, only double quotes "interpolate" variables and special characters
such as newlines ("\n"):

    print "Hello, $name\n";     # works fine
    print 'Hello, $name\n';     # prints $name\n literally

(Note that C<print> and C<say> do the same thing, except C<say> appends a newline
character at the end.)

Numbers don't need quotes around them:

    say 42;

You can use parentheses for functions' arguments or omit them according
to your personal taste.  They are only required occasionally to clarify
issues of precedence.

    say("Hello, world");
    say "Hello, world";

You can call methods in OO-Style notation:

    "Hello, world".say;

If you provide addtional arguments to method calls, you should always use
parentheses.

=head2 Perl variable types

Perl has three main variable types: scalars, arrays, and hashes.

=head3 Scalars

A scalar represents a single value:

    my $animal = "camel";
    my $answer = 42;

Scalar values can be strings, integers or floating point numbers, and Perl
will automatically convert between them as required.  There is no need to
pre-declare your variable types. But if you feel like it, you can declare
their type explictly:

    my Str $animal = "camel";
    my Int $answer = 42;
    my Num $close_to_pi = 3.141;

Scalar values can be used in various ways:

    say $animal;
    say "The animal is $animal";
    say "The square of $answer is ", $answer * $answer;

There are some "magic" scalars with names that look like punctuation or line
noise.  These special variables are used for different purposes, all of them
are documented in L<doc:perlvar>. The only one you need to know about for now
is C<$_> which is the "default variable".  It's used as the default object
when you invoke a method with the dot (C<.>) operator without specifying the
object, and it's also set implicitly by certain looping constructs.

    .print;     # prints contents of $_
    $_.print    # same thing

=head3 Arrays

An array represents a list of values:

    my @animals = "camel", "llama", "owl";
    my @numbers = 23, 42, 69;
    my @mixed   = "camel", 42, 1.23;

Arrays are zero-indexed.  Here's how you get at elements in an array:

    print @animals[0];              # prints "camel"
    print @animals[1];              # prints "llama"

You can get the index of the last element of an arry with C<end>:

    print @mixed[@mixed.end];       # last element, prints 1.23

You might be tempted to use C<@array.end + 1> to tell you how many
items there are in an array. Don't bother.  As it happens, using
@array where Perl expects to find a scalar value (in I<scalar context>) 
will give you the number of elements in the array:

    if @animals < 5 {
        ...
    }

If you want to get the number of elements explicitly, you can use C<elems>:

    print @animals.elems;       # prints "3";

To get multiple elements from an array you can use a list of indexes in the
square brackets:

    @animals[0,1];              # gives ("camel", "llama");
    @animals[0..2];             # gives ("camel", "llama", "owl");
    @animals[1..@animals.end];  # gives all except the first element

This is called an I<array slice>.

You can do various useful things to arrays:

    my @sorted = @animals.sort;  
    # or: my @sorted = sort @animals
    my @backwards = @numbers.reverse;

There are some special arrays too, such as C<@*ARGS> (the command line
arguments to your script). These are documented in L<doc:perlvar>.

There are also some shortcuts that make life easy. For example, these two
statements do the same thing:

    my @list = "foo", "bar", "baz";
    my @list = <foo bar baz>;

=head3 Hashes

A hash represents a set of key/value pairs:

    my %fruit_color = "apple", "red", "banana", "yellow";

You can use whitespace and the C«=>» operator to lay them out more nicely:

    my %fruit_color = 
        "apple"     => "red",
        "banana"    => "yellow",
    );

To get at hash elements:

    %fruit_color{"apple"};              # gives: "red"
    %fruit_color{"apple", "banana"};    # gives: "red", "yellow"

The C<{"apple"}> part is called a I<subscript>. The above can be more
conveniently written as:

    %fruit_color<apple>
    %fruit_color<apple banana>

You can get a list of all the keys and values with the C<keys> and C<values>
methods:

    my @fruits = %fruit_color.keys;
    my @colors = %fruit_color.values;

Hashes have no particular internal order, though you can sort the keys and
loop through them.

Just like special scalars and arrays, there are also special hashes.  The most
well known of these is C<%*ENV> which contains environment variables.  Read
all about it (and other special variables) in L<doc:perlvar>.

=head2 Variable scoping

Throughout the previous section all the examples have used the syntax:

    my $var = "value";

C<my> creates lexically scoped variables, that means they are scoped to the
block (i.e. a bunch of statements surrounded by curly-braces) in which they are
defined.

    my $a = "foo";
    if $some_condition {
        my $b = "bar";
        say $a;           # says "foo"
        say $b;           # says "bar"
    }
    say $a;               # says "foo"
    say $b;               # error: $b has fallen out of scope

=for comment
This probably has no place in perlintro:
Using C<no strict;> at the top of your Perl scripts allows you to use
variables without declaring them, but that is strongly discouraged. 

=head2 Conditional and looping constructs

Perl has all of the usual conditional and looping constructs.

The conditions can be any Perl expression.  See the list of operators
in the next section for information on comparison and boolean logic
operators, which are commonly used in conditional statements.

=head3 C<if>

C<if> blocks test by conditions. Unlike Perl 5, you don't need
parentheses. However, you need a space between the condition and
the opening bracket:

    if $condition {
        ...
    } elsif $other_condition {
        ...
    } else {
        ...
    }

There's also a negated version of it:

    unless $condition {
        ...
    }

However, C<unless> blocks can't have C<else> or C<elsif>s attached.

This is provided as a more readable version of C<if !$condition>.

Note that the braces are required in Perl, even if you've only got
one line in the block.  However, there is a clever way of making your
one-line conditional blocks more English like:

    # the traditional way
    if $zippy {
        print "Yow!";
    }

    # the Perlish post-condition way
    print "Yow!" if $zippy;
    print "We have no bananas" unless $bananas;

Sometimes the condition is more important than the action. You can say:

    $zippy and print "Yow!";

and get the same effect.

=head3 C<while>

    while $condition {
        ...
    }

There's also a negated version, for the same reason we have C<unless>:

    until $condition {
        ...
    }

You can also use C<while> in a post-condition:

    say "LA LA LA" while 1;          # loops forever

If you want the condition to be checked after the loop block, you can use
Pascal-like C<repeat>:

    repeat {
        ...
    } while $condition
    
    repeat {
        ...
    } until $condition

=head3 C<for> and C<loop>

For a C-style for-loop use C<loop>:
    
    loop (my $i = 0; $i < $max; $i++){
        ...
    }

This kind of loop is rarely needed since Perl provides the more friendly list
scanning C<for> loop.

    for @list -> my $i {
        say "This element is $i";
    }

    # or you can use the default $_ variable:
    for @list {
        say "This element is $_";
    }

=head3 Junctions

A junction is a single value that can be used in place of multiple values.
The C<|>, C<&>, and C<^> operators are used to create junctions. Here is an
example of an OR junction:

    my $even = 2|4|6|8;                 # $even is now all four values at once
    say "It's even!" if 4 == $even;     # true

In the code above, the condition is true because C<4> matches B<any> one of
the junction's values. As it happens, there is an English equivalent called
C<any>:

    $even = any(2,4,6,8)

The C<&> junction's English counterpart is called C<and()>, while C<^> is
C<one>. There's also a C<none()> junction which has no symbolic shorthand.
For detailed coverage of junctions, see L<doc:perlop>.

=head2 Builtin operators and functions

Perl comes with a wide selection of builtin functions.  Some of the
ones we've already seen include C<say>, C<sort> and C<reverse>.  A list
of them is given at the start of L<doc:perlfunc> and you can easily read about
any given function by using K<grok functionname>.

Here are a few of the most common used operators:

=head3 Arithmetic

=begin table :caption<Arithmetic operators>
    +       addition
    -       substraction
    *       multiplication
    /       division
=end table

=head3 Numeric comparison

=begin table :caption<Numeric comparison operators>
    ==  equality
    !=  inequality
    <   less than
    >   greater than
    <=  less than or equal
    >=  greater than or equal
=end table

=head3 String comparison

=begin table :caption<String comparison operators>
    eq  Equality
    ne  Non-equality
    lt  Less than
    gt  Greater than
    ge  Greater then or equal
    le  Less than or equal
=end table

Why do we have separate numeric and string comparisons? Because in the case
of scalars, Perl needs to know whether to sort numerically (where 99 is less
than 100) or alphabetically (where 100 comes before 99).

=head3 Boolean logic

=begin table :caption<Boolean logic operators>
    &&  and
    ||  or
    !   not
=end table

C<and>, C<or> and C<not> aren't just in the above table as descriptions of
the operators -- they're also supported as operators in their own right.
They're more readable than the C-style operators, but have different
precedence to C<&&> and friends. Check L<doc:perlop> for more details.

=head3 Miscellaneous

=begin table :caption<Miscellaneous operators>
    .   method call
    =   assignment
    ~   string concatenation
    x   string multiplication
    xx  list multiplication
    ..  range operator (creates a list of numbers)
=end table

Many operators can be combined with a C<=> as follows:

    $a += 1;        # same as $a = $a + 1
    $a -= 1;        # same as $a = $a - 1
    $a ~= "\n";     # same as $a = $a ~ "\n";

=head3 Smart matching

The smart match operator, C<~~>, can be used in a variety of situations. Here
are a few examples:

    say "Yep" if $banana ~~ @fruits;    # is the element is present in the array?
    exit if $error ~~ %fatal;           # is the key present in the hash?
    function() if $condition ~~ True    # is the condition true?
    %my_hash ~~ %their_hash             # do the hashes have the same keyes?

Smart matching is used in Perl's switch statement. It is called C<given>:

    given $foo {
        when False { say "foo is false" }
        when @list { say "foo is in the list" }
        when /bar/ { say "foo contains the substring 'bar'" }
        default { say "we're not quite sure what to do with foo" }
    }

=head2 Files and I/O

You can open a file for input or output using the C<open> function.

    my $in = open "input.txt", :r;       # open for reading
    my $out = open "output.txt", :w;     # open for writing
    my $log = open "my.log", :a;         # open for appending

You can read from an open filehandle using the C<.get> or C<.lines> methods:

    my $line = $in.get;
    my @lines = $in.lines;

=comment Maybe scrap the next paragraph, since Perl 6 is supposed to be lazy?

Reading in the whole file at one time is called slurping. It can be useful but
it may be a memory hog. Most text file processing can be done a line at a time
with Perl's looping constructs:

    while $in.get {     # assigns each line in turn to $_
        print "Just read in this line: $_";
    }

When you're done with your filehandles, you should C<close> them (though, to
be honest, Perl will clean up after you if you forget):

    $in.close;

=head2 Regular expressions

Perl's regular expression support is both broad and deep, and is the subject
of lengthy documentation in L<doc:perlrequick>, L<doc:perlretut>, and
elsewhere. However, in short:

=head3 Simple matching

    if /foo/        { ... }     # true if $_ contains "foo"
    if $a ~~ /foo/  { ... }     # true if $a contains "foo"

The C<//> matching operator is documented in L<doc:perlop>. It operators on
C<$_> by default, or can be bound to another variable using the C<~~>
smart match operator (also documented in L<doc:perlop>).

=head3 Simple substitution

    s/foo/bar/;                 # replaces "foo" with "bar" in $_
    $a ~~ s/foo/bar/;           # replaces "foo" with "bar" in $a
    $a ~~ s:global/foo/bar/     # replaces ALL INSTANCES of "foo" with "bar" in $a
    $a ~~ s:g/foo/bar/          # same thing

The C<s///> substitution operator is documented in L<doc:perlop>.

=head3 More complex regular expressions

You don't just have to match on fixed strings. In fact, you can match on just
about anything you could dream of by using more complex regular expressions.
These are documented at great length in L<doc:perlre>, but in the meantime,
here's a quick cheat sheet:

=begin table :caption<Regular expression metacharacter cheat sheet>
    C<.>                a single character
    C<\s>               a whitespace character (space, tab, newline, ...)
    C<\S>               a non-whitespace character
    C<\d>               a digit
    C<\D>               a non-digit
    C<\w>               a word character
    C<\W>               a non-word character
    C< <[aeiou]> >      matches a single character in the given set
    C< <-[aeiou]> >     matches a single character outside the given set
    C<[foo|bar|baz]>    matches any of the alternatives specified
    C<^^>               start of string
    C<$$>               end of string
=end table

Quantifiers can be used to specify how many of the previous thing you want to
match on, where "thing" means either a literal character, one of the
metacharacters listed above, or a group of characters or metacharacters in
brackets.

=begin table :caption<Regular expression quantifiers>
    C<*>        zero or more of the previous thing
    C<+>        one or more of the previous thing
    C<?>        zero or one of the previous thing
    C<** 3>     matches exactly 3 of the previous thing
    C<** 3..6>  matches between 3 and 6 of the previous thing
    C<** 3..*>  matches 3 or more of the previous thing
=end table

Some brief examples:

    /^^ \d+ /           # string starts with one or more digits
    /^^$$/              # nothing in the string (start and end are adjacent)
    /[\d\s] ** 3/       # a three digits, each followed by a whitespace character (eg "3 4 5 ")
    /[a.]+/             # matches a string in which every odd-numbered letter is a (eg "abacadaf")
    
    # This loop reads from STDIN, and prints non-blank lines:
    while $*IN.get {
        next if /^^$$/;
        print;
    }

=head3 Parentheses for capturing

Parenteses are used to capture the results of parts of the regexp match for
later use. The results end up in C<$0>, C<$2>, C<$3>, and so on.

    # a cheap and nasty way to break an email address up into parts
    if ($email =~ /(<-[@]>+) @ (.+)/) {
        say "Username is $0";
        say "Hostname is $1";
    }

=head3 Other regex features

Perl regexes also support backreferences, lookaheads, and all kinds of other
complex details. Read all about them in L<doc:perlrequick>, L<doc:perlretut>,
and L<doc:perlre>.

=head2 Writing subroutines

Writing subroutines is easy:

    sub logger ($message) {
        my $log = open "my.log", :rw;
        $log.say($message);
    }

Now we can use the subroutine just as any other built-in function:

    logger("We have a logger subroutine!");

Subroutines can also return values:

    sub square ($num) {
        my $result = $num * $num;
        return $result;
    }

Then use it like:

    $sq = square(8);

For more information on writing subroutines, see L<doc:perlsub>.

=head2 Object oriented Perl

Creating objects in Perl is simple.

    class Dog {
        has $.color;
        has $.tail;
        has @.legs;
        
        method wag () {
            # do something with $.tail
        }
    }

Object orientation is mostly beyond the scope of this tutorial however. See
L<doc:perlobj> for more.

=comment TODO: =head2 Using Perl modules

=end DESCRIPTION

=begin AUTHORS
L<Kirrily "Skud" Robert|mailto:skud@cpan.org> (original Author)

L<Moritz Lenz|mailto:moritz@faui2k3.org> and
L<Hinrik Örn Sigurðsson|mailto:hinrik.sig@gmail.com> ("translation"
to Perl 6)

Some fixup by L<David Koenig|mailto:karhu@u.washington.edu>
=end AUTHORS

=comment vim: filetype=perl6
=end pod