Day 18 – ABC Module

Day 18 – ABC Module

Instead of focusing on a particular feature of Perl 6 today, I’d like to take you on a quick tour of the ABC module. I think it’s a nice example of some of the strengths of Perl 6.

ABC Notation is a simple text file format designed to make it easy to support musical notation. It’s widely used in the world of traditional dance music because it is very lightweight and more than powerful enough to support notating jigs and reels. Here’s an example in honor of the season:

T:While Shepherds Watched Their Flocks
O:Green's Harbour, Newfoundland
K:A major
E|:[M:5/4] A A/B/ B2 A|B c/B/ A2 A/B/|
[M:6/4]c d/c/ B2 B2|[M:4/4] A3 E|AB AG|
FE FE|AB AG|F2 F2|E2 G2|A/G/ F/E/ DF|
[1 [M:6/4] E C/B,/ A,3 E:|[2 [M:5/4] E C/B,/ A,3|]

I won’t get into the details — here’s a tutorial if you’d like to know more — but the structure of the file is simple. The first section is the header, with general information about the tune. The remainder is the tune itself. This one is a bit more complicated than many because of all the embedded time signature changes, like [M:6/4].

I was always surprised there wasn’t a CPAN module for handling ABC notation, and even seriously considered writing one myself at one point. But parsing ABC is a complicated process, and I gave up in frustration before getting very far.

Enter Perl 6 and its grammars. About 60 lines of simple regexes is all that is needed to parse most of the tunes I am interested in. (Several of the more complicated features of ABC, like lyrics and multi-staff music are not implemented yet.) Here’s a snatch of it:

    regex basenote { <[a..g]+[A..G]> }
    regex octave { "'"+ | ","+ }
    regex accidental { '^' | '^^' | '_' | '__' | '=' }
    regex pitch { <accidental>? <basenote> <octave>? }

Compare that to the model BNF grammar for ABC:

basenote ::= %x43 / %x44 / %x45 / %x46 / %x47 / %x41 / %x42 / %x63 / %x64 / %x65 / %x66 / %x67 / %x61 / %x62 ; CDEFGABcdefgab
octave ::= 1*"'" / 1*"," 
accidental ::= "^" / "^^" / "_" / "__" / "=" 
pitch ::= [accidental] basenote [octave]

It’s clearly a very straightforward translation process.

By default, parsing with a Perl 6 grammar just gives you a basic Match object. Adding an object to specify actions to go with the grammar allows you to easily process the information as it is parsed. A simple example is

    method rest($/) {

Whenever the rest regex fires, it returns a new ABC::Rest object. The constructor is passed the string form of the rest_type regex, and an ABC::Duration object created by the action for note_length.

Speaking of durations, another feature of Perl 6 comes very handy here. Durations are represented exactly using the rational number Rat type. If we didn’t have them available, we’d have to code up something similar by hand in order to handle things like triplets whose durations cannot be exactly represented by a floating point number.

So far there is only one significant application using these tools — the script included in the ABC module. It converts ABC files to the Lilypond music notation format. Lilypond is a very powerful open source music notation system which produces gorgeous sheet music output. This is a great way to print out good looking music notation from ABC files. (I know there is an abc2ly program included with Lilypond, but last time I checked its output looked tragically bad. is already working well enough that I’m hoping to produce a book of sheet music using it in 2011.) So let me leave you with the PDF of the above carol, produced using these tools, Rakudo Perl 6, and Lilypond.

Day 17 – Rosetta Code

Day 17 – Rosetta Code

Do you know what a program chrestomathy is? How about a phrasebook? Or a cribsheet? What about the Rosetta Stone? is much like any of those, though it focuses primarily on programming languages. It’s organized as hundreds of ‘tasks’, which are roughly problem statements, and each task is shown with implementations in many languages.

The gist? Let’s say you know how to do something in language A, and want to see how to do it in language B. By comparing A and B across enough problems, you will start to get a feel for language B’s syntax, and how it relates to the language you’ve come from. Then you’ll notice recurring design patterns and behaviors–the language’s idioms. You’ll be able to see where these are similar to habits you already have, and you’ll be able to see where your existing habits might be get in your way.

Enough preamble. Allow me to direct your attention to a specific places on the site. The topic here isn’t Rosetta Code, really, but how it can help you with Perl 6.

First, there’s a list of all tasks on Rosetta Code which have Perl 6 implementations. Here are a few examples:

Of course, we can’t talk about these kinds of lists of programs without touching on some classics, can we?

As I write this, there are 243 examples of Perl 6 code on the site. If I were to link to all the cases I think you might find interesting, this post would be a link-bomb of amazing proportion. However, allow me to throw one more link at you.

I’ve already given you a link to an index of all 243 of the existing Perl 6 code on the site. As I write this, though, there are 449 tasks. If you’d like to fill in some of the gap…

Day 16: Time in Perl6

Day 16: Time in Perl6

It’s the 0x10th day of Christmas, and it’s time for you to learn of time. The synopsis S32::Temporal has been heavily revised in the past year, and today’s post details some of the basics of time as it is implemented in Perl 6.

time and now

The two terms that give the current time (at least what your system thinks is the current time) are time; and now. Here’s a quick example:
> say time; say now;

The first (obvious) difference is that time returns POSIX time, as an integer. now returns an object known as an Instant. Use now if  you want fractions of a second and recognition of leap seconds. time won’t give you fractions of a second or leap seconds, because it returns POSIX time. Which one you use all depends on what you need.

DateTime and friend

Most of the time, you will want to store dates other than now. For this, the DateTime object is what you need. If you want to store the current time, you can use:

my $moment =; # or

Otherwise, there are two ways of creating a DateTime object:

my $dw =, :month(11), :day(23), :hour(17), :minute(15));

This is in UTC, if you want to enter it in in another timezone, use the :timezone adverb. Here, only :year is required, the rest defaults to midnight on January 1 of the year.

This way is also pretty tedious. You could instead create a DateTime object by inputting an ISO 8601 timestamp, as a string.

my $dw ="1963-11-23T17:15:00Z");

The Z denotes UTC. To change that, replace Z with +hhmm or -hhmm, where ‘hh’ is the number of hours offset and ‘mm’ the number of minutes.

There is also a Date object, which is created in a similar way, but without hours, minutes, or seconds. For example:

my $jfk ="1963-11-22"); # you can also use :year and so on

The introduction of the Date object is actually a lesson from CPAN’s DateTime module: sometimes you want to treat days without having to worry about things like time zones and leap seconds. It’s inherently easier to handle pure dates. For example Date has built-in .succ and .pred methods, so you can increment and decrement them in your code.

$jfk++; # Day after JFK


That’s about it for Time in P6. To see all the gritty details go to the Temporal specification or ask about it in the community!

Day 15 – Calling native libraries from Perl 6

Day 15 – Calling native libraries from Perl 6

If you’ve used Perl 5 for any length of time, you’ve probably encountered a package with “::XS” in the name. Maybe you’ve even written one, in which case you can skip this paragraph. XS is Perl 5’s way of calling into native code (C libraries), and it works great for what it does. Writing such modules takes effort though; there’s C code and compilers involved, and it’s not much fun if you just want to get something working with a minimum of effort.

Perl 6 puts a lot of effort into letting you be lazy. That goes for using foreign code too. Let’s tell it we’re going to do that:

#!/usr/bin/env perl6
use v6;
use NativeCall;

That’s it. NativeCall does the hard work of talking to C libraries; you don’t need to manually compile anything. For Rakudo, you just need to install zavolaj.

Let’s have some fun with it. For demonstration, I’ll go and port part 1 of XMMS2’s C client tutorial to Perl 6.

First off, NativeCall needs to know how to talk to the C library. At present it knows how to translate to/from strings, numbers, and a thing called OpaquePointer. That last one is for things like database connection handles that you should only poke with a 10-foot pole.

We’re dealing with weird structs and a socket connection in this code, so let’s pretend those are subclasses of OpaquePointer. These don’t have any effect on the code, but it’ll be easier to follow:

class xmmsc_connection_t is OpaquePointer;
class xmmsc_result_t is OpaquePointer;
class xmmsv_t is OpaquePointer;

Now the C functions we’re using, in alphabetical order. One of these is slightly different from the rest – the original C code expects a **char to be passed in, or in other words a place in memory to write a string. We give it a Str is rw, and it just works.

sub xmmsc_connect(xmmsc_connection_t, Str $path) returns Int is native('libxmmsclient') { ... }
sub xmmsc_get_last_error(xmmsc_connection_t) returns Str is native('libxmmsclient') { ... }
sub xmmsc_init(Str $clientname) returns xmmsc_connection_t is native('libxmmsclient') { ... }
sub xmmsc_playback_start(xmmsc_connection_t) returns xmmsc_result_t is native('libxmmsclient') { ... }
sub xmmsc_result_get_value(xmmsc_result_t) returns xmmsv_t is native('libxmmsclient') { ... }
sub xmmsc_result_unref(xmmsc_result_t) is native('libxmmsclient') { ... }
sub xmmsc_result_wait(xmmsc_result_t) is native('libxmmsclient') { ... }
sub xmmsc_unref(xmmsc_connection_t) is native('libxmmsclient') { ... }
sub xmmsv_get_error(xmmsv_t, Str $error is rw) returns Int is native('libxmmsclient') { ... }
sub xmmsv_is_error(xmmsv_t) returns Int is native('libxmmsclient') { ... }

And because the point of this is to *avoid* writing C code, let’s make a nice wrapper object:

class XMMS2::Client {
    has xmmsc_connection_t $!connection;
    method new($client_name = 'perl6', $path = %*ENV) {
        self.bless(*, :$client_name, :$path);
    method play returns Bool {
        my $result = xmmsc_playback_start($!connection);
        return True if self.check-result($result);
        warn "Playback start failed!"; return False;
    method !check-result(xmmsc_result_t $result) returns Bool {
        my $return_value = xmmsc_result_get_value($result);
        my Bool $failed = xmmsv_is_error($return_value);
        if $failed {
            xmmsv_get_error($return_value, my $error-str) and warn $error-str;
        return not $failed;
    submethod BUILD($client_name, $path) {
        $!connection = xmmsc_init($client_name);
        xmmsc_connect($!connection, $path) or die "Connection failed with error: {xmmsc_get_last_error($!connection)}";
    submethod DESTROY {

And here’s the magic part:;

It connects! Then it spits out a Null PMC error. Looks like some work still needs to be done in NativeCall for passing null pointers around, but it’s still a work in progress.

NativeCall has been put to good use already though: check out
MiniDBI, which gives you a (working!) MySQL driver, among others. :)

(Late edit: I forgot the xmmsc_result_wait(). The above code should actually start playback now, though you’ll still get the Null PMC access error.)

Day 14 – nextsame and its cousins

Day 14 – nextsame and its cousins

Maybe you’re familiar with the way the keyword super in Java allows you to delegate to the method (or constructor) of a base class. Perl 6 has something similar… but in a world with multiple inheritance and mixins it makes less sense to call it super. So it’s called nextsame. Here’s an example of its use:

class A {
    method sing {
        say "life is but a dream.";

class B is A {
    method sing {
        say ("merrily," xx 4).join(" ");

class C is B {
    method sing {
        say "row, row, row your boat,";
        say "gently down the stream.";

Now, when we call, our class hierarchy will output this:

row, row, row your boat,
gently down the stream.
merrily, merrily, merrily, merrily,
life is but a dream.

You’ll note how the call finds its way from C.sing via B.sing over to A.sing. Those transitions are (of course) mediated by the nextsame calls. You’ll note the similarity to, for example, Java’s super.

But calling along the inheritance chain is not the only place where nextsame proves useful. Here’s an example not involving object orientation:

sub bray {
    say "EE-I-EE-I-OO.";

# Oh right, forgot to add the first line of the song...
&bray.wrap( {
    say "Old MacDonald had a farm,";
} );

bray(); # Old MacDonald had a farm,
        # EE-I-EE-I-OO.

So that’s another reason nextsame is not called super: it’s not necessarily related to the base class, because there might not be a base class. Instead, there’s some more general phenomenon involved. What might that be?

Every time we do a call to something, there’s a part of the language runtime making sure that the call ends up in the right routine. Such a part is called a dispatcher. A dispatcher makes sure that the following multi call ends up in the appropriate routine:

multi foo(    $x) { say "Any argument" }
multi foo(Int $x) { say "Int argument" }

foo(42) # Int argument

(And a nextsame in the second multi foo would re-dispatch to the first. But that doesn’t work in Rakudo yet.)

Dispatchers are everywhere in Perl 6. They’re involved in method calls, so that a method can defer along the inheritance chain, as we did in the beginning of the post. They’re in wrapped routines, so that the code doing the wrapping can call into the code being wrapped. And they participate in multi dispatch, so that multi variants can defer to each other. It’s all the same principle, but in different guises.

And nextsame is just a way to talk directly to your friendly neighborhood dispatcher. By the way, the keyword is called nextsame because it instructs the dispatcher to defer to the next candidate with the same signature. There are variants, as you’ll see below.

You can use nextsame in mixins, too:

class A {
    method foo { "OH HAI" }

role LogFoo {
    method foo {
        note ".foo was called";

my $logged_A = but LogFoo;

say $; # .foo was called
                   # OH HAI

I like this way to use mixins to inject behavior. I once wrote a post about it, and jnthn has written a Perl 6 module that exploits it.

Though pretty cool, this use of nextsame isn’t really anything new; in fact it’s just another example of the defer-along-the-OO-callchain dispatcher. That’s because mixing in the role LogFoo with but causes an anonymous subclass to be created, one that also does LogFoo. So role mixin nextsame boils down to just inheritance nextsame. (But we don’t need to actually grok that to use it, and it still feels slightly magical and very nice to use.)

In summary, nextsame works in a lot of places you’d expect it to work, and it works the way you expect it to. It defers to the next thing.

Oh, and nextsame has three closely related cousin keywords:

nextsame             Defer with the same arguments, don't return
callsame             Defer with the same arguments, then  return

nextwith($p1, $p2, ...) Defer with these arguments, don't return
callwith($p1, $p2, ...) Defer with these arguments, then  return

Naturally, the other three can be used in the same situations nextsame can.

Day 13 – The Perl6 Community

Day 13 – The Perl6 Community

Today is the halfway point of the Perl 6 Advent Calendar (and indeed any advent calendar). For 12 days you have learned various nuggets of information, and most likely experimented with those various bits of knowledge. You feel great, wonderful, stuff works!

And then it didn’t work.

You may have found your way to some documentation (available at by the way), and potentially even some talk of Real People™ out there ready to help you. Whatever you’ve done, today’s post is given to you to display the two main methods of helping in the Perl 6 Universe.

The Mailing Lists

The first of two major communication channels is the mailing lists. If you head on over to, you can see on the right hand side a list of the several lists you can subscribe to/peruse the archives of. If you have question s about the language, such as “How do I add up all the numers in an array without a loop?”, go for perl6-users. The mailing list is great for those who can’t use IRC or want more permanent discussions. Have an idea for the language? Try perl6-language, where people discuss the language itself. Things like “I think there should be a beat-object-with-catfish operator in the language” go here.

Now, the mailing lists aren’t the only option. Your question could be simple-when-you-know-it, or maybe that feature you really really want is already there! For these reasons, you may want to run your comments by the IRC community.

The #perl6 IRC channel

If you want to use something more instantaneous instead, or you hate the idea of signing up to a mailing list for one question, head over to the channel #perl6 on Here, the community is reputed as being one of the nicest on the Internet (so if you’ve been burned by IRC channels before and vowed “Never again shall I use IRC!”, try #perl6.)

#perl6 is like an eccentric incarnation of The Doctor, multifaceted in its nature. We have punfests, technotalk, lolz, above-your-head language design, and more (thanks sorear for reminding me of that)! So come and ask away!

Final Words

These are the two ways of communication in the Perl 6 universe. There are also blogs, screencasts, and more. Go to to check it all out!

Day 12 – Smart matching

Day 12 – Smart matching

Remember the sequence operator? As the last argument it takes a limit, which makes the sequence generation stop. For example:

    1, 2, 4 ... 32;         # 1 2 4 8 16 32
    1, 2, 4 ... * > 10;     # 1 2 4 8 16

You can see that in the first case, numerical equality is used. The second is a bit more interesting: * > 10 is internally rewritten into a closure like -> $x { $x > 10 } (through currying).

The sequence operator then does some magic comparison, depending on the type of the matcher. This comparison is called "smartmatching", and is a concept that reappears in many places in Perl 6. Examples:

    # after the 'when' keyword:
    given $age {
        when 100    { say "congratulations!"      }
        when * < 18 { say "You're not of age yet" }
    # after 'where':
    subset Even of Int where * %% 2;
    # with an explicit smartmatch operator:
    if $input ~~ m/^\d+$/ {
        say "$input is an integer";
    # arguments to grep(), first() etc.:
    my @even = @numbers.grep: Even;

On the right-hand side of the ~~ operator, and after when and where, the value to be matched against is set to the topic variable $_. This allows us to use constructs that operate on $_, like regexes created with m/.../ and .method_call.

Here is what the smart match operator does with some matchers on the right-hand side:

    # is it of type Str?
    $foo ~~ Str
    # is it equal to 6?
    $foo ~~ 6
    # or is it "bar"?
    $foo ~~ "bar"
    # does it match some pattern?
    $foo ~~ / \w+ '-' \d+ /
    # Is it between 15 and 25?
    $foo ~~ (15..25)
    # call a closure
    $foo ~~ -> $x { say 'ok' if 5 < $x < 25 }
    # is it an array of 6 elems in which every odd element is 1?
    $foo ~~ [1, *, 1, *, 1, *]

The full table for smart matching behavior can be found at

Notice how, unlike in Perl 5, in Perl 6 smartmatching is the only syntactic way to match a regex, it has no special operator. Also, while most smart matching cases return a Bool, matching against a regex returns a Match object – which behaves appropriately in boolean context too.

You have probably started wondering: a’right, that for built-in types, how do I use it in my own classes? You need to write a special ACCEPTS method for it. Say we have our good, old class Point:

    class Point {
        has $.x;
        has $.y;
        method ACCEPTS(Positional $p2) {
            return $.x == $p2[0] and $.y == $p2[1]

Everything clear? Let’s see how it works:

    my $a = => 7, y => 9);
    say [3, 5] ~~ $a; # Bool::False
    say (7, 9) ~~ $a; # Bool::True

Perl 6 can now do exactly what you mean, even with your own classes.