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. Cookbook   D. Delta   E. Exciting   F. FAQ   G. Glossary   H. Href

"1st law of language redesign: Everyone wants the colon for their particular syntax. 2nd law of language redesign: Larry gets the colon for whatever he wants."

Basics don't always mean easy, but fundamental.

Defaults

Please start your Perl 6 program with one of the following lines.

#!/usr/bin/perl6
use v6.0;
v6;

or just start with a keyword like module or class. That marks your code as Perl 6 (in case the interpreter defaults to Perl 5) and makes it possible to mix Perl 5 and 6 in one source file.

Where you had to include use strict; and use warnings; at the top of every perl5 script, it's now default in perl6. Also use utf8; is obsolete since any Perl 6 source code is always treated as UTF-8 and any unicode character can be used anywhere in the code. Even pragmas such as constants and vars are now part of the core language.

Also the functionality of many useful and famous modules like Moose (object system), Parse::RecDescent++, exception handling, List::[More]Utils, Export, English, an advanced pretty printer and much more is already built in. So you get a lot extra for a little v6;.

Statements

Unless you use blocks, a Perl program executes one statement after another in linear progression (from left to right, top down). They have to be separated by a semicolon (;), except before and after a closing curly brace, where it is optional.

$coderef = sub { fetch_data(); compute() }

Spaces and Indentation

Perl doesn't care about indentation, but it does care about whitespace as a disambiguator. For example, $foo$bar is a syntax error since that has two terms in a row without any whitespace to tell them apart. There's a new addition in perl6, the so called "unspace" operator. It is basically an instruction to the compiler's lexer that it should ignore whitespace there. In other words, the lexer doesn't consider those whitespaces at all.

my %hash = "foo" => 42, "bar" => 84; 
say %hash\  {"foo"}; # Same as saying %hash{"foo"}

my $clazz = new Camel;
$clazz\#some random comment
.drink();                # same as saying $clazz.drink();

#or even
$clazz\#`{some random multiline
comment`}.drink();      # which brings us to the next section...




...$var []

...$var []

Comments

Single Line

Like in Perl 5 and many other languages of its league, a "#" tells the compiler to ignore the rest of the line.

my $var = 'fine'; # that code is boring

Multi Line

Many lines can be commented by using "#`" followed by any pair of braces that surround the comment.

$things = #`( I wonder how many of these
I will need, hm maybe 3, or 4, better 5 ) 5; # same as $things = 5;

Documenting Comments

When adding an equal sign after the pound like #=, a comment about the following a subroutine or method is stored. This comment is accessible via the WHY introspection method of the routine object.

#= ...
sub {
    ...
}

POD

Even though POD is there to embed documentation, it can be used just for inserting comments.

=begin comment
...
=end comment


$=

all POD variables

Quoting

Quoting, like regular expression, is a sublanguage inside the main language with its own syntactical rules. It is parsed by a special grammar which can be found in the special variable $~Quote. The operator with the same name (the generic quoting operator Q) does almost nothing, just provides a mechanism to mark the beginning and end of text sequence.

Delimiter

The examples in this chapter use slashes as the delimier in almost all cases, however any non-alphanumeric character or pair of matching (bracing) characters can be used as well.

Q /.../ or Q |...| or Q *...* or Q "..." or Q[...] ...

An extended delimiter mechanism is delivered by heredocs.

Interpolation

Within these delimiters, every character will be taken literally. Any additional meaning has to be added by quoting adverbs that have to follow the Q. Most of them have a short and a long name and some of the most useful have an additional syntax that replaces them altogether with the Q operator (like single or double quotes).

:b aka :backslash # control character (implies at least :q)
:s aka :scalar # scalar variable: $name
:a aka :array # array variable: @name[...]
:h aka :hash # hash variable: %name{...}
:c aka :closure # anonymous blocks: {...}
:f aka :function # callable routines: &name(...)

For more info on those, see * scalar variable, * array variable, * hash variable, * anonymous blocks, and * callable routines.

