Perl 6
Encyclopedia
Perl 6 is a major revision to the Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

 programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....

. It is still in development, as a specification
Programming language specification
In computing, a programming language specification is an artifact that defines a programming language so that users and implementors can agree on what programs in that language mean....

 from which several interpreter
Interpreter (computing)
In computer science, an interpreter normally means a computer program that executes, i.e. performs, instructions written in a programming language...

 and compiler
Compiler
A compiler is a computer program that transforms source code written in a programming language into another computer language...

 implementations are being written. It is introducing elements of many modern and historical languages. Perl 6 is intended to have many implementations
Programming language implementation
A programming language implementation is a system for executing programs written in a programming language.There are two general approaches to programming language implementation:...

. Backward compatibility
Backward compatibility
In the context of telecommunications and computing, a device or technology is said to be backward or downward compatible if it can work with input generated by an older device...

 with earlier versions of Perl is not a goal, though a compatibility mode
Compatibility mode
A compatibility mode is a software mechanism in which a computer's operating system emulates an older processor, operating system, and/or hardware platform in order to allow obsolete software to remain compatible with the computer's newer hardware or software....

 is part of the specification. The design process for Perl 6 began in 2000.

Development on Pugs
Pugs
Pugs is a compiler and interpreter for the Perl 6 programming language, started on February 1, 2005 by Audrey Tang.Pugs development is now placed on hiatus, with most Perl 6 implementation efforts now taking place on Rakudo; however, its source repository is still used for storing the official Perl...

, the first high-traction implementation, began in 2005, and today there are multiple Perl 6 implementation projects. Rakudo Perl
Rakudo Perl
Rakudo Perl is a compiler that implements the Perl 6 specification and runs on the Parrot virtual machine. Rakudo Perl is currently in development....

 is based on Parrot
Parrot virtual machine
Parrot is a register-based process virtual machine designed to run dynamic languages efficiently. It uses just-in-time compilation for speed to reduce the interpretation overhead. It is currently possible to compile Parrot assembly language and PIR to Parrot bytecode and execute it...

 and NQP, and releases a new version every month; In July 2010, the project released the first Rakudo Star distribution, a useful and usable collection of a Perl 6 implementation and related materials. Larry Wall
Larry Wall
Larry Wall is a programmer and author, most widely known for his creation of the Perl programming language in 1987.-Education:Wall earned his bachelor's degree from Seattle Pacific University in 1976....

 maintains a reference grammar known as STD.pm, written in Perl 6 and bootstrapped
Bootstrapping (compilers)
In computer science, bootstrapping is the process of writing a compiler in the target programming language which it is intended to compile...

 with Perl 5.

The Perl 6 project has rarely promised official release dates for any implementation, although various contributors have given estimates over the years. In early 2007 Jesse Vincent, the Perl 6 Project Manager said, "The Perl 6 project has no schedule ... one doesn't want to rush a largely volunteer effort to design and implement a worthy successor to Perl 5." However, the first major distribution release using the Rakudo implementation (named "Rakudo *" or "Rakudo Star") occurred in July, 2010.

History

The Perl 6 design process was first announced on July 19, 2000, on the fourth day of that year's Perl Conference
O'Reilly Open Source Convention
The O'Reilly Open Source Convention is an annual convention for the discussion of free and open source software. It is organized by the publisher O'Reilly Media and is held each summer in the United States.-Notable events:...

, by Larry Wall
Larry Wall
Larry Wall is a programmer and author, most widely known for his creation of the Perl programming language in 1987.-Education:Wall earned his bachelor's degree from Seattle Pacific University in 1976....

 in his State of the Onion 2000 talk. At that time, the primary goals were to remove "historical warts" from the language; "easy things should stay easy, hard things should get easier, and impossible things should get hard;" a general cleanup of the internal design and APIs
Application programming interface
An application programming interface is a source code based specification intended to be used as an interface by software components to communicate with each other...

. The process began with a series of requests for comments
Request for Comments
In computer network engineering, a Request for Comments is a memorandum published by the Internet Engineering Task Force describing methods, behaviors, research, or innovations applicable to the working of the Internet and Internet-connected systems.Through the Internet Society, engineers and...

 or "RFCs". This process was open to all contributors, and left no aspect of the language closed to change.

Once the RFC process was complete, Wall reviewed and classified each request (361 were received). He then began the process of writing several "Apocalypse
Apocalypse
An Apocalypse is a disclosure of something hidden from the majority of mankind in an era dominated by falsehood and misconception, i.e. the veil to be lifted. The Apocalypse of John is the Book of Revelation, the last book of the New Testament...

s", a term which means "revealing." While the original goal was to write one Apocalypse for each chapter of Programming Perl, it became obvious that, as each Apocalypse was written, previous Apocalypses were being invalidated by later changes. For this reason, a set of Synopses were published, each one relating the contents of an Apocalypse, but with any subsequent changes reflected in updates. Today, Perl 6 specification continues almost entirely within the Synopses.

There are also a series of Exegeses written by Damian Conway
Damian Conway
Damian Conway is a prominent member of the Perl community, a proponent of object-oriented programming, and the author of several books. He is also an Adjunct Associate Professor in the Faculty of Information Technology at Monash University....

 that explain the content of each Apocalypse in terms of practical usage. Each Exegesis consists of code examples along with discussion of the usage and implications of the examples.

