34,79 €
Perl is a family of high-level, general-purpose, interpreted, dynamic programming languages consisting of Perl 5 and Perl 6. Perl 6 helps developers write concise and declarative code that is easy to maintain.
This book is an end-to-end guide that will help non-Perl developers get to grips with the language and use it to solve real-world problems.
Beginning with a brief introduction to Perl 6, the first module in the book will teach you how to write and execute basic programs. The second module delves into language constructs, where you will learn about the built-in data types, variables, operators, modules, subroutines, and so on available in Perl 6. Here the book also delves deeply into data manipulation (for example, strings and text files) and you will learn how to create safe and correct Perl 6 modules. You will learn to create software in Perl by following the Object Oriented Paradigm. The final module explains in detail the incredible concurrency support provided by Perl 6. Here you will also learn about regexes, functional programming, and reactive programming in Perl 6.
By the end of the book, with the help of a number of examples that you can follow and immediately run, modify, and use in practice, you will be fully conversant with the benefits of Perl 6.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 452
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: September 2017
Production reference: 1060917
ISBN 978-1-78728-204-9
www.packtpub.com
Author
Andrew Shitov
Copy Editor
Safis Editing
Reviewer
Alex Kapranoff
Project Coordinator
Prajakta Naik
Commissioning Editor
Merint Mathew
Proofreader
Safis Editing
Acquisition Editor
Chaitanya Nair
Indexer
Francy Puthiry
ContentDevelopmentEditor
Lawrence Veigas
Graphics
Abhinash Sahu
Technical Editor
Mehul Singh
Production Coordinator
Nilesh Mohite
Andrew Shitov has been a Perl enthusiast since the end of the 1990s, and is the organizer of over 30 Perl conferences in eight countries. He worked as a developer and CTO in leading web-development companies, such as Art. Lebedev Studio, Booking.com, and eBay, and he learned from the "Fathers of the Russian Internet", Artemy Lebedev and Anton Nossik.
Andrew has been following the Perl 6 development since its beginning in 2000. He ran a blog dedicated to the language, published a series of articles in the Pragmatic Perl magazine, and gives talks about Perl 6 at various Perl events. In 2017, he published the Perl 6 at a Glance book by DeepText, which was the first book on Perl 6 published after the first stable release of the language specification.
Through the course of writing this book, I contacted many people who helped me clarify many dark corners of Perl 6. First of all, thanks to the reviewers of this book, Liz Mattijsen, who is also the core developer of the Perl 6 compiler, and Alex Kapranoff, who has helped me promote Perl 6 for more than a decade already.
I would also like to thank the whole Rakudo compiler team, who worked hard to make things happen even when almost nobody believed that Perl 6 would become a reality. So, primarily, thanks to Jonathan Worthington for not only working on the compiler, but also for his talks, which I found on YouTube and used for reference. Also, thanks to the rest of the team.
Special thanks go to Wendy van Dijk, who has done great work to change the image of the Perl language and has personally helped me promote my books.
And of course, thanks to the author of Perl, Larry Wall, and his wife, Gloria, for the years of patience and enthusiasm; they made Perl 6 fly in the end.
This book has also been possible due to the number of other Perl 6 books that appeared this year; so, I want to thank the authors of those books as they indirectly stimulated me to write faster and more.
Finally, this book took its shape with the efforts of the editors at Packt, Lawrence Veigas, who guided me through the writing process, and Mehul Singh, who joined at the last stage of the publishing process and provided many suggestions on how to make the book better and more useful for the readers.
Alex Kapranoff studied software engineering in one of the smaller Russian cities and then worked in the internet industry for about 20 years in roles ranging from software developer to CTO to technical manager. Having written production code in many programming languages, he still considers Perl his one true love. Perl 6 is a huge step forward for the language, for the ecosystem, and, maybe even for programming language theory.
Agava, Inline Technologies, Rambler.ru, and Yandex are companies that provided Alex with the opportunities to be his best and write impactful code in Perl on a day-to-day basis throughout his career.
Alex has worked on a number of books about the performance-oriented web server software, Nginx, and published his own take on Nginx Troubleshooting with Packt Publishing.
For support files and downloads related to your book, please visitwww.PacktPub.com. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version atwww.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us [email protected] more details.
Atwww.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/178728204X.
If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
What is Perl 6?
Origins of Perl 6
Differences from Perl 5
Sigils
Signatures
Classes
Compatibility with Perl 5
Perl 6 resources
Documentation
Test Suite
STD.pm
Community
Compilers
Parrot
Pugs
Perlito
Rakudo
Working with Rakudo Star
Downloading and installing Rakudo Star
Command-line options
The -c command
The --doc command
The -e command
The -h and --help commands
The -n command
The -p command
The -I and -M commands
The -v and --version command
The --stagestats command
Writing our Hello World program
Summary
Writing Code
Using Unicode
Whitespaces and unspaces
Comments
One-line comments
Multiline comments
Embedded comments
Creating Pod documentation
The =begin / =end Pod block
Phasers
Simple input and output
Summary
Working with Variables and Built-in Data Types
Using variables
Declaring variables
Variable containers in Perl 6
Scalars
Arrays
Methods of the Array type
Hashes
Methods of the Hash class
Naming conventions
Typed variables
Using simple built-in data types
Integer data type
Methods of the Int type
Converting to a character using the chr method
Checking whether the number is prime
Generating a random number
Getting the sign of the value
Calculating the square root of the value
Getting the next and previous values
Getting the absolute value
Rational data type
Methods of the Rat type
Getting the Perl representation of the value
Converting to an Int value
Getting the numerator and denominator
Methods for rounding the value
Methods pred and succ
Numeric data type
Num versus Numeric versus Real
Enumerations
Boolean data type
Methods of the Bool type
Using pred and succ
Methods to generate random Boolean values
String data type
Methods of the Str class
Converting register
Methods to cut strings
Methods to check the content of a string
Length of the string
Reversing a string
Complex numbers
Methods of the Complex data type
Getting real and imaginary parts
Data types to manipulate date and time
Using the Date class
Using the DateTime data type
Summary
Working with Operators
Operator classification
Categories of operators
Operators as functions
Operators in Perl 6
Infix operators
Assignment operators
Operators for multiplication and division
Operators for addition and subtraction
Modulo operator
Divisibility operator
Integer division and modulo operators
Bitwise operators
Integer shift operators
String logical operators
Boolean logical operators
Great common divisor and least common multiple operators
String repetition operator
List repetition operator
String concatenation operator
Junction operators
The does operator
The but operator
Universal comparison operator
String comparison operator leg
Comparison operator for Real numbers
Range creating operator
Equality and non-equality operators
Numerical comparison operators
String comparison operators eq and ne
Other string comparison operators
The before and after operators
Equivalency test operator
Value identity operator
Bound check operator
Smartmatch operator
Approximate-equality operator
Boolean logical operators
Defined-or operator
Operators for minimum and maximum
Pair creation operator
Comma operator
Invocant separator
Zip operator
Cross operator
Sequence operator
Binding operators
Logical operator with lower precedence
Data pipe operators
Ternary operator ?? !!
Prefix operators
Increment and decrement operators ++ and --
Boolean coercion operator
Boolean negation operator
Numeric coercion operator
Numeric negation operator
String coercion operator
Two-complement binary negation operator
Boolean coercion and negation operator
The upto operator
The temp operator
The let operator
The not operator
The so operator
Postfix operators
Object-oriented postfix operators
Increment and decrement operators
Circumfix operators
Quote-word operator
Group operator
Hash or block creation operator
Postcircumfix operators
Positional access operator
Element access operators
Invoke operator
Meta-operators in Perl 6
Assignment meta-operator
Negation meta-operator
Reverse meta-operator
Reduction meta-operator
Cross meta-operator
Zip meta-operator
Hyper-operators
User-defined operators
Summary
Control Flow
Understanding code blocks and variable scoping
The do keyword
Conditional checks
Using loops
The loop cycle
The for loop
Using while, until, and repeat
Breaking the loop
Using labels
Executing code once
Collecting data with gather and take
Setting the topic with given
Summary
Subroutines
Creating and calling subroutines
Default values
Optional parameters
Named parameters
Parameter traits
Slurpy parameters
Parameter placeholders
Type constraints
Typed parameters
Return type
Multi subs
An example
Nested subroutines
Creating operators
Passing functions as arguments
Anonymous subs
Summary
Modules
Creating a module
Using modules
The need keyword
The import keyword
The use keyword
The require keyword
Scoping
More on is export
Exporting variables
Selective import
Introspection
Using zef
Installing a module
Searching for a module
Uninstalling modules
zef command summary
How Rakudo stores modules
Summary
Object-Oriented Programming
Creating a class
Working with attributes
Read-and-write attributes
Typed attributes
Using other classes as data types
Working with methods
Private methods
More about attributes
Public and private attributes
Automatic getters and setters
Class attributes
Class methods
Inheritance
Inheriting from a class
Using child class instances as objects of a base class
Overriding methods
Submethods
Multiple inheritance
Appending objects and classes using roles
Using introspection to learn more
Method postfix operators
Summary
Input and Output
Standard input and output
Working with files and directories
Opening a file
Closing a file
Testing file and directory properties
Manipulating files
Working with directories
Reading from a stream
Reading a single line
Reading characters
Lazy readers
The eof method
Writing to a stream
The print function
The say method
Example of using the gist method
The printf method
Characters and strings
Integers
Floating-point numbers
Summary
Working with Exceptions
The try block
The $! variable
Soft failures
The CATCH phaser
The Exception object
Throwing exceptions
Resuming from exceptions
Typed exceptions
Rethrowing exceptions
The Failure object
Creating custom exceptions
Summary
Regexes
Matching against regexes
Literals
Character classes
The . (dot) character
Backslashed character classes
\s and \S characters
\t and \T characters
\h and \H characters
\v and \V characters
\n and \N characters
\d and \D characters
\w and \W characters
Character classes
Predefined subrules
Using Unicode properties
Character class arithmetics
Creating repeated patterns with quantifiers
Greediness
Extracting substrings with capturing
Capturing groups
The Match object
Named captures
Using alternations in regexes
Positioning regexes with anchors
Matching at the start and at the end of lines or strings
Matching word boundaries
Looking forward and backward with assertions
Modifying regexes with adverbs
:i (:ignorecase)
:s (:sigspace)
:p (:pos)
:g (:global)
:c (:continue)
:r (:ratchet)
:ov (:overlap)
:ex (:exhaustive)
Substitution and altering strings with regexes
Summary
Grammars
Creating a grammar
Matching a grammar
Using rules and tokens
Using actions
Using abstract syntax tree attributes
Handling expressions
Using the actions class
The whole program
Summary
Concurrent Programming
Junctions
Autothreading
Threads
Starting a thread
Creating and running a new thread
The id and name methods
Printing thread objects as a string
Lifetime threads
Using locks in Perl 6
Promises
Creating a promise
Statuses of a promise
Factory methods
The result of a promise
Combining promises
Executing code after the promise is kept or broken
The anyof and allof methods
Channels
Basic use cases
To wait or not to wait?
Closing channels
Channels as queues
Summary
Functional Programming
What is functional programming?
Using recursion
Using reduction
Higher-order functions and lambdas
The WhateverCode blocks
Piping data and feed operators
Manipulating the scope
Closures
Currying
Dynamic scope
Creating and using iterators
Lazy and infinite lists
Summary
Reactive Programming
What is reactive programming?
On-demand supplies
Generating data with supplies
The react and whenever keywords
Using lists as the source of the supply data
Live supplies
Filtering and transforming data streams
Summary
Perl 6 is a new programming language in the Perl family. It has come a long way from the start of its development in 2000 to the current state, when the language is production ready.
Although the initial project of the language was a next version of Perl 5 to trim some edges, get rid of legacy, and add features that were requested by the community, it instead turned out to be a shiny language that holds the spirit of Perl, offers us a variety of modern mechanisms, and allows you to follow paradigms such as functional and reactive programming.
The great thing about today’s Perl 6 is that all these new things are already built into the language and no external libraries are needed to start working with them. For example, take one of the most difficult topics: concurrent and parallel programming. Perl 6 has support for it so that the programmer can start using it right away without thinking about how to organize spawning new threads or implement inter-process communication and access shared data.
One of the goals that we had while writing this book was to show that Perl 6 is a great tool you can consider for your daily practice.
This book contains 15 chapters that cover everything from the basics to more complex themes such as functional programming.
Chapter 1, What is Perl 6?, talks about the reasons why Perl 6 appeared, briefly describes the changes that happened since Perl 5, and explains how to install the compiler and run the first program, "Hello, World!".
Chapter 2, Writing Code, prepares you to write a Perl 6 code and explains how the source code is organized. It gives an overview of the Unicode support that Perl 6 offers to a programmer.
Chapter 3, Working with Variables and Built-In Data Types, takes you through the built-in types of the language and teaches you how to work with variables, such as simple scalars, arrays, and hashes, as well as composite data types.
Chapter 4, Working with Operators, covers the dozens of built-in operators in Perl 6 and introduces you to concepts such as meta-, cross-, and hyper-operators, which may be new for the Perl 5 programmers.
Chapter 5, Control Flow, explains the main elements to control the flow of programs in Perl 6, such as conditional checks and loops.
Chapter 6, Subroutines, covers the work with subroutines in Perl 6. It explains how to create and call a subroutine, how to describe its arguments and return types, and how to deal with anonymous and nested subroutines.
Chapter 7, Modules, talks about the topic of organizing code into modules and the ways of importing the module in a program.
Chapter 8, Object-Oriented Programming, introduces the concepts of inheritance, roles, and introspections, and gives information about using an object in code. It also discusses the object-oriented facilities of Perl 6.
Chapter 9, Input and Output, is devoted to input and output in a console application and working with files and directories.
Chapter 10, Working with Exceptions, talks about exceptional situations that the program can face, for example, disk failure or broken connection to a database. Also, it shows how to create your own exceptions to control the behavior of the program.
Chapter 11, Regexes, describes the redesigned regular expressions, which was one of the keystones of Perl 5 and has become even more powerful in Perl 6.
Chapter 12, Grammars, introduces the new built-in tool that helps create a parser, a translator, or a compiler; a domain-specific language or even a programming language; or even a parser that can work with human languages.
Chapter 13, Concurrent Programming, describes that Perl 6’s built-in support of the concepts, which makes it easy to create an application that supports parallel and concurrent programming, such as threads, junctions, promises, and channels.
Chapter 14, Functional Programming, shows the ways in which you can use the functional programming style with Perl 6, including recursion, reduction, higher order functions, closures, currying, and lazy evaluations.
Chapter 15, Reactive Programming, talks about a particular topic of functional programming--event-driven programming. It explains how to work with supplies and taps and how to filter and transform the data streams.
This book can, of course, be read without a computer at hand, in which case, you need nothing more than the book itself. However, to follow the examples in the book, you need a compiler of Perl 6, which you can download from http://rakudo.org/how-to-get-rakudo/ (more details on installing it are in Chapter 1, What is Perl 6?). The Rakudo Perl 6 compiler works on a variety of platforms--Windows, macOS, and Linux. You will also need your favorite text editor to write programs in.
This book is intended for different groups of people--first of all, to the current developers that use the Perl 5 programming language and are willing to switch to Perl 6 in the near future or simply want to know what’s new in the world of Perl. Second, this book will suit the needs of software developers who are interested in broadening the horizons of their tools and want to be familiar with a new handy programming language that offers built-in support of many programming paradigms. The content of this book is built in such a way that references to Perl 5 are avoided as much as possible, so both people with and without a Perl 5 background can read this book with ease. Finally, this book is written with the hope that it will become a textbook for the educational courses of Perl 6.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, URLs, user input, and program output are shown as follows: "If the file does not exist, the $fh handle will be set to a Failure object."
A block of code is set as follows:
say 0.7 * (@street ==>grep {.number %% 2} ==>grep {.colour eq 'red'} ==>grep {.renovation-year < 2013} ==>map {.area * 3} ==>reduce {$^a + $^b});
Any command-line input and output are shown in bold as follows:
$ perl6 –v
This is Rakudo version 2017.07 built on MoarVM version 2017.07
implementing Perl 6.c.
New terms and important words are shown in bold.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important to us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply email [email protected], and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Perl-6-Deep-Dive. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!'
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
In this chapter, we will examine the reasons why Perl 6 appeared and follow the history of the development of the language. You will see some examples of changes that have happened since Perl 5, and you will learn how to download and use the compiler, where to find the documentation, and how to run your first program in Perl 6.
In this chapter, we will cover the following topics:
Origins of Perl 6
Differences from Perl 5
Perl 6 resources
Compilers
Working with Rakudo Star
Writing our Hello World program
Perl 6 is a programming language from the Perl family. Perl itself emerged in 1987 and since then, it is constantly evolving: its current stable version is 5.26, which was released in May 2017. In 2000, Larry Wall, the creator of Perl, proposed to start working on the next version of the language—Perl 6.
There were a few reasons for that. First, a language should continue developing to reflect the new requirements of developers. Second, it may change the perception of Perl in the non-Perl community. The version 5.0 appeared in 1993 and despite that, the language has continued developing. The major version number was still 5 and in the eyes of many people, it meant that Perl was stalled since 1993. The new major version update would refresh the perception.
The idea was to make Perl 6 "the community rewrite of Perl". Larry asked the community to share what bits of Perl they wanted to change. That call for changes resulted in 361 RFC (Request for Comments) documents, which are published at https://perl6.org/archive/rfc/. These documents are only of historical interest as of today.
Later, the various proposals were systematically analyzed, grouped together by similar topics and published as a series of Synopses. The naming and numbering principle behind those documents were to keep the structure of the chapters of the Programming Perl book.
Later, Synopses were once again summarized and explained in a set of documents called Apocalypses and Exegeses. All these papers are available today at http://design.perl6.org, but again, they are not the final specification of the language, only a collection of historical documents.
Another important idea about Perl 6 was about the way compilers are created. In Perl 5, the language rules are indirectly defined by the single available compiler. Some bugs, or not obvious behavior of the compiler, may be considered as part of the language standard. In Perl 6, it was decided to have a clear language specification, and no reference compiler. There can be more than one compiler. The main requirement for them is implementing the specification and passing the set of tests.
Let's briefly look at some of the changes that happened on the way to Perl 6. In the following sections, you will see a few examples of code in Perl 5 and 6. They are intended for a general understanding of how Perl 5 transforms to Perl 6, but you are not expected to understand every bit of it. All the details about the syntax of Perl 6 will be explained later in this book.
Perl 6 has a long history and many documents were created during that time, for instance, language ideas, draft specifications, and compiler documentation. Many enthusiasts wrote articles and blog posts about Perl 6. Some of that is outdated and does not reflect the current state of the language. In this chapter, I will give you a brief list of materials that are up-to-date and that you should use in your practice of working with Perl 6.
The main entry point for documentation of the Perl 6 programming language is the Documentation section of Perl 6's site (http://docs.perl6.org). It contains a few sections with a comprehensive description of the types, operators, and built-in classes that are available in Perl 6. As the language is still developing, you may sometimes find places in the documentation where it does not reflect the current state of the language. In this case, you may consult the community of language developers or check the files from the test suite.
Perl 6's test suite, called Roast, can be found in the repository at https://github.com/perl6/roast. It contains thousands of tests covering many corners of Perl 6. The test suite is also a good place to look if you want to see ways you can write programs in Perl 6. It may be a long read sometimes, but many tests are checking the features from all possible angles.
In Roast, the tests are grouped in directories with names such as S32-io. These names correspond to the numbers of the Synopses, and are split into thematic sections. For example, for the Synopses 11 'Compilation Units', there exist three directories in tests—S11-compunits, S11-modules, and S11-repository.
STD.pm is a huge file describing the formal Perl 6 grammar. The grammar of Perl 6 is written in Perl 6 itself. The repository of https://github.com/perl6/std contains the grammar and the viv utility that translates the grammar into the Perl 5 code. We have mentioned the STD.pm grammar because it may be interesting for those readers who want to dig deeper into the internal structure of the grammar. In the rest of this book, we will explain the grammar based on examples of code in Perl 6.
The developers of Perl 6 traditionally use IRC for communication. You may also join the #perl6 channel to ask questions about the language or execute a piece of Perl 6 online.
To join the channel, follow the instructions listed on the https://perl6.org/community/ page.
If you want to run the code in IRC, refer to the rakudo bot as follows:
<me> rakudo: say "Hello, World!"<+camelia> rakudo-moar cb8fa0: OUTPUT: «Hello, World!»
In the output, you can see that Rakudo is using the MoarVM backend by default. The string that was printed by the program is displayed after the OUTPUT keyword.
Use this feature carefully as the result of your requests will be visible to the whole room and also be logged. The best use case is to show the behavior of the compiler when you find a bug or when you see a different result from what is said in the documentation. The Perl 6 developers are always present in the IRC channel and will advise on what is wrong or will aim to fix the bug and make the documentation correct.
If you are on Facebook, visit the Perl 6 group here:https://www.facebook.com/groups/1595443877388632/
In the offline, you will see many people who love Perl 6 at various conferences. Go to the Perl Conference (previously known as YAPC, (Yet Another Perl Conference)), which is held every year in Europe and in the USA. You may find more about them on http://theperlconference.org and http://www.yapc.eu. For many years, there were work Perl booths at the big open-source conferences like OSCON and FOSDEM. There are also many local conferences, workshops, and local group meetings. Find the closest group to your location at http://pm.org.
During the process of Perl 6 development, a number of compilers were created. Some of them were just a playground to test some ideas, whereas some were more mature. Among the most important, we should mention the following four projects:
Parrot
Pugs
Perlito
Rakudo
There were more attempts to create a Perl 6 compiler, which were less successful or less complete. We will go through the preceding list to see the highlights of each project and then focus on Rakudo, which is the compiler you should use today.
Parrot is the first virtual machine aimed to be the base of the Perl 6 compiler. The initial design of the language suggested that the source code is compiled to the bytecode, which is executed by the virtual machine. Parrot's goal was to create a virtual machine suitable for handling all the needs of Perl 6 from simple data types, such as integers, to more complicated structures, such as classes, with the ability to call methods on objects and follow the object hierarchy.
The project is available at parrot.org. After some time, Parrot started supporting other programming languages, such as Lua or Python, and the virtual machine became less focused on Perl 6 itself. For example, the Ponie project was an attempt to create a compiler that would execute Perl 5 programs using Parrot.
Parrot became one of the virtual machines inside another project, Rakudo. However, before we go to Rakudo, let's follow the historical path and talk about Pugs.
Pugs (Perl User's Golfing System) is a Perl 6 compiler written in Haskell. It was started in 2005 by a sole developer and soon attracted more people to the team. Pugs was the most sophisticated compiler of its time. It was difficult and very time consuming to compile the project, the execution speed was low, but the quality of the compilation and the coverage of Perl 6 specification were outstanding.
Pugs main role in Perl 6 as of today is the vast test suite. It was created to test Pugs itself, but turned out to be an official test suite for Perl 6. A compiler that claims to call itself a Perl 6 compiler must pass the test suite tests.
Pugs are not developing anymore, but its source code is available on GitHub at https://github.com/perl6/Pugs.hs.
Perlito is another very interesting example of a project of building a Perl 6 compiler. It was aimed at cross-compiling Perl 5 or Perl 6 to one of these languages—JavaScript, Java, Go, Python, Ruby, or Lisp. You can find the project's repository at https://github.com/fglock/Perlito.
Perlito offers a web interface to compile the subset of Perl 6 in the browser. It compiles the code in Perl 6 to JavaScript and executes it immediately. This page is available at http://fglock.github.io/Perlito/perlito/perlito6.html. This project covers the Perl 6 specification only partially, but it may still be used to create various online educational systems for both Perl 5 and 6.
Rakudo is a compiler initially built on the Parrot virtual machine. Later, it started using the Java Virtual Machine (JVM), but in the end, the developers of Parrot created their own virtual machine, MoarVM (Metamodel on a Runtime Virtual Machine (www.moarvm.org)). Currently, the support of JVM is limited, and the main virtual machine is MoarVM.
Rakudo itself is a Perl 6 compiler. For us, the most useful compiler is Rakudo Star, which is a distribution including the compiler as well as a number of Perl 6 modules and a few command-line tools, such as a module installer. In this book, we will use the Rakudo Star compiler to run programs in Perl 6.
Rakudo's website is rakudo.org.
Rakudo is the most complete compiler available today. It supports the biggest subset of the Perl 6 language, and it would not be a mistake to say that Rakudo is the only compiler you should use to learn Perl 6.
There are a few ways of installing Rakudo Star on your computer. You can either download the source code and compile it or download an installer for your platform. Rakudo Star is available for all major platforms, namely, Windows (both 32- and 64-bit versions), Mac OS X, and Linux.
The main download page of Rakudo Star is http://perl6.org/downloads. On that page, you will find links to the latest versions of the Rakudo Star distributions for different platforms and instructions on how to install them.
On Windows, the process is extremely simple. Just download the most recent version of the MSI installer, run it, and follow the instructions.
On Mac OS X, you either download a .dmg installer, or use the brew manager, as shown here:
$ brew install rakudo-star
On Linux, you have to install Rakudo Star from the source files.
After you have installed Rakudo Star, you will find the perl6 executable file in its bin directory. Make sure to add the path to that directory to your system-wide PATH variable so that you can type perl6 from any location.
In the rest of this book, we will assume that Rakudo Star is installed, and we will use the perl6 executable to run programs.
The Perl 6 compiler of Rakudo Star accepts a few command-line options. Let's take a look at some of them.
The -c command-line checks the syntax of the program and exits. It also runs the BEGIN and CHECK blocks in the program, which are discussed in the section Phasers of Chapter 2, Writing Code later in this book. This command-line option is useful if you only want to check that there are no syntax errors in the code and don't want to execute it, with the exception being the code in the BEGIN and CHECK code blocks.
In the case of correct programming, it prints the following output:
Syntax OK
If there were compile-time errors, the compilation will stop at the first error and will display it on the console, mentioning the line number where it found an error.
The error message contains the description of the error and indicates the exact place in the code with the help of the eject character (). If your console supports colors, the fragment of the code before the eject character is green, and the rest of the line is red.
Here is an example of a program that misses the closing quote for the string:
say "Hello;
Run it to check the syntax, as shown here:
$ perl6 -c err.pl
The program did not compile, and this is what the compiler prints:
===SORRY!=== Error while compiling /Users/ash/code/err.pl Unable to parse expression in double quotes; couldn't find final '"' at /Users/ash/code/err.pl:2 ------> <BOL><EOL> expecting any of: argument list double quotes term
The --doc (notice the double hyphen) command-line extracts the documentation from the program and prints it. Here, the so-called Pod documentation is meant. We will cover the Pod syntax in Chapter2, Writing Code.
Let's see the small program that includes the documentation inside itself:
=begin pod =head1 Hello, World program =item This program prints "Hello, World!" =end pod say "Hello, World!";
Run it with the --doc command-line option as follows:
$ perl6 --doc pod.pl
It will print only parts of the documentation. The code itself will not be executed:
Hello, World program * This program prints "Hello, World!"
The -e option allows you to pass the whole program in a command line. This is useful for short programs that do a few actions or, for example, for small tests when you check how things work in Perl 6.
Run it with the program enclosed in quotes:
$ perl6 -e'say "Hello"'
And this is the result you will see:
Hello
The -h and --help commands print the text with a list of available command-line options.
The -n command-line option creates a loop so that the program is executed once for every line of the text submitted to the input of the program.
It may be, for example, a one-line utility that prints the first letter of the strings from the STDIN input:
perl6 -n -e'print $_.substr(0, 1)' < file.txt
It will print the line composed from the first characters of the lines in file.txt.
The -p command-line option acts like the previously described -n option, but it also prints the value of the default variable $_ at the end of each line. We will see the meaning of the default variable in the following chapters.
The -I and -M options are used to load modules into the program. The module's name is passed to the -M option and if necessary, the path to the module should be passed in the -I option.
The -v and --version options print the version of the current Perl 6 compiler as follows:
$ perl6 -v
At the time of writing, I am using Rakudo Star version 2017.01, and this is what the output looks like:
This is Rakudo version 2017.01 built on MoarVM version 2017.01 implementing Perl 6.c.
The important thing here, apart from the version itself, is the virtual machine that is used to execute Perl 6 (MoarVM, as shown earlier) and the version of the Perl 6 language specification (it is 6.c in this example).
The Rakudo Star versioning scheme uses the year and the month of the release date of the distributive. Rakudo is rapidly developing, so check the rakudo.org site regularly to get updates.
The --stagestats is a command-line option that is more Rakudo-specific than the others we have described earlier. It prints the time spent by the compiler at different stages of compiling and executing the program.
The output differs depending on whether you are running a program or checking its syntax with the -c command-line option. Let's first take a look at what is printed when the -c option is used:
$ perl6 --stagestats -c hello.pl
The output is as follows:
Stage start : 0.000 Stage parse : 0.107 Stage syntaxcheck: Syntax OK
Without the -c option, you will see more statistics, because the program will not only be compiled but also executed, as shown here:
$ perl6 --stagestats hello.pl
The regular output of the program is printed:
Stage start : 0.000 Stage parse : 0.327 Stage syntaxcheck: 0.000 Stage ast : 0.000 Stage optimize : 0.003 Stage mast : 0.008 Stage mbc : 0.000 Stage moar : 0.000 Hello, World!
So far, as we have installed the Rakudo Star compiler, it's now time to create the first program in Perl 6. It will print Hello, World! and exit.
The program is really easy. All you need is a single line with the only instruction to call the built-in say function. It takes the string, prints it to the console, and adds a new line after it.
This is how the whole program looks:
say 'Hello, World!'
Save the code to the file, say, hello.pl, and pass it to the compiler as follows:
$ perl6 hello.pl
It will compile the program and immediately execute it. The result is the desired string on the screen:
Hello, World!
Notice that the output ends with a new line. This is the behavior of the built-in say function. Alternatively, we could use another method of printing the output, using the print built-in function. Unlike say