Q :b /\t\n/; # tab and new line character
Q :s /$poem/; # content of $poem
Q :a /@primes[]/; # all number separated by single spaces
Q :a /@primes[0]/; # returns '2', the first prime
# returns literally the mail adress, you need the square
# braces to interpolate arrays
Q :a /me@primes.de/;
# all developer names (values, not keys) separated by single
# spaces, [angle brackets](basic-syntax.html#quote-words) work too
Q :h /%dev{}/;
Q :h /%dev[rakudo] %dev<niecza>/; # just 2 values
Q :h /%dev/; # literally '%dev', you need braces here too
# returns: 'There are 64 hexagrams in I Ging.', inserts the result
# of the closure
Q :c /There are {2**6} hexagrams in I Ging./;
Q :c /Perl 6 Compiler: {%dev.keys}./; # use it too for method calls
Q :h /Perl 6 Compiler: %dev.keys./; # no interpolation
# inserts report of that day, even inside Strings the correctness
# of arguments will be checked!
Q :f :a /Here it Tom with the weather: &fetch_report($day)./;
Q :f :a /fetch_report($day)/; # interpolates just $day
# literal string '&fetch_report', even if the subroutine takes
# no arguments
Q :f :a /&fetch_report/;

Single Quotes

They provide the most basic mechanism in a convenient syntax. All the following are synonyms:

Q :single /.../;
Q :q /.../;
q /.../;
'...'

We sometimes use the backslash (\) to escape other special characters or the backslash itself. These are all part of the family of characters known as /escape sequences/. For example, \\\\ translates to \\, while \\' translates to a '. You can avoid all that extra typing by using adverbs.

'Welcome in Larry\'s madhouse'
'\'\\'; # string contains: '\
q |\||; # string contains: |

Double Quotes

Double quoting combines all the previously mentioned adverbs for interpolation (also :q - implied by :b), so all the following are synonymous.

Q :s, :a, :h, :f, :c, :b /.../;
Q :double /.../;
Q :qq /.../;
qq /.../;
"..."

But further adverbs can also be added using q/.../ or qq/.../.

Quote Words

While other quote operators return a single string item, this one can return arrays because it splits the string on any whitespace (\s aka ).

Q :words /.../;
Q :w /.../; # :q implied
qw/.../; # like Perl 5's qw/.../
<...>

Q :quotewords /.../; # qw/.../ with quote protextion
Q :ww /.../; # :qq implied
<<>> # also have a unicode alias (chevron)

The second group of aliases mark a modified version, where single and double quoted strings (inside the quote) are treated as one word. This is called quote protection.

my @steps = <one "two three">;   # 3 steps to success: ["one", "\"two", "three\""]
my @steps = <<one "two three">>; # now only 2 steps: ["one", "two three"]

Please note also that :quotewords (double pointy braces) implies :double (double quotes), which means all interpolation rules apply here as well.

<$pi> eq '$pi'   # True
<<$pi>> == pi    # True (hopefully)

The same pointy braces (quote operators) are also in used when writing hash slices.

Heredocs

Heredocs are now normal quoted strings, only with a special delimiter, defined by the adverbs to and heredoc. Heredocs can be nested.

Q :to 'EOT';
...
...
EOT

To make templates in which variables and closures are evaluated, take the normal double quote and just add the adverb for the heredoc delimiter or define with other adverbs exactly what you want to have evaluated.

qq:heredoc 'EOT';
EOT

Paths

Pathstrings have their own quote operator. This way you get the warnings early if there is something incompatible with convention.

Q :path /.../;
Q :p /.../;
qp /.../;

Regex

Even being a completely different language than quoting on its own (as to be defined in $~Regex and $~P5Regex), regular expressions can be built using the general quoting operator with the right adverb.

Q :regex /.../ aka rx/.../
Q :subst /.../.../ aka s/.../.../
Q :trans /.../.../ aka tr/.../.../ aka .trans("..." => "...")

Code

The following 3 aliases quote code that will be run immediately (on runtime) and replaced with the result.

Q :exec /.../;
Q :x /.../;
qx /.../;

In Perl 5, qx/.../ aka ... did a system call and not just run eval. To get that behaviour use:

qqx/$cmd @args[]/ # do system call and insert result, alias to that is gone

However there is yet another adverb for quasi quoting, meaning: the quoted code will be parsed and compiled into a abstract syntax tree (AST - internal representation of the compiler) during compile time. Result is the compiled AST. Parsing will be done by using the grammar stored in $~Quasi. This gets important when writing macros.

Q :code /.../;

Number Literals