There are three primary methods of communication used in the development of Perl 6 today. The first is the [irc://irc.freenode.net/#perl6 #perl6] IRC channel
Internet Relay Chat
Internet Relay Chat is a protocol for real-time Internet text messaging or synchronous conferencing. It is mainly designed for group communication in discussion forums, called channels, but also allows one-to-one communication via private message as well as chat and data transfer, including file...

 on freenode
Freenode
freenode, formerly known as Open Projects Network, is an IRC network used to discuss peer-directed projects. Their servers are all accessible from the domain name [irc://chat.freenode.net chat.freenode.net], which load balances connections by using the actual servers in rotation...

. The second is a set of mailing list
Mailing list
A mailing list is a collection of names and addresses used by an individual or an organization to send material to multiple recipients. The term is often extended to include the people subscribed to such a list, so the group of subscribers is referred to as "the mailing list", or simply "the...

s on The Perl Foundation
The Perl Foundation
The Perl Foundation is dedicated to the advancement of the Perl programming language through open discussion, collaboration, design, and code...

's servers at perl.org. The third is the Subversion source code repository used by the pugs
Pugs
Pugs is a compiler and interpreter for the Perl 6 programming language, started on February 1, 2005 by Audrey Tang.Pugs development is now placed on hiatus, with most Perl 6 implementation efforts now taking place on Rakudo; however, its source repository is still used for storing the official Perl...

 team. Pugs is an early implementation of Perl 6; see the Implementations section for more detail.

Goals

The break in compatibility was mandated from the start of the project, and immediately allowed some of the changes that Larry Wall had suggested in his initial speech. "Historical warts" such as the confusion surrounding sigil
Sigil (computer programming)
In computer programming, a sigil is a symbol attached to a variable name, showing the variable's datatype or scope. In 1999 Philip Gwyn adopted the term "to mean the funny character at the front of a Perl variable".- Historical context:...

 usage for containers; the ambiguity between the select functions; the syntactic impact of bareword filehandles; and many other problems that Perl programmers had discussed fixing for years were some of the first issues addressed.

Over the years, Perl 6 has undergone several alterations in its direction. The introduction of concepts from Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

 and Ruby were early influences , but as the Pugs interpreter was written in the Haskell programming language
Haskell (programming language)
Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...

, many functional programming
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...

 influences were absorbed by the Perl 6 design team.

Implementations

, multiple Perl 6 implementations are under development, but none are considered "complete". As noted in the history section the language design itself is still subject to change. No implementation will be designated as the official Perl 6 implementation; rather, "Perl 6 is anything that passes the official test suite."

Rakudo Perl
Rakudo Perl
Rakudo Perl is a compiler that implements the Perl 6 specification and runs on the Parrot virtual machine. Rakudo Perl is currently in development....

 is a Perl 6 implementation targeting the Parrot virtual machine
Parrot virtual machine
Parrot is a register-based process virtual machine designed to run dynamic languages efficiently. It uses just-in-time compilation for speed to reduce the interpretation overhead. It is currently possible to compile Parrot assembly language and PIR to Parrot bytecode and execute it...

. Parrot is a virtual machine
Virtual machine
A virtual machine is a "completely isolated guest operating system installation within a normal host operating system". Modern virtual machines are implemented with either software emulation or hardware virtualization or both together.-VM Definitions:A virtual machine is a software...

 designed for dynamic programming language
Dynamic programming language
Dynamic programming language is a term used broadly in computer science to describe a class of high-level programming languages that execute at runtime many common behaviors that other languages might perform during compilation, if at all...

s, primarily for Perl 6. It provides several powerful compiler tools, many of which take inspiration from Perl 6. In particular, the Parser Grammar Engine, or PGE, provides an implementation of Perl 6 grammars. As well, the language used for building compilers is itself Not Quite Perl 6, or NQP. The Rakudo implementation of Perl 6 on Parrot takes advantage of PGE and NQP. Some portions of Rakudo are written in Perl 6 itself, though this is not a self-hosting implementation, nor are there concrete plans at this point to make Rakudo a bootstrapping compiler.

Pugs
Pugs
Pugs is a compiler and interpreter for the Perl 6 programming language, started on February 1, 2005 by Audrey Tang.Pugs development is now placed on hiatus, with most Perl 6 implementation efforts now taking place on Rakudo; however, its source repository is still used for storing the official Perl...

 is an implementation of Perl 6 written in Haskell
Haskell (programming language)
Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...

. Pugs can execute Perl 6 code directly, and has also compiled Perl 6 to JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

, Perl 5
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

 and Parrot
Parrot virtual machine
Parrot is a register-based process virtual machine designed to run dynamic languages efficiently. It uses just-in-time compilation for speed to reduce the interpretation overhead. It is currently possible to compile Parrot assembly language and PIR to Parrot bytecode and execute it...

 bytecode
Bytecode
Bytecode, also known as p-code , is a term which has been used to denote various forms of instruction sets designed for efficient execution by a software interpreter as well as being suitable for further compilation into machine code...

. Pugs used to be the most advanced implementation of Perl 6, but since mid 2007 it is mostly dormant (only actualisation to new GHC versions have been done since that time).

v6.pm
V6 (Perl)
v6 is a module for the Perl programming language which runs under Perl version 5, and transforms Perl 6 code into Perl 5 code on the fly. To quote the release notes:-Components:...

is a pure Perl 5 implementation of Perl 6, making liberal use of existing CPAN
CPAN
CPAN, the Comprehensive Perl Archive Network, is an archive of nearly 100,000 modules of software written in Perl, as well as documentation for it. It has a presence on the World Wide Web at and is mirrored worldwide at more than 200 locations...

 modules, such as Moose
Moose (Perl)
Moose is an extension of the Perl 5 object system. It brings modern object-oriented language features to Perl 5, making object-oriented programming more consistent and less tedious.-Features:...

 and Pugs::Compiler::Rule. It aims to make the existing perl runtime a first-class virtual machine for both Perl 5 and Perl 6.

In 2007, v6-MiniPerl6 ("mp6") and its reimplementation, v6-KindaPerl6 ("kp6") were written as a means to bootstrap the Perl-6.0.0 STD, using Perl 5. The STD is a full grammar for Perl 6, and is written in Perl 6. In theory, anything capable of parsing the STD and generating executable code is a suitable bootstrapping system for Perl 6. kp6 is currently compiled by mp6 and can work with multiple backends. mp6 and kp6 are not full Perl 6 implementations, and are designed only to implement the minimum featureset required to bootstrap a full Perl 6 compiler.

Sprixel is being written as a means to bootstrap the Perl-6.0.0 STD on the CLR, using another new intermediary language/environment named Perlesque, which intends to implement closely the strongly typed subset of Perl 6. Its source code repository is located on Google Code as CSMeta. CSMeta/Perlesque/Sprixel evolved from the JSMeta/Sprixel project in JavaScript, located on Google Code and in the pugscode repository.

Yapsi is a Perl 6 compiler and runtime written in Perl 6 itself. As a result, it requires an existing Perl 6 interpreter, such as one of the Rakudo Star releases, in order to run.

Module system

The Perl 6 specification requests that modules are identified by name, version and authority. It is possible to load only a specific version of a module, or even two modules of the same name that differ in version or authority. As a convenience, aliasing to a short name is provided.

CPAN
CPAN
CPAN, the Comprehensive Perl Archive Network, is an archive of nearly 100,000 modules of software written in Perl, as well as documentation for it. It has a presence on the World Wide Web at and is mirrored worldwide at more than 200 locations...

, the Perl 5 module distribution system, does not yet handle Perl 6 modules. Instead a prototype module system is in use.

Major changes from Perl 5

Perl 5 and Perl 6 differ fundamentally, though in general the intent has been to "keep Perl 6 Perl". Most of the changes are intended to normalize the language, to make it easier for learning and expert programmers alike to understand, and to make "easy things easier and hard things more possible".

A specification

A major, but non-technical difference between Perl 5 and Perl 6 is that Perl 6 began as a specification. This means that Perl 6 can be re-implemented if needed, and it also means that programmers don't have to read the source code for the ultimate authority on any given feature. Perl 5's documentation is regarded as excellent, even outside of the Perl community where even mixed reviews typically note its maturity and breadth. However, the documentation is not considered authoritative and only describes the behavior of the actual Perl 5 interpreter informally. Any discrepancies found between the documentation and the implementation may lead to either being changed to reflect the other, a dynamic which drives the continuing development and refinement of the Perl 5 releases.

A type system

In Perl 6, the dynamic type system of Perl 5 has been augmented by the addition of static types. For example:

my Int $i = 0;
my Num $n = 3.142;
my Str $s = "Hello, world";

However, static typing remains optional, so programmers can do most things without any explicit typing at all:

my $i = "25" + 10; # $i is 35


Perl 6 offers a hybrid typing system whereby the programmer may choose to use Static Typing, Dynamic Typing or mix the two.

Formal subroutine parameter lists

Perl 5 defines subroutines without formal parameter
Parameter (computer science)
In computer programming, a parameter is a special kind of variable, used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. These pieces of data are called arguments...

 lists at all (though simple parameter counting and some very loose type checking can be done using Perl 5's "prototypes"). Subroutine arguments passed in are aliased into the elements of the array @_. If the elements of @_ are modified, the changes are reflected in the original data.

Perl 6 introduces true formal parameters to the language. In Perl 6, a subroutine declaration looks like this:

sub do_something(Str $thing, Int $other) {
. . .
}

As in Perl 5, the formal parameters (i.e., the variables in the parameter list) are aliases to the actual parameters (the values passed in), but by default, the aliases are constant
Constant (programming)
In computer programming, a constant is an identifier whose associated value cannot typically be altered by the program during its execution...

 so they cannot be modified. They may be declared explicitly as read-write aliases for the original value or as copies using the is rw or is copy directives should the programmer require them to be modified locally.

Parameter passing modes

Perl 6 provides three basic modes of parameter passing:
  • Positional
  • Named
  • Slurpy

Positional parameters are the typical ordered list of parameters that most programming languages use. All parameters may also be passed by using their name in an unordered way. A named-only parameter can only be passed by specifying its name (that is, it never captures a positional argument), and are indicated with a leading : character. Slurpy parameters (indicated by an * before the parameter name) are Perl 6's tool for creating variadic function
Variadic function
In computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments. Support for variadic functions differs widely among programming languages....

s. A slurpy hash will capture remaining passed-by-name parameters, whereas a slurpy array will capture remaining passed-by-position parameters.

Here is an example of the use of all three parameter-passing modes:


sub somefunction($a, $b, :$c, :$d, *@e) {
. . .
}

somefunction(1, 2, :d<3>, 4, 5, 6); # $a=1, $b=2, $d=3, @e=(4,5,6)
somefunction(:b<2>, :a<1>); # $a=1, $b=2


Positional parameters, such as those used above are always required, unless followed by ? to indicate that they are optional. Named parameters are optional by default, but may be marked as required by adding ! after the variable name. Slurpy parameters are always optional.

Blocks and closures

Parameters can also be passed to arbitrary blocks, which act as closures
Closure (computer science)
In computer science, a closure is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its typical scope. Such a function is said to be "closed over" its free variables...

. This is how, for example, for and while loop iterators are named. In the following example, a list is traversed, 3 elements at a time, and passed to the loop's block as the variables, $a, $b, $c.

for @list -> $a, $b, $c {
. . .
}

This is generally referred to as a "pointy sub" or "pointy block", and the arrow behaves almost exactly like the sub keyword, introducing an anonymous closure (or anonymous subroutine in Perl 5 terminology).

Sigil invariance

In Perl 5, sigils
Sigil (computer programming)
In computer programming, a sigil is a symbol attached to a variable name, showing the variable's datatype or scope. In 1999 Philip Gwyn adopted the term "to mean the funny character at the front of a Perl variable".- Historical context:...

 — the punctuation characters that precede a variable name — change depending on how the variable is used:
# Perl 5 code
my @array = ('a', 'b', 'c');
my $element = $array[1]; # $element equals 'b'
my $element = @array[1]; # in 5.10, $element equals 'b', with optional warning
my @extract = @array[1, 2]; # @extract equals ('b', 'c')

In Perl 6, sigils are invariant, which mean they do not change based on whether it is the array or the array element that is needed:
# Perl 6 code
my @array = ('a', 'b', 'c');
my $element = @array[1]; # $element equals 'b'
my @extract = @array[1]; # @extract equals ('b')
my @extract = @array[1, 2]; # @extract equals ('b', 'c')

The variance in Perl 5 was inspired by number agreement in English and many other natural languages:

"This apple." # CORRECT
"These apples." # CORRECT
"This third apple." # CORRECT
"These third apple." # WRONG

However, this conceptual mapping breaks down when references come into play, since they may refer to containers even though they are scalars. Thus, dealing with nested data structures may require an expression of both singular and plural form in a single term:
# Perl 5 code: retrieve a list from the leaf of a hash containing hashes that contain arrays
my @trans_verbs = @{ $dictionary{ 'verb' }{ 'transitive' } };

This complexity has no equivalent either in common use of natural language or in other programming languages, and it causes high cognitive load
Cognitive load
The term cognitive load is used in cognitive psychology to illustrate the load related to the executive control of working memory . Theories contend that during complex learning activities the amount of information and interactions that must be processed simultaneously can either under-load, or...

 when writing code to manipulate complex data structures. Compare this with Perl 6:

# Perl 6 code: retrieve a list from the leaf of a hash containing hashes that contain arrays
my @trans_verbs = %dictionary{ 'verb' }{ 'transitive' };

Object-oriented programming

Perl 5 supports object-oriented programming
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...

 via a mechanism known as blessing. Any reference
Reference (computer science)
In computer science, a reference is a value that enables a program to indirectly access a particular data item, such as a variable or a record, in the computer's memory or in some other storage device. The reference is said to refer to the data item, and accessing those data is called...

 can be blessed into being an object of a particular class. A blessed object can have method
Method (computer science)
In object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...

s invoked on it using the "arrow syntax" which will cause Perl to locate or "dispatch" an appropriate subroutine
Subroutine
In computer science, a subroutine is a portion of code within a larger program that performs a specific task and is relatively independent of the remaining code....

 by name, and call it with the blessed variable as its first argument.

While extremely powerful—virtually any other computer language's object model
Object model
In computing, object model has two related but distinct meanings:# The properties of objects in general in a specific computer programming language, technology, notation or methodology that uses them. For example, the Java objects model, the COM object model, or the object model of OMT...

 can be simulated using this simple facility—it makes the most common case of object orientation, a struct
Struct
struct is a computer science term for a record that is used to store more than one value.struct is used in the following programming languages:* struct * struct vs. C++ classes...

-like object with some associated code, unnecessarily difficult. In addition, because Perl can make no assumptions about the object model in use, method invocation can not be optimized very well.

In the spirit of making the "easy things easy and hard things possible", Perl 6 retains the blessing model and supplies a more robust object model for the common cases. For example, a class to encapsulate a Cartesian
Cartesian coordinate system
A Cartesian coordinate system specifies each point uniquely in a plane by a pair of numerical coordinates, which are the signed distances from the point to two fixed perpendicular directed lines, measured in the same unit of length...

 point
Point (geometry)
In geometry, topology and related branches of mathematics a spatial point is a primitive notion upon which other concepts may be defined. In geometry, points are zero-dimensional; i.e., they do not have volume, area, length, or any other higher-dimensional analogue. In branches of mathematics...

 could be defined and used this way:

class Point is rw {
has $.x;
has $.y;
}

my $point = Point.new( x => 1.2, y => -3.7 );

# Now change x (note method "x" used as lvalue):
$point.x = 2;
say "Point is at X location: ", $point.x;

The dot replaces the arrow in a nod to the many other languages (e.g. Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

, Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

, etc.) that have coalesced around dot as the syntax for method invocation.

In the terminology of Perl 6, $.x is called an "attribute". Some languages call these fields or members. The method used to access an attribute is called an "accessor". Auto-accessors are methods that are created automatically, as the method x is in the example above. These accessor functions return the value of the attribute. When a class or individual attribute is declared with the is rw modifier (short for "read/write"), the auto-accessor can be passed a new value to set the attribute to, or it can be directly assigned to as an lvalue (as in the example). Auto-accessors can be replaced by user-defined methods, should the programmer desire a richer interface to an attribute. Attributes can only be accessed directly from within a class definition. All other access must go through the accessor methods.

The Perl 6 object system has inspired the Moose
Moose (Perl)
Moose is an extension of the Perl 5 object system. It brings modern object-oriented language features to Perl 5, making object-oriented programming more consistent and less tedious.-Features:...

 framework that introduces many of Perl 6's OOP features to Perl 5
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

.

Roles

Roles in Perl 6 take on the function of interfaces in Java
Interface (Java)
An interface in the Java programming language is an abstract type that is used to specify an interface that classes must implement. Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations...

, mixin
Mixin
In object-oriented programming languages, a mixin is a class that provides a certain functionality to be inherited or just reused by a subclass, while not meant for instantiation , Mixins are synonymous functionally with abstract base classes...

s
in Ruby, and traits in the Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...

 variant Squeak
Squeak
The Squeak programming language is a Smalltalk implementation. It is object-oriented, class-based and reflective.It was derived directly from Smalltalk-80 by a group at Apple Computer that included some of the original Smalltalk-80 developers...

. These are much like classes, but are entirely abstract
Abstraction (computer science)
In computer science, abstraction is the process by which data and programs are defined with a representation similar to its pictorial meaning as rooted in the more complex realm of human life and language with their higher need of summarization and categorization , while hiding away the...

. These are used to perform composition when used with classes rather than adding to their inheritance
Inheritance (computer science)
In object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...

 chain. Roles define nominal types; they provide semantic names for collections of behavior and state. The fundamental difference between a role and a class is that classes are instantiable; roles are not.

Essentially, a role is a bundle of (possibly abstract) methods and attributes that can be added to a class without using inheritance. A role can even be added to an individual object; in this case, Perl 6 will create an anonymous subclass, add the role to the subclass, and change the object's class to the anonymous subclass.

For example, a Dog
Dog
The domestic dog is a domesticated form of the gray wolf, a member of the Canidae family of the order Carnivora. The term is used for both feral and pet varieties. The dog may have been the first animal to be domesticated, and has been the most widely kept working, hunting, and companion animal in...

 is a Mammal
Mammal
Mammals are members of a class of air-breathing vertebrate animals characterised by the possession of endothermy, hair, three middle ear bones, and mammary glands functional in mothers with young...

. Dogs inherit certain characteristics from Mammals, such as mammary gland
Mammary gland
A mammary gland is an organ in mammals that produces milk to feed young offspring. Mammals get their name from the word "mammary". In ruminants such as cows, goats, and deer, the mammary glands are contained in their udders...

s and (through Mammal's parent, Vertebrate
Vertebrate
Vertebrates are animals that are members of the subphylum Vertebrata . Vertebrates are the largest group of chordates, with currently about 58,000 species described. Vertebrates include the jawless fishes, bony fishes, sharks and rays, amphibians, reptiles, mammals, and birds...

) a backbone
Backbone
Backbone may refer to:* Vertebral column, of a vertebrate organism* Backbone chain, in polymer chemistry, the framework of the molecule* Backbone Entertainment, a video game development company* Backbone network, the top level of a hierarchical network...

. Dogs may have one of several distinct types of behavior; for example, a Dog may be a Pet
Pet
A pet is a household animal kept for companionship and a person's enjoyment, as opposed to wild animals or to livestock, laboratory animals, working animals or sport animals, which are kept for economic or productive reasons. The most popular pets are noted for their loyal or playful...

, a Stray
Feral
A feral organism is one that has changed from being domesticated to being wild or untamed. In the case of plants it is a movement from cultivated to uncultivated or controlled to volunteer. The introduction of feral animals or plants to their non-native regions, like any introduced species, may...

, or a Guide
Guide dog
Guide dogs are assistance dogs trained to lead blind and visually impaired people around obstacles.Although the dogs can be trained to navigate various obstacles, they are partially color blind and are not capable of interpreting street signs...

 for the blind. However, these are simply sets of additional behaviors that can be added to a Dog; a Cat
Cat
The cat , also known as the domestic cat or housecat to distinguish it from other felids and felines, is a small, usually furry, domesticated, carnivorous mammal that is valued by humans for its companionship and for its ability to hunt vermin and household pests...

 can equally be a Pet or Stray, for example. Hence, Dog and Mammal are classes, while Pet, Stray, and Guide are roles.

class Mammal is Vertebrate {
. . .
}
class Dog is Mammal {
. . .
}
role Pet {
. . .
}
role Stray {
. . .
}
role Guide {
. . .
}

Roles are added to a class or object with the does keyword, as opposed to inheritance's is. The keywords reflect the differing meanings of the two features: role composition gives a class the behavior of the role, but doesn't indicate that it is truly the same thing as the role.

class GuideDog is Dog does Guide {
. . .
} # Subclass composes role

my $dog = new Dog;
$dog does Guide; # Individual object composes role

Although roles are distinct from classes, both are types, so a role can appear in a variable declaration where one would normally put a class. For example, a Blind role for a Human could include an attribute of type Guide; this attribute could contain a Guide Dog, a Guide Horse
Guide horse
A guide horse is an experimental mobility option for blind people who do not wish to or cannot use a guide dog. They are provided by The Guide Horse Foundation, founded in 1999 to provide miniature horses as assistance animals to blind users living in rural environments.There are several perceived...

, a Guide Human, or even a Guide Machine.

class Human {
has Dog $dog; # Can contain any kind of Dog, whether it does the
... # Guide role or not
}
role Blind {
has Guide $guide; # Can contain any object that does the Guide role,
... # whether it is a Dog or something else
}

Regular expressions

Perl's regular expression
Regular expression
In computing, a regular expression provides a concise and flexible means for "matching" strings of text, such as particular characters, words, or patterns of characters. Abbreviations for "regular expression" include "regex" and "regexp"...

 and string-processing support has always been one of its defining features. Since Perl's pattern-matching constructs have exceeded the capabilities of regular language
Regular language
In theoretical computer science and formal language theory, a regular language is a formal language that can be expressed using regular expression....

 expressions for some time, Perl 6 documentation will exclusively refer to them as regexes, distancing the term from the formal definition.

Perl 6 provides a superset of Perl 5 features with respect to regexes, folding them into a larger framework called "rules
Perl 6 rules
Perl 6 rules are the regular expression, pattern matching and general-purpose parsing facility of Perl 6, and are a core part of the language. Since Perl's pattern-matching constructs have exceeded the capabilities of formal regular expressions for some time, Perl 6 documentation refers to them...

" which provide the capabilities of context-sensitive
Context-sensitive
Context-sensitive is an adjective meaning "depending on context" or "depending on circumstances". It may refer to:* Context-sensitive grammar* Context-sensitive language* Context-sensitive help* Context sensitive user interface in computing...

 parsing
Parsing
In computer science and linguistics, parsing, or, more formally, syntactic analysis, is the process of analyzing a text, made of a sequence of tokens , to determine its grammatical structure with respect to a given formal grammar...

 formalisms (such as the syntactic predicate
Syntactic predicate
A syntactic predicate specifies the syntactic validity of applying a production in a formal grammar and is analogous to a semantic predicate that specifies the semantic validity of applying a production. It is a simple and effective means of dramatically improving the recognition strength of an LL...

s of parsing expression grammar
Parsing expression grammar
A parsing expression grammar, or PEG, is a type of analytic formal grammar, i.e. it describes a formal language in terms of a set of rules for recognizing strings in the language...

s and ANTLR
ANTLR
In computer-based language recognition, ANTLR , or ANother Tool for Language Recognition, is a parser generator that uses LL parsing. ANTLR is the successor to the Purdue Compiler Construction Tool Set , first developed in 1989, and is under active development...

), as well as acting as a closure
Closure (computer science)
In computer science, a closure is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its typical scope. Such a function is said to be "closed over" its free variables...

 with respect to their lexical scope
Scope (programming)
In computer programming, scope is an enclosing context where values and expressions are associated. Various programming languages have various types of scopes. The type of scope determines what kind of entities it can contain and how it affects them—or semantics...

. Rules are introduced with the rule keyword which has a usage quite similar to subroutine definition. Anonymous rules can also be introduced with the regex (or rx) keyword, or they can simply be used inline as regexps were in Perl 5 via the m (matching) or s (substitute) operators.

In Apocalypse 5, Larry Wall enumerated 20 problems with "current regex culture". Among these were that Perl's regexes were "too compact and 'cute'", had "too much reliance on too few metacharacters", "little support for named captures", "little support for grammars", and "poor integration with 'real' language".

Syntactic simplification

Some Perl 5 constructs have been changed in Perl 6, optimized for different syntactic cues for the most common cases. For example, the parentheses (round bracket
Bracket
Brackets are tall punctuation marks used in matched pairs within text, to set apart or interject other text. In the United States, "bracket" usually refers specifically to the "square" or "box" type.-List of types:...

s) required in control flow
Control flow
In computer science, control flow refers to the order in which the individual statements, instructions, or function calls of an imperative or a declarative program are executed or evaluated....

 constructs in Perl 5 are now optional:

if is_true {
for @array {
...
}
}

Also, the , (comma) operator is now a list constructor, so enclosing parentheses are no longer required around lists. The code

@array = 1, 2, 3, 4;

now makes @array an array with exactly the elements '1', '2', '3', and '4'.

Chained comparisons

Perl 6 allows comparisons to "chain". That is, a sequence of comparisons such as the following are allowed:

if 20 <= $temperature <= 25 {
say "Room temperature is between 20 and 25 !"
}

This is treated as if each left-to-right comparison were performed on its own, and the result is logically combined via the and operation.

Lazy evaluation

Perl 6 uses the technique of lazy evaluation
Lazy evaluation
In programming language theory, lazy evaluation or call-by-need is an evaluation strategy which delays the evaluation of an expression until the value of this is actually required and which also avoids repeated evaluations...

 of lists that has been a feature of some functional programming
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...

 languages such as Haskell
Haskell (programming language)
Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...

:

@integers = 0..Inf; # integers from 0 to infinity

The code above will not crash by attempting to assign a list of infinite size to the array @integers, nor will it hang indefinitely in attempting to expand the list if a limited number of slots are searched.

This simplifies many common tasks in Perl 6 including input/output operations, list transformations and parameter passing.

Gather

Related to lazy evaluation is the construction of lazy lists using gather and take, behaving somewhat like generators in languages like Icon or Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

.

my $squares = gather for 0..Inf {
take $_ * $_;
};

$squares will be an infinite list of square numbers, but lazy evaluation of the gather ensures that elements are only computed when they are accessed.

Junctions

Perl 6 introduces the concept of junctions: values that are composites of other values. In the earliest days of Perl 6's design, these were called "superpositions", by analogy to the concept in quantum physics of quantum superposition
Quantum superposition
Quantum superposition is a fundamental principle of quantum mechanics. It holds that a physical system exists in all its particular, theoretically possible states simultaneously; but, when measured, it gives a result corresponding to only one of the possible configurations.Mathematically, it...

s — waveforms that can simultaneously occupy several states until observation "collapses" them. A Perl 5 module released in 2000 by Damian Conway
Damian Conway
Damian Conway is a prominent member of the Perl community, a proponent of object-oriented programming, and the author of several books. He is also an Adjunct Associate Professor in the Faculty of Information Technology at Monash University....

 called Quantum::Superpositions provided an initial proof of concept
Proof of concept
A proof of concept or a proof of principle is a realization of a certain method or idea to demonstrate its feasibility, or a demonstration in principle, whose purpose is to verify that some concept or theory that has the potential of being used...

. While at first such superpositional values seemed like merely a programmatic curiosity, over time their utility and intuitiveness became widely recognized, and junctions now occupy a central place in Perl 6's design.

In their simplest form, junctions are created by combining a set of values with junctive operator
Operator (programming)
Programming languages typically support a set of operators: operations which differ from the language's functions in calling syntax and/or argument passing mode. Common examples that differ by syntax are mathematical arithmetic operations, e.g...

s:

my $any_even_digit = 0 | 2 | 4 | 6 | 8; # any(0, 2, 4, 6, 8)
my $all_odd_digits = 1 & 3 & 5 & 7 & 9; # all(1, 3, 5, 7, 9)

| indicates a value which is equal to either its left or right-hand arguments. & indicates a value which is equal to both its left and right-hand arguments. These values can be used in any code that would use a normal value. Operations performed on a junction act on all members of the junction equally, and combine according to the junctive operator. So, ("apple"|"banana") ~ "s" would yield "apples"|"bananas". In comparisons, junctions return a single true or false result for the comparison. "any" junctions return true if the comparison is true for any one of the elements of the junction. "all" junctions return true if the comparison is true for all of the elements of the junction.

Junctions can also be used to more richly augment the type system by introducing a style of generic programming
Generic programming
In a broad definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters...

 that is constrained to junctions of types:

sub get_tint(RGB_Color | CMYK_Color $color, Num $opacity) {
. . .
}
sub store_record(Record & Storable $rec) {
. . .
}

Autothreading

Junctions are unordered; 1|2|3 and 3|2|1 represent the same value. This lack of ordering means that the Perl 6 compiler can choose to evaluate junctive expressions in parallel. For instance, the code:

if $string ~~ all(@list_of_regexes) {
. . .
}

would indicate to the compiler that all matches of a string against a list of regexes can be executed in parallel, possibly in separate threads
Thread (computer science)
In computer science, a thread of execution is the smallest unit of processing that can be scheduled by an operating system. The implementation of threads and processes differs from one operating system to another, but in most cases, a thread is contained inside a process...

. This feature is dubbed "autothreading". The parallelization of autothreading is not yet implemented in any Perl 6 compiler .

Macros

In low-level languages, the concept of macros has become synonymous with textual substitution of source-code due to the widespread use of the C preprocessor
C preprocessor
The C preprocessor is the preprocessor for the C and C++ computer programming languages. The preprocessor handles directives for source file inclusion , macro definitions , and conditional inclusion ....

. However, high-level languages such as Lisp
Lisp programming language
Lisp is a family of computer programming languages with a long history and a distinctive, fully parenthesized syntax. Originally specified in 1958, Lisp is the second-oldest high-level programming language in widespread use today; only Fortran is older...

 pre-dated C in their use of macros that were far more powerful. It is this Lisp-like macro concept that Perl 6 will take advantage of. The power of this sort of macro stems from the fact that it operates on the program as a high-level data structure
Data structure
In computer science, a data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently.Different kinds of data structures are suited to different kinds of applications, and some are highly specialized to specific tasks...

, rather than as simple text, and has the full capabilities of the programming language at its disposal.

A Perl 6 macro definition will look like a subroutine or method definition, and can operate on unparsed strings, an AST
Abstract syntax tree
In computer science, an abstract syntax tree , or just syntax tree, is a tree representation of the abstract syntactic structure of source code written in a programming language. Each node of the tree denotes a construct occurring in the source code. The syntax is 'abstract' in the sense that it...

 representing pre-parsed code, or a combination of the two. A macro definition would look like this:


macro hello($what) {
quasi { say "Hello { }" };
}


In this particular example, the macro is no more complex than a C-style textual substitution, but because parsing of the macro parameter occurs before the macro operates on the calling code, diagnostic messages would be far more informative. However, because the body of a macro is executed at compile time
Compile time
In computer science, compile time refers to either the operations performed by a compiler , programming language requirements that must be met by source code for it to be successfully compiled , or properties of the program that can be reasoned about at compile time.The operations performed at...

 each time it is used, many techniques of optimization
Optimization (computer science)
In computer science, program optimization or software optimization is the process of modifying a software system to make some aspect of it work more efficiently or use fewer resources...

 can be employed. It is even possible to entirely eliminate complex computations from resulting programs by performing the work at compile-time.

Hello world

The hello world program
Hello world program
A "Hello world" program is a computer program that outputs "Hello world" on a display device. Because it is typically one of the simplest programs possible in most programming languages, it is by tradition often used to illustrate to beginners the most basic syntax of a programming language, or to...

 is a common program used to introduce a language. In Perl 6, hello world is:

say 'Hello, world'

— though there is more than one way to do it
There is more than one way to do it
There's more than one way to do it is a Perl motto. The language was designed with this idea in mind, in that it “doesn't try to tell the programmer how to program.” This makes it easy to write extremely messy programs, but, as proponents of this motto argue, it also makes it easy to write concise...

. The say function prints its arguments, like the print function, but with a trailing newline
Newline
In computing, a newline, also known as a line break or end-of-line marker, is a special character or sequence of characters signifying the end of a line of text. The name comes from the fact that the next character after the newline will appear on a new line—that is, on the next line below the...

. (This feature was backported
Backporting
Backporting is the action of taking a certain software modification and applying it to an older version of the software than it was initially created for. It is part of the maintenance step in a software development process....

 into Perl 5.10.)

Quicksort

Quicksort is a well-known sorting algorithm. A working implementation using the functional programming paradigm can be succinctly written in Perl 6:

# Empty list sorts to the empty list
multi quicksort([]) { }

# Otherwise, extract first item as pivot...
multi quicksort([$pivot, *@rest]) {
# Partition.
my @before = @rest.grep(* < $pivot);
my @after = @rest.grep(* >= $pivot);

# Sort the partitions.
(quicksort(@before), $pivot, quicksort(@after))
}

Tower of Hanoi

Tower of Hanoi
Tower of Hanoi
The Tower of Hanoi or Towers of Hanoi, also called the Tower of Brahma or Towers of Brahma, is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod...

 is often used to introduce recursive programming in computer science. This implementation uses Perl 6's multi-dispatch mechanism and parametric constraints:

multi sub hanoi(0, $, $, $) { } # No disk, so do not do anything
multi sub hanoi($n, $a = 'A', $b = 'B', $c = 'C') { # Start with $n disks and three pegs A, B, C
hanoi $n - 1, $a, $c, $b; # firstly move top $n - 1 disks from A to B
say "Move disk $n from peg $a to peg $c"; # then move last disk from A to C
hanoi $n - 1, $b, $a, $c; # lastly move $n - 1 disks from B to C
}

External links

  • Perl 6 - the main site
  • Official Perl 6 Documentation. The Synopses (The official language specification). While the Apocalypses and Exegeses are linked here for reference, note that the Synopses are kept very much more up-to-date and are the primary recommended reference.
  • The original community RFCs - For historical interest only.

Other

  • The Wiki
  • Planet Perl 6 - Perl 6's blogs aggregrator.
  • Perl5 to Perl 6 - Moritz Lenz's guide to Perl 6 syntax and features
  • Perl 6 and Parrot links - resources catalog
  • Present Continuous, Future Perfect - Larry Wall's talk about Perl 5 and Perl 6 at Open Source Developer Conference 2006 in Netanya
    Netanya
    Netanya is a city in the Northern Centre District of Israel, and is the capital of the surrounding Sharon plain. It is located north of Tel Aviv, and south of Haifa between the 'Poleg' stream and Wingate Institute in the south and the 'Avichail' stream in the north.Its of beaches have made the...

    , Israel (archived HTML, with links to slides and audio recording)
  • Perl 6 FAQ - Answers a wide range of questions about Perl 6.
  • Perl6::Perl5::Differences
  • Perl 6 at Wikia An independent Perl 6 wiki.
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK