Perl 6 IRL (In Real Life)

A couple of weeks ago a ran into a real life situation where Perl 6 was able to greatly simplify my life. I was in the process of importing some Canadian postal codes from a PDF document where the data was presented like this:

A0A-A0R,D13
A1A-A1G,D11
A1H-A1M,D13
A1N,D11
A1S-A8A,D13
B0C-B0E,D11
B0H-B0W,D10
B1A-B2E,D11
B2G-B2H,D10

Each postal code, or postal code range, was tied to a zone. To store this to a database, I wanted to expand out each of these ranges to capture each value. Causing the first line to be represented as:

A0A => D13
A0B => D13
A0C => D13
... some more ...
A0R => D13

Using the Perl 5.12 range operator (..) I thought I could use easily accomplish this goal.

#!/usr/bin/perl

use strict;
use warnings FATAL => 'all';

use Perl6::Slurp;

my $file = 'data.csv';
my $data = slurp $file;

for my $line (split /\n/, $data) {
  my ($range, $zone) = split(/\,/, $line);
  if ($range =~ m/\-/) {
    my ($beg, $end) = split (/\-/, $range);
    for ($beg .. $end) {
      print "zone $_\n";
    }
  }
}

Unfortunately, Perl 5.12 doesn't recognize A0A through A0R as a valid range.  Causing this script to output only the first element of each range.

Then realizing that this problem wasn't as easy to solve, I suddenly remembered a presentation I saw at OSCON 2009 by Damien Conway on the current state of Perl 6 and how the new range operator was much more clever than its predecessor. So, I downloaded a copy of Rakudo, and re-wrote the same script using Perl 6.

use v6;
my $file = 'data.csv';
my @rows = slurp($file).split(/\n/);
for @rows -> $row {
  my ($range, $zone) = $row.split(/\,/);
  if ($range ~~ /\-/) {
    my ($beg, $end) = $range.split(/\-/);
    for ($beg .. $end) {
      say "$_ : $zone";
    }
  }
  else {
    say "$range : $zone";
   }
}

Perfect! Exactly what I was hoping for! Thanks Perl 6! I look forward to finding more uses for Perl 6 in my daily routine...

Disclaimer: I had done some previous reading of Perl 6 before writing this script, so the learning curve was minimal. If you are interested in Perl 6 I strongly recommend this book (not yet completed, but a great resource).

Leave a comment

About Jonathan Lloyd

user-pic I blog about Perl.