Unlike strings, numbers don't need quoting. But if there is a non number character in it, there will be an error. Chars of a number definition are: (0-9,.,+,-,e,E,i,_) including the radix prefixes: (0b,0o,0d,0x) and the prefix for version numbering (v). The + can also act as an operator that converts a string to numerical context, which means: take form left to right all digits and interprate as a numeric literal. This will fail if the string contains any number numeric digits.

A single underscore is allowed only between any two digits, delimiter helping readability.

3_456_789; # same as 3456789

$int = 2;
$real = 2.2;

$num = +'123';
$num = +'123foo'; # fails, 'foo' is not numeric

Radix Prefixes

Prefixes may be use to enter numbers in the most commonly used radices.

0b binary - base 2, digits 0..1
0o ocatal - base 8, digits 0..7
0d decimal - base 10, digits 0..9
0x hexadecimal - base 16, digits 0..9,a..f (case insensitive)

General Radix Form

Numbers may be entered in any radix using the general radix form, digits are represented by 0-9 and then a-z (case insensitive), so up to base 36 can be represented as a string of digits.

:10<42> # same as 0d42 or 42
:36<3z> # 3*(36**1) + 35*(36**0) = 143

Larger radices can be entered as lists of decimal numbers.

:60[12,34,56]; # 12*(60**2) + 34*(60**1) + 56*(60**0) = 45296

Scientific Notation

Scientific notation may be entered using e (case insensitive) and works the way you would expect.

$float = 60.2e23 # becomes automatically 6.02e24
$float = 6.02E-23 # capital E works too

Rational Number

To distinguish them from a division operation, you have to group them with braces.

(3/7)
(3/7).numerator
(3/7).denominator
(3/7).nude.perl

As always, .perl gives you an almost source like code formatting which results here in 3/7. Adding .nude you get (3/7), the nude source code. There are 2 different immutable value types representing both rational number. FatRat has unlimited precision and Rat has just enough to be evaled into a Real type. When you explicitly type a variable to one of them, the braces become optional.

my Rat $pi_approx = 22/7;
my FatRat $pi_approx = 2222222222/6981317007; # much more precision

Complex Number

There is also an immutable value type for complex numbers.

1+2i
my $c = 5.2+1e42i;
say $c.WHAT; # returns 'Complex', which is the classname of the value object

Version Number

v1.2.3 # okay
v1.2.* # okay, wildcard version
v1.2.3+ # okay, wildcard version
v1.2.3beta # illegal
Version('1.2.3beta') # okay

Formatting

perl

The .perl method returns a string that arranges any set of values in the same format, as it would be defined in source code (if possible). It's a built in pretty printer similar to Perl 5s Data::Dumper that works with data of any nesting depth.

@a.perl # evals to: [1, 2, 3, 4, 5]
%h.perl # evals to: {"akey" => "avalue", "bkey" => "bvalue"}

gist

The .gist method returns a summary of an object intended to be read by humans. For many types it carries more information than plain string conversion with .Str. Most notably, .gist on a type object returns the name of the type object followed by () to indicate emptiness.

Notably the say function uses .gist to convert its arguments to strings.

say Int;    # prints Int()\n

fmt

Small brother of sprinf that works as a method of a variable. If thats a pair or list it formats of course several values in the same way with same syntax as sprinf.

$result = '5.123456789';
say $result.fmt('%.2f'); # "5.12\n"
@nr = 1..5;
say @nr.fmt("+%d."); # "+1.+2.+3.+4.+5.\n"
say @nr.fmt("%d.",','); # "1.,2.,3.,4.,5.\n"
say @nr.fmt("%d %d"); # ERROR
%p6c = sorear => 'niecza', fglock => 'perlito';
say %p6c.fmt("%s!"); # "sorear!\nfglock!\n"
say %p6c.fmt("%s",','); # "sorear,fglock!\n"
say %p6c.fmt("%s:%s"); # "sorear:niecza\nfglock:perlito\n"
say %p6c.fmt("%s:%s",); # "sorear:niecza,fglock:perlito\n"
say %p6c.fmt("%s %s %s"); # ERROR

sprintf

Since Algol68 known function, that inserts into a string any number of special formatted values.

pack

xxx

Formats

Moved from core language to a module.

Date and Time

xxx


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. Cookbook   D. Delta   E. Exciting   F. FAQ   G. Glossary   H. Href