Categories
Posts in this category
- Current State of Exceptions in Rakudo and Perl 6
- Meet DBIish, a Perl 6 Database Interface
- doc.perl6.org and p6doc
- Exceptions Grant Report for May 2012
- Exceptions Grant Report -- Final update
- Perl 6 Hackathon in Oslo: Be Prepared!
- Localization for Exception Messages
- News in the Rakudo 2012.05 release
- News in the Rakudo 2012.06 release
- Perl 6 Hackathon in Oslo: Report From The First Day
- Perl 6 Hackathon in Oslo: Report From The Second Day
- Quo Vadis Perl?
- Rakudo Hack: Dynamic Export Lists
- SQLite support for DBIish
- Stop The Rewrites!
- Upcoming Perl 6 Hackathon in Oslo, Norway
- A small regex optimization for NQP and Rakudo
- Pattern Matching and Unpacking
- Rakudo's Abstract Syntax Tree
- The REPL trick
- First day at YAPC::Europe 2013 in Kiev
- YAPC Europe 2013 Day 2
- YAPC Europe 2013 Day 3
- A new Perl 6 community server - call for funding
- New Perl 6 community server now live, accepting signups
- A new Perl 6 community server - update
- All Perl 6 modules in a box
- doc.perl6.org: some stats, future directions
- Profiling Perl 6 code on IRC
- Why is it hard to write a compiler for Perl 6?
- Writing docs helps you take the user's perspective
- Perl 6 Advent Calendar 2016 -- Call for Authors
- Perl 6 By Example: Running Rakudo
- Perl 6 By Example: Formatting a Sudoku Puzzle
- Perl 6 By Example: Testing the Say Function
- Perl 6 By Example: Testing the Timestamp Converter
- Perl 6 By Example: Datetime Conversion for the Command Line
- What is Perl 6?
- Perl 6 By Example, Another Perl 6 Book
- Perl 6 By Example: Silent Cron, a Cron Wrapper
- Perl 6 By Example: Testing Silent Cron
- Perl 6 By Example: Stateful Silent Cron
- Perl 6 By Example: Perl 6 Review
- Perl 6 By Example: Parsing INI files
- Perl 6 By Example: Improved INI Parsing with Grammars
- Perl 6 By Example: Generating Good Parse Errors from a Parser
- Perl 6 By Example: A File and Directory Usage Graph
- Perl 6 By Example: Functional Refactorings for Directory Visualization Code
- Perl 6 By Example: A Unicode Search Tool
- What's a Variable, Exactly?
- Perl 6 By Example: Plotting using Matplotlib and Inline::Python
- Perl 6 By Example: Stacked Plots with Matplotlib
- Perl 6 By Example: Idiomatic Use of Inline::Python
- Perl 6 By Example: Now "Perl 6 Fundamentals"
- Perl 6 Books Landscape in June 2017
- Living on the (b)leading edge
- The Loss of Name and Orientation
- Perl 6 Fundamentals Now Available for Purchase
- My Ten Years of Perl 6
- Perl 6 Coding Contest 2019: Seeking Task Makers
- A shiny perl6.org site
- Creating an entry point for newcomers
- An offer for software developers: free IRC logging
- Sprixel, a 6 compiler powered by JavaScript
- Announcing try.rakudo.org, an interactive Perl 6 shell in your browser
- Another perl6.org iteration
- Blackjack and Perl 6
- Why I commit Crud to the Perl 6 Test Suite
- This Week's Contribution to Perl 6 Week 5: Implement Str.trans
- This Week's Contribution to Perl 6
- This Week's Contribution to Perl 6 Week 8: Implement $*ARGFILES for Rakudo
- This Week's Contribution to Perl 6 Week 6: Improve Book markup
- This Week's Contribution to Perl 6 Week 2: Fix up a test
- This Week's Contribution to Perl 6 Week 9: Implement Hash.pick for Rakudo
- This Week's Contribution to Perl 6 Week 11: Improve an error message for Hyper Operators
- This Week's Contribution to Perl 6 - Lottery Intermission
- This Week's Contribution to Perl 6 Week 3: Write supporting code for the MAIN sub
- This Week's Contribution to Perl 6 Week 1: A website for proto
- This Week's Contribution to Perl 6 Week 4: Implement :samecase for .subst
- This Week's Contribution to Perl 6 Week 10: Implement samespace for Rakudo
- This Week's Contribution to Perl 6 Week 7: Implement try.rakudo.org
- What is the "Cool" class in Perl 6?
- Report from the Perl 6 Hackathon in Copenhagen
- Custom operators in Rakudo
- A Perl 6 Date Module
- Defined Behaviour with Undefined Values
- Dissecting the "Starry obfu"
- The case for distributed version control systems
- Perl 6: Failing Softly with Unthrown Exceptions
- Perl 6 Compiler Feature Matrix
- The first Perl 6 module on CPAN
- A Foray into Perl 5 land
- Gabor: Keep going
- First Grant Report: Structured Error Messages
- Second Grant Report: Structured Error Messages
- Third Grant Report: Structured Error Messages
- Fourth Grant Report: Structured Error Messages
- Google Summer of Code Mentor Recap
- How core is core?
- How fast is Rakudo's "nom" branch?
- Building a Huffman Tree With Rakudo
- Immutable Sigils and Context
- Is Perl 6 really Perl?
- Mini-Challenge: Write Your Prisoner's Dilemma Strategy
- List.classify
- Longest Palindrome by Regex
- Perl 6: Lost in Wonderland
- Lots of momentum in the Perl 6 community
- Monetize Perl 6?
- Musings on Rakudo's spectest chart
- My first executable from Perl 6
- My first YAPC - YAPC::EU 2010 in Pisa
- Trying to implement new operators - failed
- Programming Languages Are Not Zero Sum
- Perl 6 notes from February 2011
- Notes from the YAPC::EU 2010 Rakudo hackathon
- Let's build an object
- Perl 6 is optimized for fun
- How to get a parse tree for a Perl 6 Program
- Pascal's Triangle in Perl 6
- Perl 6 in 2009
- Perl 6 in 2010
- Perl 6 in 2011 - A Retrospection
- Perl 6 ticket life cycle
- The Perl Survey and Perl 6
- The Perl 6 Advent Calendar
- Perl 6 Questions on Perlmonks
- Physical modeling with Math::Model and Perl 6
- How to Plot a Segment of a Circle with SVG
- Results from the Prisoner's Dilemma Challenge
- Protected Attributes Make No Sense
- Publicity for Perl 6
- PVC - Perl 6 Vocabulary Coach
- Fixing Rakudo Memory Leaks
- Rakudo architectural overview
- Rakudo Rocks
- Rakudo "star" announced
- My personal "I want a PONIE" wish list for Rakudo Star
- Rakudo's rough edges
- Rats and other pets
- The Real World Strikes Back - or why you shouldn't forbid stuff just because you think it's wrong
- Releasing Rakudo made easy
- Set Phasers to Stun!
- Starry Perl 6 obfu
- Recent Perl 6 Developments August 2008
- The State of Regex Modifiers in Rakudo
- Strings and Buffers
- Subroutines vs. Methods - Differences and Commonalities
- A SVG plotting adventure
- A Syntax Highlighter for Perl 6
- Test Suite Reorganization: How to move tests
- The Happiness of Design Convergence
- Thoughts on masak's Perl 6 Coding Contest
- The Three-Fold Function of the Smart Match Operator
- Perl 6 Tidings from September and October 2008
- Perl 6 Tidings for November 2008
- Perl 6 Tidings from December 2008
- Perl 6 Tidings from January 2009
- Perl 6 Tidings from February 2009
- Perl 6 Tidings from March 2009
- Perl 6 Tidings from April 2009
- Perl 6 Tidings from May 2009
- Perl 6 Tidings from May 2009 (second iteration)
- Perl 6 Tidings from June 2009
- Perl 6 Tidings from August 2009
- Perl 6 Tidings from October 2009
- Timeline for a syntax change in Perl 6
- Visualizing match trees
- Want to write shiny SVG graphics with Perl 6? Port Scruffy!
- We write a Perl 6 book for you
- When we reach 100% we did something wrong
- Where Rakudo Lives Now
- Why Rakudo needs NQP
- Why was the Perl 6 Advent Calendar such a Success?
- What you can write in Perl 6 today
- Why you don't need the Y combinator in Perl 6
- You are good enough!
Sun, 22 Jan 2017
Perl 6 By Example: Perl 6 Review
Permanent link
This blog post is part of my ongoing project to write a book about Perl 6.
If you're interested, either in this book project or any other Perl 6 book news, please sign up for the mailing list at the bottom of the article, or here. It will be low volume (less than an email per month, on average).
In the previous "Perl 6 by Example" blog posts we've discussed some examples interleaved with the Perl 6 mechanics that make them work. Here I want to summarize and deepen the Perl 6 knowledge that we've touched on so far, removed from the original examples.
Variables and Scoping
In Perl 6, variable names are made of a sigil, $
, @
, %
or &
,
followed by an identifier. The sigil implies a type constraint, where $
is
the most general one (no restriction by default), @
is for arrays, %
for
hashes (associative arrays/maps), and &
for code objects.
Identifiers can contain -
and '
characters, as long as the character after
it is a letter. Identifiers must start with a letter or underscore.
Subroutines and variables declared with my
are lexically scoped. They are
visible from the point of the declaration to the end of the current
{}
-enclosed block (or the current file, in case the declaration is outside a
block). Subroutine parameters are visible in the signature and block of the
subroutine.
An optional twigil between the sigil and identifier can influence the
scoping. The *
twigil marks a dynamically scoped variable, thus lookup is
performed in the current call stack. !
marks attributes, that is,
a per-instance variable that's attached to an object.
Subroutines
A subroutine, or short sub, is a piece of code with its own scope and usually also a name. It has a signature which specifies what kind of values you have to pass in when you call it:
sub chunks(Str $s, Int $chars) {
# ^^^^^^^^^^^^^^^^^^^^ signature
# ^^^^^^ name
gather for 0 .. $s.chars / $chars - 1 -> $idx {
take substr($s, $idx * $chars, $chars);
}
}
The variables used in the signature are called parameters, whereas we call the values that you pass in arguments.
To refer to a subroutine without calling it, put an ampersand character in front of it, for example
say &chunks.^name; # Sub
to call it, simply use its name, followed by the list of arguments, which can optionally be in parentheses:
say chunks 'abcd', 2; # (ab cd)
say chunks('abcd', 2); # (ab cd)
You only need the parentheses if some other construct would otherwise interfere with the subroutine call. For example if you intend to write
say chunks(join('x', 'ab', 'c'), 2);
and you leave out the inner pair of parentheses:
say chunks(join 'x', 'ab', 'c', 2);
then all the arguments go to the join
function, leaving only one argument to the
chunks
function. On the other hand it is fine to leave out the outer pair of
parentheses and write
say chunks join('x', 'ab', 'c'), 2;
because there's no ambiguity here.
One case worth noting is that if you call a subroutine without arguments as the
block of an if
condition or a for
loop (or similar constructs), you have
to include the parentheses, because otherwise the block is parsed as an
argument to the function.
sub random-choice() {
Bool.pick;
}
# right way:
if random-choice() {
say 'You were lucky.';
}
# wrong way:
if random-choice {
say 'You were lucky.';
}
If you do happen to make this mistake, the Perl 6 compiler tries very hard to detect it. In the example above, it says
Function 'random-choice' needs parens to avoid gobbling block
and when it tries to parse the block for the if
-statement, it doesn't find
one:
Missing block (apparently claimed by 'random-choice')
When you have a sub called MAIN
, Perl 6 uses its signature to parse the
command line arguments and pass those command line arguments to MAIN
.
multi subs are several subroutines with the same name but different signatures. The compiler decides at run time which of the candidates it calls based on the best match between arguments and parameters.
Classes and Objects
Class declarations follow the same syntactic schema as subroutine
declarations: the keyword class
, followed by the name, followed by the body
in curly braces:
class OutputCapture {
has @!lines;
method print(\s) {
@!lines.push(s);
}
method captured() {
@!lines.join;
}
}
By default, type names are scoped to the current namespace, however you can make
it lexically scoped by adding a my
in front of class
:
my class OutputCapture { ... }
Creating a new instance generally works by calling the new
method on the
type object. The new
method is inherited from the implicit parent class
Any
that all types get:
my $c = OutputCapture.new;
Per-instance state is stored in attributes, which are declared with the
has
keyword, as seen above in has @!lines
. Attributes are always private,
as indicated by the !
twigil. If you use the dot .
twigil in the
declaration instead, you have both the private attribute @!lines
and a
public, read-only accessor method:
my class OutputCapture {
has @.lines;
method print(\s) {
# the private name with ! still works
@!lines.push(s);
}
method captured() {
@!lines.join;
}
}
my $c = OutputCapture.new;
$c.print('42');
# use the `lines` accessor method:
say $c.lines; # [42]
When you declare attributes with the dot twigil, you can also initialize the
attributes from the constructor through named arguments, as in
OutputCapture.new( lines => [42] )
.
Private methods start with a !
and can only be called from inside the class
body as self!private-method
.
Methods are basically just subroutines, with two differences. The first is
that they get an implicit parameter called self
, which contains the object
the method is called on (which we call the invocant). The second is that
if you call a subroutine, the compiler searches for this subroutine in the
current lexical scope, and outer scopes. On the other hand, the methods for
a method calls are looked up in the class of the object and its
superclasses.
Concurrency
Perl 6 provides high-level primitives for concurrency and parallel execution.
Instead of explicitly spawning new threads, you are encouraged to run a
computation with start
, which returns a
Promise. This is an object that
promises that in the future the computation will yield a result. The status
can thus be Planned
, Kept
or Broken
. You can chain promises, combine
them, and wait for them.
In the background, a scheduler distributes such computations to operating system level threads. The default scheduler is a thread pool scheduler with an upper limit to the number of threads to use.
Communication between parallel computations should happen through thread-safe
data structures. Foremost among them are the
Channel, a thread-safe queue, and
Supply, Perl 6's implementation of the
Observer Pattern. Supplies
are very powerful, because you can transform them with methods such as map
,
grep
, throttle
or delayed
, and use their actor
semantic to ensure that a
consumer is run in only one thread at a time.