Perl 6
Perl 6 Basics Tablet: Revision 37
"Overview"[Perl 6 Tablets] - _Chapter:_ "0:History"[Perl 6 History Tablet], "1:Design"[Perl 6 Language Design Tablet], *"2:Basics"[Perl 6 Basics Tablet]*, "3:Var"[Perl 6 Variable Tablet], "4:Op"[Perl 6 Operator Tablet], "5:IO"[Perl 6 IO Tablet], "6:{}"[Perl 6 Block Tablet], "7:Sub"[Perl 6 Subroutine Tablet], "8:OOP"[Perl 6 OOP Tablet], "9:Rx"[Perl 6 Regex Tablet], "10:Meta"[Perl 6 Meta Tablet]
"Intro"[Perl 6 Intro Tablet] - _Appendices:_ "A:Index"[Perl 6 Index Tablet], "B:Tables"[Perl 6 Lookup Tablet], "C:Cook"[Perl 6 Cookbook Tablet], "D:Delta"[Perl 6 Delta Tablet], "E:Best of"[Best Of Perl 6 Tablet], "F:Links"[Perl 6 Links Tablet]

----

{toc: }

_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 doesn't mean here easy but fundamental. Which mostly translates to how to format and reformat data (numbers, strings and more).

^ Defaults

Please note that any Perl 6 source code is treated as unicode by default. Also _use strict;_ and _use warnings;_ are enabled implicitly. But the interpreter most likely also defaults to read code as Perl 5. To declare sources as Perl 6 you can write:

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

or just start with a keyword like *module* or *class*.

^ Statements

Unless you use "blocks"[Perl 6 Block Tablet], a Perl program executes one statement after another in linear progression. 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. And spaces are still in many places without meaning. However these have become fewer.

^ 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 = 'good'; # that code is boring

^^ Multi Line

I many lines has to be commented, use *#`* 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;_

^^ POD

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

> =begin comment
> ...
> =end comment

> $=

^ Quoting

Quoting is like "regular expression"{link: [Perl 6 Regex Tablet]} a sublanguage inside the main language with it's own syntactical rules. It is parsed by a special grammar as to be found in the "special variable"{link: [perl 6 lookup tablet] Special Variables} _$~Q_. The operator with the same name (the generic quoting operator) does almost nothing, just provides a mechanism to mark the beginning and end of text sequence. The examples in this chapter use almost every time slashes for that purpose, but any not alphanumerical character or pair of matching (bracing) character can be used as well.

> {{Q /.../ or Q |...| or Q *...* or Q "..." or Q[...] ...}}

An extended delimiter mechanism is delivered by "heredocs"{link: Heredocs}.

Inside of these delimiters, every character will be taken literally. Any additional meaning has to be added by "quoting adverbs"{link: [Perl 6 Lookup Tablet] Quoting Adverbs}. 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.

^^ Single Quotes

No matter which string delimiter is chosen, sometimes he has to occur as a literal character inside the string too. In that case use single quotes with the adverb _:single_ or one of the following aliases, from which {{' '}} ist maybe the best know. Its also the shortest and easy to understand, but don't allow to add other adverbs.

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

Inside single quotes the backslash (\) "quotes" meaning: he liberates the following character from his special meaning. Or to put it simple _\\_ translates (or interpolates) to _\_ and _\'_ to _'_. For anything more you need additional adverbs.

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

^^ Interpolation

The following adverbs with their short or long version allow a very fine grained definition what to interpolate. The three dots mark here optional content, mostly parameter.

> :b aka :backslash # "control character"{link: [Perl 6 Lookup Tablet] Control Chars} (implies at least :q)
> :s aka :scalar # "scalar variable"{link: [Perl 6 Variable Tablet] Scalar}: $name
> :a aka :array # "array variable"{link: [Perl 6 Variable Tablet] Array}: @name[...]
> :h aka :hash # "hash variable"{link: [Perl 6 Variable Tablet] Hash}: %name{...}
> :c aka :closure # "anonymous blocks"{link: [Perl 6 Block Tablet] Block}: {...}
> :f aka :function # "callable routines"{link: [Perl 6 Variable Tablet] Callable}: &name(...)

