Raku is a member of the
Perl
Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
family of
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming l ...
s. Formerly known as Perl 6, it was renamed in October 2019.
Raku introduces elements of many modern and historical languages. Compatibility with Perl was not a goal, though a
compatibility mode is part of the specification. The design process for Raku began in 2000.
History
The Raku design process was first announced on 19 July 2000, on the fourth day of that year's
Perl Conference, by
Larry Wall
Larry Arnold Wall (born September 27, 1954) is an American computer programmer and author. He created the Perl programming language.
Personal life
Wall grew up in Los Angeles and then Bremerton, Washington, before starting higher education at ...
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
Apis or APIS may refer to:
* Apis (deity), an ancient Egyptian god
* Apis (Greek mythology), several different figures in Greek mythology
* Apis (city), an ancient seaport town on the northern coast of Africa
**Kom el-Hisn, a different Egyptian ci ...
. The process began with a series of
requests for comments
A Request for Comments (RFC) is a publication in a series from the principal technical development and standards-setting bodies for the Internet, most prominently the Internet Engineering Task Force (IETF). An RFC is authored by individuals or g ...
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 of the 361 requests received. He then began the process of writing several "Apocalypses", using the original meaning of the term, "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, the Raku specification is managed through the "roast" testing suite, while the Synopses are kept as a historical reference.
There are also a series of Exegeses written by
Damian Conway
Damian Conway (born 5 October 1964 in Melbourne, Australia) is a computer scientist, a member of the Perl and Raku communities, a public speaker, and the author of several books. Until 2010, he was also an adjunct associate professor in the Fa ...
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 Raku today. The first is the raku
IRC channel on
Libera Chat
Libera Chat, stylized Libera.Chat, is an IRC network for free and open source software projects. It was founded on 19 May 2021 by former Freenode staff members, after Freenode was taken over by Andrew Lee, founder of Private Internet Access ...
. The second is a set of
mailing lists.
The third is the
Git
Git () is a distributed version control system: tracking changes in any set of files, usually used for coordinating work among programmers collaboratively developing source code during software development. Its goals include speed, data integ ...
source code repository
In version control systems, a repository is a data structure that stores metadata for a set of files or directory structure. Depending on whether the version control system in use is distributed, like Git or Mercurial, or centralized, like Sub ...
hosted at
GitHub
GitHub, Inc. () is an Internet hosting service for software development and version control using Git. It provides the distributed version control of Git plus access control, bug tracking, software feature requests, task management, co ...
.
Initial goals and implications
The major goal Wall suggested in his initial speech was the removal of historical warts. These included the confusion surrounding
sigil
A sigil () is a type of symbol used in magic. The term has usually referred to a pictorial signature of a deity or spirit. In modern usage, especially in the context of chaos magic, sigil refers to a symbolic representation of the practitio ...
usage for containers, the ambiguity between the
select
functions, and the syntactic impact of bareword
filehandle
In Unix and Unix-like computer operating systems, a file descriptor (FD, less frequently fildes) is a process-unique identifier ( handle) for a file or other input/output resource, such as a pipe or network socket.
File descriptors typically h ...
s. There were many other problems that Perl programmers had discussed fixing for years that were explicitly addressed by Wall in his speech.
An implication of these goals was that Perl 6 would not have
backward compatibility
Backward compatibility (sometimes known as backwards compatibility) is a property of an operating system, product, or technology that allows for interoperability with an older legacy system, or with input designed for such a system, especially ...
with the existing Perl codebase. This meant that some code which was correctly interpreted by a Perl 5 compiler would not be accepted by a Perl 6 compiler. Since backward compatibility is a common goal when enhancing software, the breaking changes in Perl 6 had to be stated explicitly. The distinction between Perl 5 and Perl 6 became so large that eventually Perl 6 was renamed Raku.
Mascot

The language's
mascot
A mascot is any human, animal, or object thought to bring luck, or anything used to represent a group with a common public identity, such as a school, professional sports team, society, military unit, or brand name. Mascots are also used as fic ...
is "Camelia, the Raku bug".
Her name is a nod to the camel mascot associated with
Perl
Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
, and her form, in the pun-loving tradition of the Perl community, is a play on "
software bug". Spiral designs embedded in her butterfly-like wings resemble the characters "P6", the favored nickname for Perl 6, and off-center eye placement is an intentional pun on "Wall-eyed".
One of the goals behind the lively and colorful design of the logo was to discourage misogyny in the community and for it to be an opportunity for those of "masculine persuasion" to show their sensitive side.
Implementations
, only the
Rakudo
Rakudo is a Raku compiler targeting MoarVM, and the Java Virtual Machine, that implements the Raku specification. It is currently the only major Raku compiler in active development.
Originally developed within the Parrot project, the Rakudo sou ...
implementation is under active development. No implementation will be designated as the official Raku implementation; rather, "Raku is anything that passes the official test suite."
Rakudo Perl 6 targets a number of virtual machines, such as
MoarVM, the
Java Virtual Machine
A Java virtual machine (JVM) is a virtual machine that enables a computer to run Java programs as well as programs written in other languages that are also compiled to Java bytecode. The JVM is detailed by a specification that formally describ ...
, and
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
. MoarVM is a
virtual machine
In computing, a virtual machine (VM) is the virtualization/ emulation of a computer system. Virtual machines are based on computer architectures and provide functionality of a physical computer. Their implementations may involve specialized har ...
built especially for Rakudo and the NQP Compiler Toolchain. There is a layer between Raku and the virtual machines called Not Quite Perl 6, or NQP, which implements
Raku rules for parsing Raku, as well as an
abstract syntax tree
In computer science, an abstract syntax tree (AST), or just syntax tree, is a tree representation of the abstract syntactic structure of text (often source code) written in a formal language. Each node of the tree denotes a construct occurring ...
and backend-specific
code generation. Large portions of Rakudo are written in Raku itself, or in its subset NQP. Rakudo is not a completely
self-hosting implementation, nor are there concrete plans at this point to make Rakudo a bootstrapping compiler.
Historical implementations
Pugs
The Pug is a breed of dog originally from China, with physically distinctive features of a wrinkly, short-muzzled face and curled tail. The breed has a fine, glossy coat that comes in a variety of colors, most often light brown (fawn) or blac ...
was an initial implementation of Perl 6 written in
Haskell
Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lan ...
. Pugs used to be the most advanced implementation of Perl 6, but since mid 2007 it is mostly dormant (with updates made only to track the current version of
GHC). As of November 2014 Pugs was not being actively maintained.
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.
Yapsi was a Perl 6 compiler and runtime written in Perl 6 itself. As a result, it required an existing Perl 6 interpreter, such as one of the Rakudo Star releases, in order to run.
Niecza, another major Perl 6 implementation effort, focused on optimization and efficient implementation research. It targets the
Common Language Infrastructure
The Common Language Infrastructure (CLI) is an open specification and technical standard originally developed by Microsoft and standardized by ISO/ IEC (ISO/IEC 23271) and Ecma International (ECMA 335) that describes executable code and a ...
.
Module system
The Raku specification requests that
modules be 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
In signal processing and related disciplines, aliasing is an effect that causes different signals to become indistinguishable (or ''aliases'' of one another) when sampled. It also often refers to the distortion or artifact that results when ...
to a short name is provided.
CPAN
The Comprehensive Perl Archive Network (CPAN) is a repository of over 250,000 software modules and accompanying documentation for 39,000 distributions, written in the Perl programming language by over 12,000 contributors. ''CPAN'' can denote eith ...
, the Perl module distribution system, does not yet handle Raku modules. Instead a prototype module system is in use.
Major changes from Perl
Perl and Raku differ fundamentally, though in general the intent has been to "keep Raku Perl", so that Raku is clearly "a Perl programming language". Most of the changes are intended to normalize the language, to make it easier for novice and expert programmers alike to understand, and to make "easy things easier and hard things more possible".
A specification
A major non-technical difference between Perl and Raku is that Raku began as a specification.
This means that Raku can be re-implemented if needed, and it also means that programmers do not have to read the
source code
In computing, source code, or simply code, is any collection of code, with or without comment (computer programming), comments, written using a human-readable programming language, usually as plain text. The source code of a Computer program, p ...
for the ultimate authority on any given feature. In contrast, in Perl, the official documentation is not considered authoritative and only describes the behavior of the actual Perl 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 releases.
A type system
In Raku, the
dynamic type system of Perl has been augmented by the addition of
static type
In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a type to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer program ...
s.
For example:
my Int $i = 0;
my Rat $r = 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
Raku offers a
gradual typing
Gradual typing is a type system in which some variables and expressions may be given types and the correctness of the typing is checked at compile time (which is static typing) and some expressions may be left untyped and eventual type errors a ...
system, whereby the programmer may choose to use static typing, use dynamic typing, or mix the two.
Formal subroutine parameter lists
Perl defines subroutines without
formal parameter lists at all (though simple parameter counting and some type checking can be done using Perl'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.
Raku introduces true formal parameters to the language.
In Raku, a subroutine declaration looks like this:
sub do_something(Str $thing, Int $other)
As in Perl, 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 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 respectively should the programmer require them to be modified locally.
Parameter passing modes
Raku provides three basic modes of parameter passing: positional parameters,
named parameters, and slurpy parameters.
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. Named-only parameters (indicated by a
:
before the parameter name) can only be passed by specifying its name, i.e. it never captures a positional argument. Slurpy parameters (indicated by an
*
before the parameter name) are Raku's tool for creating
variadic function
In mathematics and 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.
The term ''var ...
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)
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. 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 terminology).
Sigil invariance
In Perl,
''sigils'' – the punctuation characters that precede a variable name – change depending on how the variable is used:
# Perl code
my array = ('a', 'b', 'c');
my $element = array
# $element equals 'b',
my @extract = array
, 2
The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...
# @extract equals ('b', 'c')
my $element = array
# 'b' comes with a warning (5.10 option)
In Raku, sigils are invariant, which means that they do not change based on whether it is the array or the array element that is needed:
# Raku code
my array = 'a', 'b', 'c';
my $element = array
# $element equals 'b'
my @extract = array
# @extract equals ('b')
my @extract = array
, 2
The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...
# @extract equals ('b', 'c')
The variance in Perl is inspired by number agreement in English and many other natural languages:
"This apple." # $a CORRECT
"These apples." # @a CORRECT
"This third apple." # $a
CORRECT
"These third apple." # @a
WRONG
However, this conceptual mapping breaks down when using
references
Reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a '' name'' ...
, since they may refer to data structures 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 code: retrieve a list from the leaf of a hash containing hashes that contain arrays
my @trans_verbs = @;
This complexity has no equivalent either in common use of natural language or in other programming languages, and it causes high
cognitive load
In cognitive psychology, cognitive load refers to the amount of working memory resources used. There are three types of cognitive load: ''intrinsic'' cognitive load is the effort associated with a specific topic; ''extraneous'' cognitive load refe ...
when writing code to manipulate complex data structures. This is the same code in Raku:
# Raku code: retrieve a list from the leaf of a hash containing hashes that contain arrays
my @trans_verbs = %dictionary<>;
Object-oriented programming
Perl supports
object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of " objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
via a mechanism known as ''blessing''. Any reference can be blessed into being an object of a particular class. A blessed object can have
method
Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to:
*Scien ...
s invoked on it using the "arrow syntax" which will cause Perl to locate or "dispatch" an appropriate
subroutine
In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.
Functions ma ...
by name, and call it with the blessed variable as its first argument.
While extremely powerful, it makes the most common case of object orientation, a
struct
In computer science, a record (also called a structure, struct, or compound data) is a basic data structure. Records in a database or spreadsheet are usually called "rows".
A record is a collection of ''fields'', possibly of different data types ...
-like object with some associated code, unnecessarily difficult. In addition, because Perl can make no assumptions about the
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. Examples are the object models of ''Java'', ...
in use, method invocation cannot be optimized very well.
In the spirit of making the "easy things easy and hard things possible", Raku retains the blessing model and supplies a more robust object model for the common cases. For example, a class to encapsulate a
Cartesian point could be defined and used this way:
class Point is rw
my $point = Point.new( x => 1.2, y => -3.7 );
say "Point's location: (", $point.x, ', ', $point.y, ')';
# OUTPUT: Point's location: (1.2, -3.7)
# Changing x and y (note methods "x" and "y" used as lvalues):
$point.x = 3;
$point.y = 4;
say "Point's location: (", $point.x, ', ', $point.y, ')';
# OUTPUT: Point's location: (3, 4)
my $other-point = Point.new(x => -5, y => 10);
$point.distance($other-point); #=> 10
$point.distance-to-center; #=> 5
The dot replaces the arrow in a nod to the many other languages (e.g.
C++,
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
,
Python, etc.) that have coalesced around dot as the syntax for method invocation.
In the terminology of Raku,
$.x
is called an "attribute". Some languages call these ''fields ''or ''members''. The method used to access an attribute is called an "accessor". An auto-accessor method is a method created automatically and named after the attribute's name, 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-accessors 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 via the
$!
syntax regardless of how the attributes are declared. All other access must go through the accessor methods.
The Raku object system has inspired the
Moose
The moose (in North America) or elk (in Eurasia) (''Alces alces'') is a member of the New World deer subfamily and is the only species in the genus ''Alces''. It is the largest and heaviest extant species in the deer family. Most adult ma ...
framework that introduces many of Raku's OOP features to Perl.
Inheritance, Roles and Classes
Inheritance is the technique by which an object or type can re-use code or definitions from existing objects or types. For example, a programmer may want to have a standard type but with an extra attribute. Inheritance in other languages, such as Java, is provided by allowing Classes to be sub-classes of existing classes.
Raku provides for inheritance via Classes, which are similar to Classes in other languages, and Roles.
Roles in Raku take on the function of
''interfaces'' in Java, ''
mixin
In object-oriented programming languages, a mixin (or mix-in) is a class that contains methods for use by other classes without having to be the parent class of those other classes. How those other classes gain access to the mixin's methods depen ...
s'' in Ruby, and ''
traits'' in
PHP
PHP is a General-purpose programming language, general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementati ...
and in the
Smalltalk
Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by ...
variant
Squeak
Squeak is an object-oriented, class-based, and reflective programming language. It was derived from Smalltalk-80 by a group that included some of Smalltalk-80's original developers, initially at Apple Computer, then at Walt Disney Imagineering ...
. These are much like classes, but they provide a safer composition mechanism. These are used to perform composition when used with classes rather than adding to their
inheritance
Inheritance is the practice of receiving private property, titles, debts, entitlements, privileges, rights, and obligations upon the death of an individual. The rules of inheritance differ among societies and have changed over time. Offici ...
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 can be instantiated; roles are not.
Although Roles are distinct from Classes, it is possible to write Raku code that directly instantiates a Role or uses a Role as a type object, Raku will automatically create a class with the same name as the role, making it possible to transparently use a role as if it were a class.
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, Raku 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
The dog (''Canis familiaris'' or ''Canis lupus familiaris'') is a domesticated descendant of the wolf. Also called the domestic dog, it is derived from the extinct Pleistocene wolf, and the modern wolf is the dog's nearest living relativ ...
is a
Mammal because dogs inherit certain characteristics from Mammals, such as
mammary gland
A mammary gland is an exocrine gland in humans and other mammals that produces milk to feed young offspring. Mammals get their name from the Latin word ''mamma'', "breast". The mammary glands are arranged in organs such as the breasts in pr ...
s and (through Mammal's parent,
Vertebrate
Vertebrates () comprise all animal taxon, taxa within the subphylum Vertebrata () (chordates with vertebral column, backbones), including all mammals, birds, reptiles, amphibians, and fish. Vertebrates represent the overwhelming majority of the ...
) a
backbone. On the other hand, dogs also may have one of several distinct types of behavior, and these behaviours may change over time. For example, a Dog may be a
Pet
A pet, or companion animal, is an animal kept primarily for a person's company or entertainment rather than as a working animal, livestock, or a laboratory animal. Popular pets are often considered to have attractive appearances, intelligence ...
, a
Stray
Stray or The Stray or ''variation'', may refer to:
Animals
* A feral (abandoned or escaped) domestic animal; see also estray
* A stray or free-ranging dog
Places
* Areas of open grassland in North Yorkshire:
** Strays of York
** The Stray (Har ...
(an abandoned pet will acquire behaviours to survive not associated with a pet), or a
Guide
A guide is a person who leads travelers, sportspeople, or tourists through unknown or unfamiliar locations. The term can also be applied to a person who leads others to more abstract goals such as knowledge or wisdom.
Travel and recreation
Exp ...
for the blind (guide dogs are trained, so they do not start life as guide dogs). However, these are sets of additional behaviors that can be added to a Dog. It is also possible to describe these behaviors in such a way that they can be usefully applied to other animals, for example, a
Cat
The cat (''Felis catus'') is a domestic species of small carnivorous mammal. It is the only domesticated species in the family Felidae and is commonly referred to as the domestic cat or house cat to distinguish it from the wild members of ...
can equally be a Pet or Stray. Hence, Dog and Cat are distinct from each other, while both remain within the more general category Mammal. So Mammal is a Class and Dog and Cat are classes that inherit from Mammal. But the behaviours associated with Pet, Stray, and Guide are Roles that can be added to Classes, or objects instantiated from Classes.
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. In order to show inheritance from a class, there is a different keyword
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
A guide horse is an alternative mobility option for blind people who do not wish to or cannot use a guide dog. History
The idea of a guide horse for a blind person dates back to 1943 if not earlier, the film '' The Blocked Trail'' of that year ha ...
, a Guide Human, or even a Guide Machine.
class Human
role Blind
Regular expressions
Perl's
regular expression
A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" ...
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
In theoretical computer science and formal language theory, a regular language (also called a rational language) is a formal language that can be defined by a regular expression, in the strict sense in theoretical computer science (as opposed to ...
expressions for some time, Raku documentation will exclusively refer to them as ''regexes'', distancing the term from the formal definition.
Raku provides a superset of Perl features with respect to regexes, folding them into a larger framework called "
rules
Rule or ruling may refer to:
Education
* Royal University of Law and Economics (RULE), a university in Cambodia
Human activity
* The exercise of political or personal control by someone with authority or power
* Business rule, a rule pert ...
" which provide the capabilities of
context-sensitive parsing
Parsing, syntax analysis, or syntactic analysis is the process of analyzing a string of symbols, either in natural language, computer languages or data structures, conforming to the rules of a formal grammar. The term ''parsing'' comes from Lati ...
formalisms (such as the
syntactic predicates of
parsing expression grammar
In computer science, a parsing expression grammar (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. The formalism was introduced by Bryan Ford in ...
s and
ANTLR
In computer-based language recognition, ANTLR (pronounced ''antler''), or ANother Tool for Language Recognition, is a parser generator that uses LL(*) for parsing. ANTLR is the successor to the Purdue Compiler Construction Tool Set (PCCTS), fir ...
), as well as acting as a
closure with respect to their
lexical scope
In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other part ...
. 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 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 constructs have been changed in Raku, optimized for different syntactic cues for the most common cases. For example, the parentheses (round
bracket
A bracket is either of two tall fore- or back-facing punctuation marks commonly used to isolate a segment of text or data from its surroundings. Typically deployed in symmetric pairs, an individual bracket may be identified as a 'left' or 'r ...
s) required in
control flow
In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an '' ...
constructs in Perl are now optional:
if is-true()
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
Raku allows comparisons to "chain". That is, a sequence of comparisons such as the following is allowed:
if 20 <= $temperature <= 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
Raku uses the technique of
lazy evaluation
In programming language theory, lazy evaluation, or call-by-need, is an evaluation strategy which delays the evaluation of an expression until its value is needed ( non-strict evaluation) and which also avoids repeated evaluations ( sharing).
T ...
of lists that has been a feature of some
functional programming
In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions that ...
languages such as
Haskell
Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lan ...
:
@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 Raku 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
An icon () is a religious work of art, most commonly a painting, in the cultures of the Eastern Orthodox, Oriental Orthodox, and Catholic churches. They are not simply artworks; "an icon is a sacred image used in religious devotion". The most c ...
or
Python.
my $squares = lazy gather for 0..Inf ;
$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
Raku introduces the concept of ''junctions'': values that are composites of other values.
In their simplest form, junctions are created by combining a set of values with junctive
operator
Operator may refer to:
Mathematics
* A symbol indicating a mathematical operation
* Logical operator or logical connective in mathematical logic
* Operator (mathematics), mapping that acts on elements of a space to produce elements of another ...
s:
# Example for , ("any") Junction:
my $color = 'white';
unless $color eq 'white' , 'black' , 'gray' , 'grey'
# Example for & ("all") Junction:
my $password = 'secret!123';
if $password ~~ /<:alpha>/ & /<:digit>/ & /<:punct>/
,
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 is a style of computer programming in which algorithms are written in terms of types ''to-be-specified-later'' that are then ''instantiated'' when needed for specific types provided as parameters. This approach, pioneered b ...
that is constrained to junctions of types:
subset Color of Any where RGB_Color , CMYK_Color;
sub get_tint(Color $color, Num $opacity)
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
The C preprocessor is the macro preprocessor for the C, Objective-C and C++ computer programming languages. The preprocessor provides the ability for the inclusion of header files, macro expansions, conditional compilation, and line contro ...
. However, high-level languages such as
Lisp
A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech.
Types
* A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lispi ...
pre-dated C in their use of macros that were far more powerful. It is this Lisp-like macro concept that Raku 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
In computer science, a data structure is a data organization, management, and storage format that is usually chosen for Efficiency, efficient Data access, access to data. More precisely, a data structure is a collection of data values, the rel ...
, rather than as simple text, and has the full capabilities of the programming language at its disposal.
A Raku macro definition will look like a subroutine or method definition, and it can operate on unparsed strings, an
AST representing pre-parsed code, or a combination of the two. A macro definition would look like this:
macro hello($what)
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
In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled.
The term is used as an adjective to describe concepts related to the context of program compilation, as opposed to concept ...
each time it is used, many techniques of
optimization
Mathematical optimization (alternatively spelled ''optimisation'') or mathematical programming is the selection of a best element, with regard to some criterion, from some set of available alternatives. It is generally divided into two subfi ...
can be employed. It is even possible to eliminate complex computations from resulting programs by performing the work at compile-time.
Identifiers
In Perl, identifier names can use the ASCII alphanumerics and underscores also available in other languages. In Raku, the alphanumerics can include most Unicode characters. In addition, hyphens and apostrophes can be used (with certain restrictions, such as not being followed by a digit). Using hyphens instead of underscores to separate words in a name leads to a style of naming called "
kebab case".
Examples
Hello world
The
hello world program
''Hello'' is a salutation or greeting in the English language. It is first attested in writing from 1826. Early uses
''Hello'', with that spelling, was used in publications in the U.S. as early as the 18 October 1826 edition of the '' Norwich ...
is a common program used to introduce a language. In Raku, hello world is:
say 'Hello, world';
— though
there is more than one way to do it.
Factorial
The
factorial
In mathematics, the factorial of a non-negative denoted is the product of all positive integers less than or equal The factorial also equals the product of n with the next smaller factorial:
\begin
n! &= n \times (n-1) \times (n-2) ...
function in Raku, defined in a few different ways:
# Using recursion (with `if\else` construct)
sub fact( UInt $n --> UInt )
# Using recursion (with `if` as statement modifier)
sub fact( UInt $n --> UInt )
# Using recursion (with `when` construct)
sub fact( UInt $n --> UInt )
# Using the ternary operator
sub fact( UInt $n --> UInt )
# Using multiple dispatch
multi fact(0)
multi fact( UInt $n --> UInt )
# Using the reduction metaoperator
sub fact( UInt $n --> UInt )
# Creating a factorial operator and using the reduction metaoperator
sub postfix:( UInt $n --> UInt )
# Using `state` declarator to create a memoized factorial
sub fact( UInt $n --> UInt )
Quicksort
Quicksort
Quicksort is an efficient, general-purpose sorting algorithm. Quicksort was developed by British computer scientist Tony Hoare in 1959 and published in 1961, it is still a commonly used algorithm for sorting. Overall, it is slightly faster than ...
is a well-known sorting algorithm. A working implementation using the functional programming paradigm can be succinctly written in Raku:
# Empty list sorts to the empty list
multi quicksort([])
# Otherwise, extract first item as pivot...
multi quicksort([$pivot, *@rest])
Tower of Hanoi
Tower of Hanoi is often used to introduce recursive programming in computer science. This implementation uses Raku'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')
Books
In the history of Raku there were two waves of book writing. The first wave followed the initial announcement of Perl 6 in 2000. Those books reflect the state of the design of the language of that time, and contain mostly outdated material. The second wave, that followed the announcement of Version 1.0 in 2015, includes several books that have already been published and some others that are in the process of being written.
Books published before Perl 6 version 1.0 (known as version 6.c)
* A. Randal, D. Sugalski, L. Totsch. ''Perl 6 and Parrot Essentials'', 1st edition, 2003,
* A. Randal, D. Sugalski, L. Totsch
''Perl 6 and Parrot Essentials'', Second Edition2004.
* S. Walters
''Perl 6 Now: The Core Ideas Illustrated with Perl 5.''2004.
Also, a book dedicated to one of the first Perl 6 virtual machines, Parrot, was published in 2009.
* A. Randal, A. Whitworth
2009.
Books published after Perl 6 version 1.0 (known as version 6.c)
* Andrew Shitov
''Perl 6 at a Glance.''2017. �
download free official PDFor download i
from GitHub* Laurent Rosenfeld, Allen B. Downey
''Think Perl 6''2017.
* Moritz Lenz
''Perl 6 Fundamentals''2017.
* J. J. Merelo
''Learning to program with Perl 6: First Steps: Getting into programming without leaving the command line''2017.
* Andrew Shitov
''Perl 6 Deep Dive'' 2017.
* Andrew Shitov
''Using Perl 6'' 2017. �
download free official PDFor downloa
from GitHub* Moritz Lenz
''Searching and Parsing with Perl 6 Regexes''2017.
*
brian d foy''Learning Perl 6''2018
Books published with the new Raku name
* Andrew Shitov.
Using Raku', 2nd edition, 2019, �
download free official PDFor download a cop
from GitHub* Andrew Shitov.
Raku One-Liners', 2019, �
download free official PDFor downloa
from GitHub
Books to be published
There are a few reports
Books about Perl 6
/ref> from different authors about the new books that are going to be published soon, all based on the current version 1.0 (known as version 6.c) of Perl 6.
* Andrew Shitov. ''Migrating to Perl 6. An Easy Transition from Perl 5''. . Probably never to be published.
* Gabor Szabo
''Web Application Development in Perl 6''
References
External links
*
{{Use dmy dates, date=October 2018
Programming languages
Raku (programming language)
Multi-paradigm programming languages
Articles with example Perl code
Cross-platform software
Free compilers and interpreters
High-level programming languages
Scripting languages
Programming languages created in 2015
Free software programmed in C