First day with Perl 6 – UK postcode grammar

Today I decided to install and play around with Perl 6. It’s the developing version of Perl that is meant to replace Perl 5 in the future. It’s still under very heavy development, and is not ready for general use, but I thought I’d give it a quick look. Perl 6 is not backwards compatible, which means that if you’re used to writing things in Perl 5 you’re in for a shock.

I decided a good first test of something to write would be a UK postcode parser/validator in order to try out something new to Perl 6, or at least to me: grammars.

Grammars are basically a way of relating several rules or regexes to each other in specific ways. By the way, you can’t call Perl 6 regexes “regular expressions” any more because they’re apparently not regular enough.

After a bit of playing around I actually managed to get the following code working:

grammar postcode {
  regex TOP {
    <outcode> ' ' <incode>

  regex outcode {

  regex incode {

my @postcodes = 'WC1N 2PL', 'NG18 3JL', 'L1 4DJ', 'GIR 0AA';

for @postcodes -> $postcode {
  print "$postcode: ";
  if postcode.parse($postcode) {
    say 'Yes!';
  } else {
    say 'No!';

I think that the few examples I’ve put in there represent the vast majority of postcodes out there, including certain London-style postcodes and the GiroBank postcode (GIR 0AA). If you want to play around with this then you can just add extra postcodes to the array and they’ll be iterated over in the for loop.

There are a couple of interesting differences in the syntax of the Perl above compared to Perl 5. The if and for statements have no parentheses around the condition. This is because parentheses directly after a word represent a subroutine. Also, to use a different variable as the iterator in a for loop you now use the -> construct after the array name (or range, or whatever you’re looping over).

There are loads of other differences, but I haven’t really had much of a chance to play with them properly.

So far I’m liking Perl 6 a lot. 🙂