> 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
> Q :a {{/me@primes.de/; # returns literally the mail adress, you need the square braces to interpolate arrays}}
> Q :h /%dev{}/; # all developer names (values, not keys) separated by single spaces, "angle brackets"{link: Quote Words} work too
> Q :h /%dev[rakudo] %dev<niecza>/; # just 2 values
> Q :h /%dev/; # literally '%dev', you need braces here too
> Q :c /There are {2**6} hexagrams in I Ging./; # returns: 'There are 64 hexagrams in I Ging.', inserts the result of the closure
> Q :c /Perl 6 Compiler: {%dev.keys}./; # use it too for method calls
> Q :h /Perl 6 Compiler: %dev.keys./; # no interpolation
> Q :f :a /Here it Tom with the weather: &fetch_report($day)./; # inserts report of that day, even inside Strings the correctness of arguments will be checked!
> Q :f :a /fetch_report($day)/; # interpolates just $day
> Q :f :a /&fetch_report/; # literal string '&fetch_report', even if the subroutine takes no arguments

^^ Double Quotes

Double quoting combines all the previous mentioned adverbs for interpolation (also *:q* - implied by *:b*), thatswhy 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"{link: [Perl 6 Variable Tablet]Array} because he splits the string on any whitespace (\s aka <ws>).

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

> Q :quotewords /.../; # qw/.../ with quote protextion
> Q :ww /.../; # :qq implied
> <<>> # have also 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. Thats 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"{link: Interpolation} apply here also.

> <$pi> eq '$pi'
> <<$pi>> eq "$pi" # == '3.14159...'

The same pointy braces (quote operators) are also in used, when writing "hash slices"{link: [Perl 6 Variable Tablet]Hash Slices}.

^^ 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 what exactly 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 then quoting on its own (as to be defined in _$~Regex_ and _$~P5Regex_), "regular expressions"[Perl 6 Regex Tablet] 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"{link: [Perl 6 Meta Tablet] Macros}.

> Q :code /.../;

^ Number Literals

Unlike strings, numbers don't need "quoting"{link: 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"{link: Radix Prefixes}: (0b,0o,0d,0x) and the prefix for "version numbering"{link: Version Number} (v). The + and can act also as operator that convert into the numerical context, which still means: take from left to right all digits and stop with the first none number character.

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

> 3_456_789; # same as 3456789

> $int = 2;
> $real = 2.2;

^^ Radix Prefixes

> 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

> :10<42> # same as 0d42 or 42

^^ Scientific Notation

> $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 groupe them with braces.

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

As always, ".perl"{link: 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"{link: [perl 6 lookup tablet] immutable 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"{link: [perl 6 variable tablet] data types} to one o them, the braces become optional.

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

^^ Complex Number

have also there own "immutable value type"{link: [perl 6 lookup tablet] immutable types}.

> 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 almost the same format, as the would be defined it source code. It's a built in Data::Dumper (pretty printer).

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

This works with data of any nesting depth.

^^ fmt

Small brother of sprinf that works as a method of one value.

^^ sprintf

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

^^ pack

^^ Formats

moved from core language to a module.

^^ Date and Time

----

"Overview"[Perl 6 Tablets] - _Chapter:_ "0:History"[Perl 6 History Tablet], "1:Design"[Perl 6 Language Design Tablet], *"2:Basics"[Perl 6 Basics Tablet]*, "3:Var"[Perl 6 Variable Tablet], "4:Op"[Perl 6 Operator Tablet], "5:IO"[Perl 6 IO Tablet], "6:{}"[Perl 6 Block Tablet], "7:Sub"[Perl 6 Subroutine Tablet], "8:OOP"[Perl 6 OOP Tablet], "9:Rx"[Perl 6 Regex Tablet], "10:Meta"[Perl 6 Meta Tablet]
"Intro"[Perl 6 Intro Tablet] - _Appendices:_ "A:Index"[Perl 6 Index Tablet], "B:Tables"[Perl 6 Lookup Tablet], "C:Cook"[Perl 6 Cookbook Tablet], "D:Delta"[Perl 6 Delta Tablet], "E:Best of"[Best Of Perl 6 Tablet], "F:Links"[Perl 6 Links Tablet]

----


Upload Files

Click "Browse" to find the file you want to upload. When you click "Upload file" your file will be uploaded and added to the list of attachments for this page.

Maximum file size: 50MB

 
 
 
File Name Author Date Uploaded Size

Save Page As

Enter a meaningful and distinctive title for your page.

Page Title:

Tip: You'll be able to find this page later by using the title you choose.

Page Already Exists

There is already a page named XXX. Would you like to:

Save with a different name:

Save the page with the name "XXX"

Append your text to the bottom of the existing page named: "XXX"

Upload Files

Click "Browse" to find the file you want to upload. When you click "Add file" this file will be added to the list of attachments for this page, and uploaded when you save the page.

 
 
 
Add Tags

Enter a tag and click "Add tag". The tag will be saved when you save the page.

Tag: 

Suggestions: