Main Content

Classes and object - first steps in Perl 6

Archive - Originally posted on "The Horse's Mouth" - 2016-01-02 20:56:28 - Graham Ellis

Perl 6 has a full object and class implementation ... first simple example [here]. Classes are defined with a class keyword, instance variables with a haskeyword, and methods with a method keyword. There's no "public", "protected", "private" wording, but subsidiary sigils (twigils) ... an extra "." providing an automatic accessor, and an extra "!" making a variable visible only within the object - i.e. private.

Here's a class definition:

  class trainservice {
    has $.length;
    has $.seatsPerCarriage;
    has $.time;
    has $.destination;
  
    method passengers {
      ($.length * $.seatsPerCarriage * 1.4).floor;
    }
  }


It's all a very long way from defining classes and objects in Perl 5 - showing that Perl 6 really is a new language, but you can spot similarities with the block structure, with sigils, and with defaults like functions returning the result of the last operation. There's also a default constructor which blesses a hash of the named parameters passed in (so under the bonnet, there's quite a bit more there from Perl 5.

Here's a test program to make use of that class:

  our $south = trainservice.new(length=>3, seatsPerCarriage=>78, time=>"06:38", destination=>"Southampton");
  our $north = trainservice.new(length=>2, seatsPerCarriage=>75, time=>"07:19", destination=>"Cheltenham Spa");
  
  my @services = ($south, $north);
  
  for @services -> $service {
    say $service.time ~ " to " ~ $service.destination ~ " takes up to " ~ $service.passengers ~ " people";;
    }


This is only a starter for what you can do with objects in Perl 6 - you 'll have interitance, static and factory methods, overloaded (with multi) and overridden methods. You have multiple inheritance (which I hope you don't use too often) and roles which are rather akin to interfaces allowing you to define abstract classes. As you can see, it's probably worth coming along and spending a day or two with us on Perl 6 training, even if you're familiar with Perl 5 ...