Perl6 Camelia

Perl6, get your test environment running in seconds

So you want to give a try to Perl6 to see what this language can do for you, but you don’t want to mess up your system with a lot of software you don’t know if will ever use again. No problem! The obvious answer is called Docker.

In another post I’ve already talked about how to run Perl inside a Docker container and the process here is the same: just pick the right image from the public registry and run your code.
But if you want to know something more about the advantages of using Docker containerization please jump there and read the post. You can come back here later.

Now, having a running Docker environment, here’s all the magic:

docker run --rm rakudo-star perl6 -v

This will instruct Docker to download the official Rakudo Star image, which currently provides Perl 6.d with MoarVM, and then displays the Perl version we are effectively running. If you’re asking, the image is based on Debian Stretch and contains also Perl 5.24.

Read a YAML file with Perl6

Now, to get this post a little longer so that Google will like it, I will try to do something useful with the container we just set up: we will read a simple YAML file, I will call it test.yml.

- animal: dog
  color: brown
- animal: cat
  color: white

Very nice!
To parse a YAML file in Perl6 we will need a library and I will use this wrapper round the libYAML library and this must be installed in our container.
So, to make things reusable, I will write a small Dockerfile to install the system library and then the package using Perl6’s zef package manager.

FROM rakudo-star:latest

RUN apt-get update && \
  apt-get install -y libyaml-dev && \
  zef install https://github.com/yaml/yaml-perl6.git

Very simple (when you know what to do)!
Now it’s time to build our image so we can use it later.

docker build -f Dockerfile -t perl6-yaml .

Now we have everything we need and we can write our small script, i will call it yaml.pl6

#!/usr/bin/perl6

use v6;
use YAML;

die if not @*ARGS[0];

try {
  my $doc = yaml.load(@*ARGS[0].IO.slurp);
  say "The $doc[1]{'animal'} is $doc[1]{'color'}";
  CATCH {
    default {
      say "No file in @*ARGS[0]";
    }
  }
}

If you are wondering what the hell is written there: after the shebang and the “use” keywords you already know from Perl I check the first command line argument (line 6).
Then I add the IO role to the string object and slurp the file, passing it YAML loader getting a YAML object that contains an array of YAML documents, even if in our case we have only one document.
On row 10 I write out some data.
And I surrounded everything in a try block, so that if the file does not exists we can warn the user with a nice message.

The last step is to run our staff using our Docker image. I will mount a folder inside the container to have access to my files.

docker run --rm -v /home/caribe/test:/mnt perl6-yaml perl6 /mnt/yaml.pl6 /mnt/test.yml

Awesome!