Perl 6 Programming/Classes And Attributes

< Perl 6 Programming

Classes and Objects

What we've seen so far are the building blocks for procedural programming: Lists of expressions, branches, loops, and subroutines that tell the computer what job to do and exactly how to do it. Perl 6 supports procedural programming very well, but this isn't the only style of programming that Perl 6 supports. Another common paradigm that Perl 6 fits nicely is the object-oriented approach.

Objects are combinations of data and the operations that act on that data. The data of an object are called its fields or traits, and the operations of an object are called its methods.

Classes

Classes are defined using the class keyword, and are given a name:

class MyClass {

}

Inside that class declaration you can define traits, methods, or submethods.

Attributes

Attributes are defined with the has keyword, and are specified with a special syntax:

class MyClass {
   has $!x;
   has $!y;
}

The ! twigil specifies that this variable is an attribute on an object and not a regular variable.

Attributes are private, but you can easily add an accessor for it, that is a method of the same name that can be called from the outside of the class and returns the value of the attribute. These accessors are automatically generated for you if you declare the attribute with the . twigil instead:

class MyClass {
   has $.x;
   has $.y;
}

When you assign to an attribute from within the class, you still have to use the ! form.

Methods

Methods are defined just like normal subroutines except for a few key differences:

  1. Methods use the method keyword instead of sub.
  2. Methods have the special variable self, which refers to the object that the method is being called on. This is known as the invocant.
  3. Methods can access the internal traits of the object directly.

Here's an example:

class MyClass {
   has $.x;
   has $.y;

   method set($new_x, $new_y) {
      $!x = $new_x;
      $!y = $new_y;
   }

   method getMax() {
      if ($.x >= $.y) {
         return $.x;
      } else {
         return $.y;
      }
   }
}

When defining the method, you can specify a different name for the invocant, instead of having to use self. To do this, you put it at the beginning of the method's signature and separate it from the rest of the signature with a colon:

method myMethod($invocant: $x, $y)

In this context, the colon is treated like a special type of comma, so you could write it with additional whitespace if that was easier:

method myMethod($invocant  :  $x, $y)

Objects

Objects are data items whose type is a given class. Objects contain any trait fields that the class defines, and also has access to any methods in the class. Objects are created with the new keyword

my $foo = MyClass.new();

The class constructor, new() can take named methods used to initialize any of the class traits:

my $foo = MyClass.new(:x(7), :y(8));

Methods from that class are called using the dot notation. This is the object, a period, and the name of the method after that.

my $foo = Dog.new();
$foo.bark();
$foo.jump();

When an object isn't provided for dot notation method calls, the default variable $_ is used instead:

$_ = Dog.new();
.bark();
.jump();

Inheritance

Basic class systems enable data and the code routines that operate on that data to be bundled together in a logical way. However, there are more advanced features of most class systems that enable inheritance too, which allows classes to build upon one another. Inheritance is the ability for classes to form logical hierarchies. Perl 6 supports normal inheritance of classes and subclasses, but also supports special advanced features called mixins, and roles. We are going to have to reserve some of the more difficult of these features for later chapters, but we will introduce some of the basics here.

Basic Types

We've talked about a few of Perl's basic types in earlier chapters. It may surprise you to know that all Perl 6 data types are classes, and that all these values have built-in methods that can be used. Here we're going to talk about some of the methods that can be called on some of the various objects that we've seen so far.

.print and .say

We've already seen the print and say builtin functions. All built-in classes have methods of the same name that print a stringified form of the object.

.perl and eval

We're going to take a quick digression and talk about the eval function. eval lets us compile and execute a string of Perl 6 code at runtime.

eval("say 'hello world!';");

All Perl 6 objects have a method called .perl that returns a string of Perl 6 code representing that object.

my Int $x = 5;
$x.perl.say;          # "5"

my @y = (1, 2, 3);
@y.perl.say;          # "[1, 2, 3]"

my %z = :first(1), :second(2), :third(3);
%z.perl.say;          # "{:first(1), :second(2), :third(3)}"

Context and Coercion methods

There are a number of methods that can be called to explicitly change the given data item into a different form. This is like an explicit way to force the given data item to be taken in a different context. Here is a partial list:

.item
Returns the item in scalar context.
.iterator
Returns an iterator for the object. We'll talk about iterators in a later chapter.
.hash
Returns the object in hash context
.list
Returns the object in array or "list" context
.Bool
Returns the boolean value of the object
.Array
Returns an array containing the object data
.Hash
Returns a hash containing the object data
.Iterator
Returns an iterator for the object. We'll talk about iterators in a later chapter.
.Scalar
Returns a scalar reference to the object
.Str
Returns a string representation for the object

Introspection Methods

.WHENCE
Returns a code reference for the object types autovivification closure. We'll talk about autovivification and closures later.
.WHERE
Returns the memory location address of the data object
.WHICH
Returns the objects identity value, which for most objects is just it's memory location (it's .WHERE)
.HOW
(HOW = Higher Order Workings) Returns the meta class which handles this object
.WHAT
Returns the type object of the current object
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.