BUY THIS BOOK
Add to Cart

Print Book $29.95


Safari Books Online

What is this?

Add to UK Cart

Print Book £20.95

What is this?

Looking to Reprint this content?


Perl 6 and Parrot Essentials
Perl 6 and Parrot Essentials, Second Edition

By Allison Randal, Dan Sugalski, Leopold Tötsch
Price: $29.95 USD
£20.95 GBP

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Project Overview
Perl 6 is the next major version of Perl. It's a complete rewrite of the interpreter, and a significant update of the language itself. The goal of Perl 6 is to add support for much-needed new features, and still be cleaner, faster, and easier to use.
The Perl 6 project is vast and complex, but it isn't complicated. The project runs on a simple structure with very little management overhead. That's really the only way it could run. The project doesn't have huge cash or time resources. Its only resource is the people who believe in the project enough to spend their off-hours—their "relaxation" time—working to see it completed. This chapter is as much about people as it is about Perl.
Back on July 18, 2000, the second day of the fourth Perl Conference (TPC 4), a small band of Perl geeks gathered to prepare for a meeting of the Perl 5 Porters later that day. The topic at hand was the current state of the Perl community. Four months had passed since the 5.6.0 release of Perl, and although it introduced some important features, none were revolutionary.
There had been very little forward movement in the previous year. It was generally acknowledged that the Perl 5 codebase had grown difficult to maintain. At the same time, infighting on the perl5-porters list had grown so intense that some of the best developers decided to leave. It was time for a change, but no one was quite sure what to do. They started conservatively with plans to change the organization of Perl development.
An hour into the discussion, around the time most people nod off in any meeting, Jon Orwant (the reserved, universally respected editor of the Perl Journal) stepped quietly into the room and snapped everyone to attention with an entirely uncharacteristic and well-planned gesture. Smash! A coffee mug hit the wall. "We are *@$!-ed (Crash!) unless we can come up with something that will excite the community (Pow!), because everyone's getting bored and going off and doing other things! (Bam!)" (At least, that's basically how Larry tells it. As is usually the case with events like this, no one remembers exactly what Jon said.)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Birth of Perl 6
Back on July 18, 2000, the second day of the fourth Perl Conference (TPC 4), a small band of Perl geeks gathered to prepare for a meeting of the Perl 5 Porters later that day. The topic at hand was the current state of the Perl community. Four months had passed since the 5.6.0 release of Perl, and although it introduced some important features, none were revolutionary.
There had been very little forward movement in the previous year. It was generally acknowledged that the Perl 5 codebase had grown difficult to maintain. At the same time, infighting on the perl5-porters list had grown so intense that some of the best developers decided to leave. It was time for a change, but no one was quite sure what to do. They started conservatively with plans to change the organization of Perl development.
An hour into the discussion, around the time most people nod off in any meeting, Jon Orwant (the reserved, universally respected editor of the Perl Journal) stepped quietly into the room and snapped everyone to attention with an entirely uncharacteristic and well-planned gesture. Smash! A coffee mug hit the wall. "We are *@$!-ed (Crash!) unless we can come up with something that will excite the community (Pow!), because everyone's getting bored and going off and doing other things! (Bam!)" (At least, that's basically how Larry tells it. As is usually the case with events like this, no one remembers exactly what Jon said.)
Awakened by this display, the group started to search for a real solution. The language needed room to grow. It needed the freedom to evaluate new features without the obscuring weight of legacy code. The community needed something to believe in, something to get excited about.
Within a few hours the group settled on Perl 6, a complete rewrite of Perl. The plan wasn't just a language change, just an implementation change, or just a social change. It was a paradigm shift. Perl 6 would be the community's rewrite of Perl, and the community's rewrite of itself.
Would Perl 6, particularly Perl 6 as a complete rewrite, have happened without this meeting? Almost certainly. The signs appeared on the lists, in conferences, and in journals months in advance. If it hadn't started that day, it would have happened a week later, or perhaps a few months later, but it would have happened. It was a step the community needed to take.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
In the Beginning . . .
Let's pause and consider Perl development up to that fateful meeting. Perl 6 is just another link in the chain. The motivations behind it and the directions it will take are partially guided by history.
Perl was first developed in 1987 by Larry Wall while he was working as a programmer for Unisys. After creating a configuration and monitoring system for a network that spanned the two American coasts, he was faced with the task of assembling usable reports from log files scattered across the network. The available tools simply weren't up to the job. A linguist at heart, Larry set out to create his own programming language, which he called perl. He released the first version of Perl on December 18, 1987. He made it freely available on Usenet (this was before the Internet took over the world, remember), and quickly a community of Perl programmers grew.
The early adopters of Perl were system administrators who had hit the wall with shell scripting, awk, and sed. However, in the mid-1990s Perl's audience exploded with the advent of the Web, as Perl was tailor-made for CGI scripting and other web-related programming.
Meantime, the Perl language itself kept growing, as Larry and others kept adding new features. Probably the most revolutionary change in Perl (until Perl 6, of course) was the addition of modules and object-oriented programming with Perl 5. Although this made the transition period from Perl 4 to Perl 5 unusually long, it breathed new life into the language by providing a modern, modular interface. Before Perl 5, Perl was considered simply a scripting language; after Perl 5, it was considered a full-fledged programming language.
Larry, meanwhile, started taking a back seat to Perl development and allowed others to take responsibility for adding new features and fixing bugs in Perl. The Perl 5 Porters (p5p) mailing list became the central clearinghouse for bug reports and proposed changes to the Perl language, with the "pumpkin holder" (also known as the "pumpking") being the programmer responsible for integrating the patches and distributing them to the rest of the list for review. Larry continued to follow Perl development, but like a parent determined not to smother his children, he stayed out of the day-to-day development, limiting his involvement to situations in which he was truly needed.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Continuing Mission
Much has changed since the early days of the project. New people join and others leave in a regular "changing of the guard" pattern. Plans change as the work progresses, and the demands of the work and the needs of the community become clearer. Today the Perl 6 project has two major parts: language design and internals. Each branch is relatively autonomous, though there is a healthy amount of coordination between them.
As with all things Perl, the central command of the language design process is Larry Wall, the creator of the Perl language. Larry is supported by the rest of the design team: Damian Conway, Allison Randal, Dan Sugalski, Hugo van der Sanden, and chromatic. We speak in weekly teleconferences and also meet face-to-face a few times a year to hash out ideas for the design documents, or to work through roadblocks standing in the way of design or implementation. The design team is a diverse group, including programmers-for-hire, Perl trainers, and linguists with a broad spectrum of interests and experiences. This diversity has proved quite valuable in the design process, as each member is able to see problems in the design or potential solutions that the other members missed.

Section 1.3.1.1: Requests For Comments (RFCs)

The first step in designing the new language was the RFC (Request For Comments) process. This spurred an initial burst of community involvement. Anyone was free to submit an RFC on any subject, whether it was as small as adding an operator, or as big as reworking OO syntax. Most of the proposals were really quite conservative. The RFCs followed a standard format so they would be easier to read and easier to compare.
Each RFC was subject to peer review, carried out in an intense few weeks around October 2000. One thing the RFC process demonstrated was that the Perl community still wasn't quite ready to move beyond the infighting that had characterized Perl 5 Porters earlier that year. Even though few RFCs have been accepted without modification, the process identified a large number of irritants in the language. These have served as signposts for later design efforts.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Project Development
The Perl community is rich and diverse. There are as many variations in skill sets and skill levels as there are people. Some are coders, some are testers, some are writers, some are teachers, some are theorists. For every skill, there is a task. It's the combination of all the skills that gets the job done. A team of workers all wielding hammers could never build a house. Someone has to cut the wood, sand it, apply plaster, paint it, and install windows, doors, electrical systems, and plumbing.
Theoretically, language design is the driving force behind all other parts of the project. In actual practice, Parrot development frequently affects the direction and focus of design efforts. A design that gave no consideration to what can be implemented efficiently wouldn't be much use. Equally, if the design work followed a strictly linear path, it would be a waste of developer resources. The Parrot project can't afford to go on hold every time they need information from a future area of design. For example, long before the design of OO syntax was completed, the design team took time to define enough of the required semantics so that development could move ahead.
Design work goes in cycles. Each cycle begins with a quiet period. During this time, the list traffic is fairly light, and Larry is rarely seen. It can seem as if the project is stalled, but in fact, this part of the cycle is where the bulk of original design work is done. Larry disappears when he's working on an Apocalypse. It's the most intense and creative phase.
The next phase is internal revision. Larry sends a draft of the Apocalypse to the design team for comments and makes changes based on their suggestions. Sometimes the changes are as simple as typo fixes, but sometimes they entirely alter the shape of the design. Larry repeats this several times before publishing the document. This is a very fast-paced and dynamic phase, but again, low on visible results.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Language Development
Theoretically, language design is the driving force behind all other parts of the project. In actual practice, Parrot development frequently affects the direction and focus of design efforts. A design that gave no consideration to what can be implemented efficiently wouldn't be much use. Equally, if the design work followed a strictly linear path, it would be a waste of developer resources. The Parrot project can't afford to go on hold every time they need information from a future area of design. For example, long before the design of OO syntax was completed, the design team took time to define enough of the required semantics so that development could move ahead.
Design work goes in cycles. Each cycle begins with a quiet period. During this time, the list traffic is fairly light, and Larry is rarely seen. It can seem as if the project is stalled, but in fact, this part of the cycle is where the bulk of original design work is done. Larry disappears when he's working on an Apocalypse. It's the most intense and creative phase.
The next phase is internal revision. Larry sends a draft of the Apocalypse to the design team for comments and makes changes based on their suggestions. Sometimes the changes are as simple as typo fixes, but sometimes they entirely alter the shape of the design. Larry repeats this several times before publishing the document. This is a very fast-paced and dynamic phase, but again, low on visible results.
Next is the community review. Usually the first day or two after an Apocalypse comes out are quiet, while the ideas soak in. Then the list begins to fly. Some people suggest changes, while others ask about the design. This phase reflects the most visible progress, but the changes are mostly refinements. The changes introduced at community review polish off the rough edges, add a few new tricks, or make simplifications for the average user. Here the community takes ownership of the design, as both the design and the people change until the two are a comfortable fit.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Parrot Development
Parrot development is the productive core of Perl 6 development. If you want coding action, this is the place to be.
Organization of the Parrot project is lightweight but efficient. It's a meritocracy—people who make valuable contributions are offered more responsibility. Communication is relaxed and informal. As Dan is so fond of saying, "This is far too important to take seriously." It's a bit like a special forces unit—the work gets done not because of tight control from the top, but because the whole team knows the task at hand and does it.
The cycles in Parrot development center on "point releases." A point release is a version change, such as 0.0.8 to 0.0.9. The pumpking decides when point releases happen and what features are included. Usually one or two solid new features trigger a release.
Development proceeds at a steady pace of bug reports, patches submitted, and patches applied. The pace isn't so much a result of careful planning as it is the law of averages—on any given day, someone, somewhere, is working on Parrot. A release is a spike in that activity, but since Parrot tends to follow the "release early, release often" strategy, the spike is relatively small.
Typically, the pumpking declares a feature freeze a few days before each release and all development efforts center on bug squashing. This periodic cleanup is one of the most valuable aspects of a release.
Just like design work, the first step to participating in Parrot development is joining the list. The topics on p6i tend to stick to practical matters: bug reports, patches, notifications of changes committed to CVS, and questions on coding style. Occasionally, there are discussions about how to implement a particular feature. Generally, if you have a question about syntax or a speculation about whether Perl 6 should support a particular feature, that question belongs on the language list rather than the internals list.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Design Philosophy
At the heart of every language is a core set of ideals that give the language its direction and purpose. If you really want to understand the choices that language designers make—why they choose one feature over another or one way of expressing a feature over another—the best place to start is with the reasoning behind the choices.
Perl 6 has a unique set of influences. It has deep roots in Unix and the children of Unix, which gives it a strong emphasis on utility and practicality. It's grounded in the academic pursuits of computer science and software engineering, which gives it a desire to solve problems the right way, not just the most expedient way. It's heavily steeped in the traditions of linguistics and anthropology, which gives it the goal of comfortable adaptation to human use. These influences and others like them define the shape of Perl and what it will become.
Perl is a human language. Now, there are significant differences between Perl and languages like English, French, German, etc. For one, it is artificially constructed, not naturally occurring. Its primary use, providing a set of instructions for a machine to follow, covers a limited range of human existence. Even so, Perl is a language humans use for communicating. Many of the same mental processes that go into speaking or writing are duplicated in writing code. The process of learning to use Perl is much like learning to speak a second language. The mental processes involved in reading are also relevant. Even though the primary audience of Perl code is a machine, humans have to read the code while they're writing, reviewing, or maintaining it.
Many Perl design decisions have been heavily influenced by the principles of natural language. The following are some of the most important principles, the ones we come back to over and over again while working on the design and the ones that have had the greatest impact.
The natural tendency in human languages is to keep overall complexity about equivalent, both from one language to the next, and over time as a language changes. Like a waterbed, if you push down the complexity in one part of the language, it increases complexity elsewhere. A language with a rich system of sounds (phonology) might compensate with a simpler syntax. A language with a limited sound system might have a complex way of building words from smaller pieces (morphology). No language is complex in every way, as that would be unusable. Likewise, no language is completely simple, as too few distinctions would render it useless. This principle might just as well be called the "Conservation of Complexity."
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Linguistic and Cognitive Considerations
Perl is a human language. Now, there are significant differences between Perl and languages like English, French, German, etc. For one, it is artificially constructed, not naturally occurring. Its primary use, providing a set of instructions for a machine to follow, covers a limited range of human existence. Even so, Perl is a language humans use for communicating. Many of the same mental processes that go into speaking or writing are duplicated in writing code. The process of learning to use Perl is much like learning to speak a second language. The mental processes involved in reading are also relevant. Even though the primary audience of Perl code is a machine, humans have to read the code while they're writing, reviewing, or maintaining it.
Many Perl design decisions have been heavily influenced by the principles of natural language. The following are some of the most important principles, the ones we come back to over and over again while working on the design and the ones that have had the greatest impact.
The natural tendency in human languages is to keep overall complexity about equivalent, both from one language to the next, and over time as a language changes. Like a waterbed, if you push down the complexity in one part of the language, it increases complexity elsewhere. A language with a rich system of sounds (phonology) might compensate with a simpler syntax. A language with a limited sound system might have a complex way of building words from smaller pieces (morphology). No language is complex in every way, as that would be unusable. Likewise, no language is completely simple, as too few distinctions would render it useless. This principle might just as well be called the "Conservation of Complexity."
The same is true of computer languages. They require a constant balance between complexity and simplicity. Restricting the possible operators to a small set leads to a proliferation of user-defined methods and subroutines. This is not a bad thing, in itself, but it encourages code that is verbose and difficult to read. On the other hand, a language with too many operators encourages code that is heavy in line noise and difficult to read. Somewhere in the middle lies the perfect balance.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Architectural Considerations
The second set of principles governs the overall architecture of Perl 6. These principles are connected to the past, present, and future of Perl, and define the fundamental purpose of Perl 6. No principle stands alone; each is balanced against the others.
Everyone agrees that Perl 6 should still be Perl, but the question is, what exactly does that mean? It doesn't mean Perl 6 will have exactly the same syntax. It doesn't mean Perl 6 will have exactly the same features. If it did, Perl 6 would just be Perl 5. So, the core of the question is what makes Perl "Perl?"

Section 3.2.1.1: True to the original purpose

Perl will stay true to its designer's original intended purpose. Larry wanted a language that would get the job done without getting in his way. The language had to be powerful enough to accomplish complex tasks, but still lightweight and flexible. As Larry is fond of saying, "Perl makes the easy things easy and the hard things possible." The fundamental design philosophy of Perl hasn't changed. In Perl 6, the easy things are a little easier and the hard things are more possible.

Section 3.2.1.2: Familiarity

Perl 6 will be familiar to Perl 5 users. The fundamental syntax is still the same. It's just a little cleaner and a little more consistent. The basic feature set is still the same. It adds some powerful features that will probably change the way we code in Perl, but they aren't required.
Learning Perl 6 will be like American English speakers learning Australian English, not English speakers learning Japanese. Sure, there are some vocabulary changes, and the tone is a little different, but it is still—without any doubt—English.

Section 3.2.1.3: Translatable

Perl 6 will be mechanically translatable from Perl 5. In the long term, this isn't nearly as important as what it will be like to write code in Perl 6. But during the transition phase, automatic translation will be important. It will allow developers to start moving ahead before they understand every subtle nuance of every change. Perl has always been about learning what you need now and learning more as you go.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Basic Syntax
Perl 6 is a work in progress, so the syntax is rapidly changing. The next four chapters are likely to be outdated by the time you read them. Even so, they provide a good baseline. If you start here, you'll only have to catch up on a few months of changes (starting with the design documents after Apocalypse 12), instead of several years worth.
Pretend for a moment that you don't know anything about Perl. You heard the language has some neat features, so you thought you might check it out. You go to the store and pick up a copy of Programming Perl because you think this Larry Wall guy might know something about it. It's the latest version, put out for the 6.0.1 release of Perl. It's not a delta document describing the changes, it's an introduction, and you dive in with the curiosity of a kid who got a telescope for his birthday. These chapters are a glimpse down that telescope.
There's plenty of time later to analyze each feature and decide which you like and which you don't. For now, take a step back and get a feel for the system as a whole, for what it'll be like to work in it.
The most basic building blocks of a programming language are its nouns, the chunks of data that get sucked in, pushed around, altered in various ways, and spat out to some new location. The chunks of data are values: strings, numbers, etc., or composites of the simpler values. Variables are just named containers for those values. The three kinds of variables in Perl 6 are scalars, arrays, and hashes. Each has an identifying symbol (or sigil) as part of the name of the variable: $ for scalars, @ for arrays, and % for hashes. The sigils provide a valuable visual distinction by making it immediately obvious what kinds of behavior a particular variable is likely to have. But, fundamentally, there's little difference between the three. Each variable is essentially a container for a value, whether that value is single or collective. (This statement is an oversimplification, as you'll soon see.)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variables
The most basic building blocks of a programming language are its nouns, the chunks of data that get sucked in, pushed around, altered in various ways, and spat out to some new location. The chunks of data are values: strings, numbers, etc., or composites of the simpler values. Variables are just named containers for those values. The three kinds of variables in Perl 6 are scalars, arrays, and hashes. Each has an identifying symbol (or sigil) as part of the name of the variable: $ for scalars, @ for arrays, and % for hashes. The sigils provide a valuable visual distinction by making it immediately obvious what kinds of behavior a particular variable is likely to have. But, fundamentally, there's little difference between the three. Each variable is essentially a container for a value, whether that value is single or collective. (This statement is an oversimplification, as you'll soon see.)
Scalars are all-purpose containers. They can hold strings, integers, floating-point numbers, and references to all kinds of objects and built-in types. For example:
$string = "Zaphod's just this guy, you know?";
$int = 42;
$float = 3.14159;
$arrayref = [ "Zaphod", "Ford", "Trillian" ];
$hashref = { "Zaphod" => 362, "Ford" => 1574, "Trillian" => 28 };
$subref = sub { print $string };
$object = Android.new;
A filehandle is just an ordinary object in an ordinary scalar variable. For example:
$filehandle = open $filename;
Array variables hold simple ordered collections of scalar values. Individual values are retrieved from the array by numeric index. The 0 index holds the first value. The @ sigil is part of the name of the variable and stays the same no matter how the variable is used:
@crew = ( "Zaphod", "Ford", "Trillian" );

$second_member = @crew[1]; # Ford
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Operators
Operators provide a simple syntax for manipulating values. A few characters take the place of a function call, or even several function calls. On the positive side this makes them incredibly convenient. On the negative side they're also sometimes difficult to learn because they pack so much meaning into a small space. Many of the Perl 6 operators will be familiar, especially to Perl 5 programmers. The new operators either add new features to the language, or move Perl's operator set toward a more consistent system.
The = operator is for ordinary assignment. It creates a copy of the values on the righthand side and assigns them to the variables or data structures on the lefthand side:
$copy = $original;
@copies = @originals;
$copy and $original both have the same value, and @copies has a copy of every element in @originals.
The := operator is for binding assignment. Instead of copying the value from one variable or structure to the other, it creates an alias. An alias is an additional entry in the symbol table with a different name for the one container:
$a := $b;  # $a and $b are aliases
@c := @d;  # @c and @d are aliases
In this example, any change to $a also changes $b and vice versa, because they're just two separate names for the same container. Binding assignment requires the same number of elements on both sides, so both of these would be an error:
# ($a, $b) := ($c);          # error
# ($a, $b) := ($c, $d, $e);  # error
The ::= operator is a variant of the binding operator that binds at compile time.
The arithmetic operators are addition (+), subtraction (
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Control Structures
The simplest flow of control is linear—one statement follows the next in a straight line to the end of the program. Since this is far too limiting for most development tasks, languages provide ways to alter the control flow.
Selection executes one set of actions out of many possible sets. The selection control structures are if, unless, and given/when.

Section 4.3.1.1: The if statement

The if statement checks a condition and executes its associated block only if that condition is true. The condition can be any expression that evaluates to a truth value. Parentheses around the condition are optional:
if $blue {
    print "True Blue.";
}
The if statement can also have an unlimited number of elsif statements that check additional conditions when the preceding conditions are false. The final else statement executes if all preceding if and elsif conditions are false:
if $blue {
    print "True Blue.";
} elsif $green {
    print "Green, green, green they say . . . ";
} else {
    print "Colorless green ideas sleep furiously.";
}

Section 4.3.1.2: The unless statement

The unless statement is the logical opposite of if. Its block executes only when the tested condition is false:
unless $fire {
    print "All's well.";
}
There is no elsunless statement, though else works with unless.

Section 4.3.1.3: The switch statement

The switch statement selects an action by comparing a given expression (the switch) to a series of when statements (the cases). When a case matches the switch, its block is executed:
given $bugblatter {
    when Beast::Trall { close_eyes( );  }
    when 'ravenous'   { toss('steak');   }
    when .feeding     { sneak_past( );  }
    when /grrr+/      { cover_ears( );  }
    when 2            { run_between( ); }
    when (3..10)      { run_away( );    }

}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Subroutines
Subroutines are reusable units of code. They can be called from just about anywhere, and return control to the point of the call when they finish executing. They can be passed zero or more arguments and return zero or more results. Subroutines can be named or anonymous. They can be lexically scoped, package scoped, or globally scoped. "Multi" subs allow multiple subroutines to have the same name as long as they have different parameter lists.
Methods are significantly different from subroutines. In Perl 6, they're even distinguished by a separate keyword, method. These differences will be discussed in Chapter 6.
The most basic subroutine declaration is simply the sub keyword, followed by the name of the sub, followed by the block that defines the sub:
sub alert {
    print "We have normality.";
}
The simplest subroutine call is just the subroutine name followed by a comma-separated list of variables or values:
$result = sum($a, $b, 42, 57);
Arguments are also sometimes passed as anonymous pairs:
$result = sum(first => 12, second => 21);
Parentheses are optional on calls to subroutines that have been predeclared, but required for all other calls. Including the & sigil before the subroutine name in a call will not turn off signature checking. In fact, in most contexts prefixing the subroutine name with & will return a reference to the subroutine instead of calling the subroutine.
One of the most significant additions to subroutines in Perl 6 is named formal parameters. The parameter list, often called the signature of the subroutine, is part of the subroutine declaration:
sub standardize ($text, $method) {
    my $clean;
    given $method {
        when 'length' { $clean = wrap($text, 72); }
        when 'lower'  { $clean = lowercase($text); }
         . . . 
    }
    return $clean;
}
The subroutine standardize
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using Subroutines
The most basic subroutine declaration is simply the sub keyword, followed by the name of the sub, followed by the block that defines the sub:
sub alert {
    print "We have normality.";
}
The simplest subroutine call is just the subroutine name followed by a comma-separated list of variables or values:
$result = sum($a, $b, 42, 57);
Arguments are also sometimes passed as anonymous pairs:
$result = sum(first => 12, second => 21);
Parentheses are optional on calls to subroutines that have been predeclared, but required for all other calls. Including the & sigil before the subroutine name in a call will not turn off signature checking. In fact, in most contexts prefixing the subroutine name with & will return a reference to the subroutine instead of calling the subroutine.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Parameters
One of the most significant additions to subroutines in Perl 6 is named formal parameters. The parameter list, often called the signature of the subroutine, is part of the subroutine declaration:
sub standardize ($text, $method) {
    my $clean;
    given $method {
        when 'length' { $clean = wrap($text, 72); }
        when 'lower'  { $clean = lowercase($text); }
         . . . 
    }
    return $clean;
}
The subroutine standardize has two scalar parameters, $text and $method, so it is called with two arguments, each a scalar value. The parameters are lexical variables within the body of the sub. They never need to be explicitly declared as my, even under use strict because they're declared by the subroutine declaration.
In a sub with no parameter list, all arguments are passed in the @_ array:
sub sum {
    my $sum;
    for @_ -> $number {
        $sum += $number;
    }
    return $sum;
}
Subroutines with defined parameter lists don't get an @_ array. If you want a subroutine that takes no arguments (and complains when arguments are passed), define it with an empty parameter list ( ).
Subroutine calls normally provide a nonflattening list context, which means that any array or hash passed into a subroutine is treated as a single argument. An array parameter in the signature expects to be passed an actual array or arrayref argument, and a hash parameter expects a hash or hashref argument:
sub whole (@names, %flags) {
     . . . 
}

whole(@array, %hash);
Every subroutine call checks its signature to make sure the arguments it gets match the declared parameter list. A mismatch in the number or kind of arguments is an error. But since requiring every declared parameter to be passed in on every call isn't nearly flexible enough for the average programmer, Perl 6 also allows optional parameters. Each optional parameter is marked with a ? before the parameter name:
sub someopt ($required1, $required2, ?$optional1, ?$optional2) {
     . . . 
}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Arguments
The standard way of passing arguments is by position. The first argument passed in goes to the first parameter, the second to the second, and so on:
sub matchparams ($first, $second) { . . . }

matchparams($one, $two);  # $one is bound to $first
                          # $two is bound to $second
You can also pass arguments in by name, using a list of anonymous pairs. The key of each pair gives the parameter's name and the value of the pair gives the value to be bound to the parameter. When passed by name, the arguments can come in any order. Optional parameters can be left out, even if they come in the middle of the parameter list. This is particularly useful for subroutines with a large number of optional parameters:
sub namedparams ($first, ?$second, ?$third is rw) { . . . }

namedparams(third => 'Trillian', first => $name);
Sometimes the option syntax for pairs is clearer than the pair constructor syntax:
namedparams :third('Trillian'), :first($name);
To get the Perl 5-style behavior where the elements of an array (or the pairs of a hash) flatten out into the parameter list, use the flattening operator in the call to the subroutine. Here, $first binds to @array[0] and $second binds to @array[1]:
sub flat ($first, $second) { . . . }

flat(*@array);
A flattened hash argument acts as a list of pairs, which are bound to the parameters just like ordinary named arguments. So, $first is bound to %hash{'first'}, and $second is bound to %hash{'second'}:
sub flat_hash ($first, $second) { . . . }


%hash = (first => 1, second => 2);
flat_hash(*%hash);
Flattened hash arguments are useful for building up hashes of named arguments to pass in all at once.
Arguments to subroutine calls have a standard general order. Positional arguments, if there are any, always go first. Named arguments go after any positional arguments. Variadic arguments always go at the end of the list.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Subroutine Stubs
To declare a subroutine without defining it you give it a body consisting of nothing but the . . . (or "yada, yada, yada") operator. So, all the preceding examples that look like pseudocode with { . . . } for their body are actually valid subroutine declarations.
sub stubbly (Str $name, Int ?$days) { . . . }
When you later define the subroutine, the signature and defined traits must exactly match the declaration.
sub stubbly (Str $name, Int ?$days) {
    print "$name hasn't shaved in $days day";
    print "s" if $days > 1;
}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Subroutine Scope
Just like variables, subroutine names are simply entries in a symbol table or lexical scratchpad. So, all subroutines live in a particular scope, whether it's lexical, package, or global scope.
Package scope is the default scope for subs. A sub that is declared without any scope marking is accessible within the module or class where it's defined with an unqualified call, like subname( ), and accessible elsewhere with a fully qualified call using the Package::Name::subname( ) syntax.
module My::Module {
  sub firstsub ($param) { . . . }

  sub secondsub {
    mysub('arg'); # call the subroutine
  }
}

module Other::Module {
  use My::Module;

  sub thirdsub {
     My::Module::firstsub('arg');
  }
}
This example declares two modules, My::Module and Other::Module. My::Module declares a subroutine firstsub and calls it from within secondsub. Other::Module declares a subroutine thirdsub that calls firstsub using its fully qualified name.
Subroutines can also be lexically scoped, just like variables. A myed subroutine makes an entry in the current lexical scratchpad with a & sigil. Lexically scoped subs are called just like a normal subroutine:
if $dining {
    my sub dine ($who, $where) {
         . . . 
    }

    dine($zaphod, "Milliways");
}

# dine($arthur, "Nutri-Matic");  # error
The first call to the lexically scoped dine is fine, but the second would be a compile-time error because dine doesn't exist in the outer scope.
The our keyword declares a lexically scoped alias to a package scoped subroutine (it has an entry both in the symbol table of the current package and in the current lexical scratchpad). This is useful under certain levels of strictness.
if $dining {
    our sub pay ($when, $what) {
         . . . 
    }

    pay($tuesday, "hamburger");
}
Globally scoped subroutines are visible everywhere, unless they're overridden by a lexical or package scoped subroutine of the same name. They are declared with the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Anonymous Subroutines
Anonymous subroutines do everything that ordinary subroutines do. They can declare a formal parameter list with optional and required parameters, take positional and named arguments, and do variadic slurping. The only difference is that they don't define a name. But since you can't call a subroutine if you have no way to refer to it, they have to get the equivalent of a name somewhere, whether they're assigned to a variable, passed as a parameter, or aliased to another subroutine.
$make_tea = sub ($tealeaves, ?$sugar, ?$milk) { . . . }
The arrow operator used with for and given is just another way of defining anonymous subroutines. The arrow doesn't require parentheses around its parameter list. It can't declare named subs, and can't declare a return type.
$make_tea = -> $tealeaves, ?$sugar, ?$milk { . . . }
A bare block can also define an anonymous subroutine, but it can't define a formal parameter list on the sub and can't define a named sub:
$make_tea = { 
    my $tea = boil 'tealeaves';
    combine $tea, 'sugar', 'milk';
}
You can't use the return statement within an arrow sub or bare block sub to return from an anonymous sub. Blocks and arrow subs are commonly used for ordinary control flow, so return ignores them and only returns from subroutines defined with sub keyword or methods.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Multi Subroutines
You can define multiple routines with the same name but different signatures. These are known as "multisubs" and are defined with the multi keyword before sub. They're useful if you want a routine that can handle different types of arguments in different ways, but still appear as a single subroutine to the user. For example, you might define an add multisub with different behavior for integers, floats, and certain types of numeric objects:
multi sub add (Int $first, Int $second) { . . . }
multi sub add (Num $first, Num $second) { . . . }
multi sub add (Imaginary $first, Imaginary $second) { . . . }
multi sub add (MyNum $first, MyNum $second) { . . . }
When you later call the routine:
add($apples, $oranges);
it will dispatch to the right version of add based on the types of the arguments passed to it. The parameters used for dispatch selection are called invocants. If you want to use a limited set of parameters as invocants, mark the boundary between invocant parameters and the rest of the signature with a semicolon:
multi sub add (Int $first, Int $second: Int $third) { . . . }
This version of add will dispatch based on the types of the first two arguments passed in, and ignore the type of the third.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Curried Subroutines
Currying allows you to create a shortcut for calling a subroutine with some preset parameter values. The assuming method takes a list of named arguments and returns a subroutine reference, with each of the named arguments bound to the original subroutine's parameter list. If you have a subroutine multiply that multiplies two numbers, you might create a subref $six_times that sets the value for the $multiplier parameter, so you can reuse it several times:
sub multiply ($multiplicand, $multiplier) {
    return $multiplicand * $multiplier;
}

$six_times = &multiply.assuming(multiplier => 6);

$six_times(9); # 54
$six_times(7); # 42
 . . .
You can also use binding assignment to alias a curried subroutine to an ordinary subroutine name instead of a scalar variable:
&six_times := &multiply.assuming(multiplier => 6);

six_times(7); # 42
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Wrapped Subroutines
Sometimes you might want to wrap extra functionality around a subroutine that was already defined (perhaps in a standard module), but still call it with the same name. The .wrap method is similar to the .assuming method, but more powerful. It takes a subroutine reference as an argument and returns an ID object. Inside the subref wrapper, the call statement marks the point where the original subroutine will be executed.
$id = &subname.wrap ({
    # preprocess arguments
    # or execute additional code
    call;
    # postprocess return value
    # or execute additional code
})

subname( . . . ); # call the wrapped subroutine
By default, the inner subroutine is passed the same arguments as the wrapping subroutine, and the wrapping subroutine returns the same result as the inner subroutine. You can alter the arguments passed to the inner subroutine by adding an explicit argument list to call, and alter the outer return value by capturing the result from call and explicitly returning a value in the wrapper.
$id = &subname.wrap (sub (*@args) {
    # preprocess arguments
    $result = call('modified', 'arguments');
    # postprocess return value
    return $result;
})
A subroutine can have multiple wrappers at the same time. Each new wrapper wraps around the previous one, and the outermost wrapper executes first. The ID object returned by .wrap allows the .unwrap method to remove a specific wrapper:
&subname.unwrap($id);
If you'd rather not manually unwrap your sub, wrap a temped version instead. The temp automatically removes the wrapper at the end of its scope.
{
  temp &subname.wrap ({ . . . })

  subname( . . . );
}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Lvalue Subroutines
Lvalue subroutines pretend to be assignable values, just like any ordinary variable. They do this by returning a proxy variable which handles the lvalue behavior for the subroutine (fetch, store, etc.). You declare an lvalue subroutine with the is rw property:
sub storage is rw { . . . }

storage( ) = 5;
An lvalue sub can return an ordinary variable which acts as a proxy, return the return value from another lvalue sub, or it can return a tied proxy variable defined within the sub:
my sub assignable is rw {
    my $proxy is Proxy(
        FETCH => { . . . },
        STORE => { . . . },
         . . . 
    );
    return $proxy;
}
This example defines an lvalue sub named assignable. It creates a proxy variable tied to a Proxy class that defines FETCH and STORE tie methods on the fly.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Macros
Macros are a powerful way of manipulating source code at compile time. Macr