Reader small image

You're reading from  Perl 6 Deep Dive

Product typeBook
Published inSep 2017
Reading LevelIntermediate
PublisherPackt
ISBN-139781787282049
Edition1st Edition
Languages
Right arrow
Author (1)
Andrew Shitov
Andrew Shitov
author image
Andrew Shitov

Andrew Shitov has been a Perl enthusiast since the end of the 1990s, and is the organizer of over 30 Perl conferences in eight countries. He worked as a developer and CTO in leading web-development companies, such as Art. Lebedev Studio, Booking dotCom, and eBay, and he learned from the "Fathers of the Russian Internet", Artemy Lebedev and Anton Nossik. Andrew has been following the Perl 6 development since its beginning in 2000. He ran a blog dedicated to the language, published a series of articles in the Pragmatic Perl magazine, and gives talks about Perl 6 at various Perl events. In 2017, he published the Perl 6 at a Glance book by DeepText, which was the first book on Perl 6 published after the first stable release of the language specification.
Read more about Andrew Shitov

Right arrow

Object-Oriented Programming

Object-oriented programming (OOP) is one of the most required features in modern programming languages. In Perl 6, the approach of how previous versions of Perl worked with OOP was completely redesigned. In this chapter, we will learn about creating classes and working with objects in Perl 6. The following will be covered:

  • Creating a class
  • Class (read and write, public, private, state attributes)
  • Class methods (public and private methods)
  • Inheritance (inheriting from a class, overriding methods, submethods, multiple inheritance)
  • Roles
  • Introspection
  • Postfix method operators

Creating a class

In Perl 6, classes are an integral part of the language design. To create a class, use the class keyword. The body of the class, containing its definition, is placed between a pair of curly braces.

Let us start creating a program that uses classes. We'll start with an empty class for a house:

class House {
}

It can be a good practice to begin class names with capital letters. This also agrees with the convention used in Perl 6 itself. Its types are called in the same manner, compare

Int, Str, Array, and so on.

The preceding code declares a class House and defines its body. Currently, the body is empty, but already you can use this definition to create instances of that class (or, using other terms, create objects of that type).

To some extent, the terms class and type are interchangeable. For example, you can treat strings as instances of the Str class...

Working with attributes

In the previous section, we created the House class, which did not contain anything. Real houses do have some parameters, such as address, area in square meters, number of rooms, height, and so on. All that can be expressed using Perl 6.

Let us start adding the details to the class. We start with the most simple element, the number of rooms. This parameter can be described by an integer value that is attached to the object of the House type. In Perl 6, such data elements are called attributes and are declared with the has keyword, as shown in the following example:

class House {
has $.rooms;
}

What has been done here? The House class got an attribute $.rooms. This is a scalar value that belongs to the class object. Notice the dot after the dollar sigil. It is a twigil that describes the access level to the attribute; we will talk about it later in this...

Working with methods

In OOP, objects not only keep data, but also do some actions. In Perl 6, data is saved in attributes, and actions are done via methods.

Methods are like regular subs but defined inside a class. They can use the data from object attributes for their work.

Continue with the Address class from the previous sections. The details of the address are kept in separate attributes. This is good for creating a clean and structured representation but, in some cases, we need all data to be used together. For example, let's print a formatted address to put on an envelope:

class Address {
has Str $.housenumber;
has Str $.zipcode;
has Str $.country;
has Str $.town;
has Str $.street;
}

my $address = Address.new(
housenumber => '10',
zipcode => '1020',
country => 'Country',
town => &apos...

More about attributes

We started this chapter with the Class attributes, section but some of the features of attributes are closely connected with methods, that's why we made a break and now are able to continue talking about attributes.

Public and private attributes

In the previous code examples, the class attribute was declared with the dot sigil—$.rooms or $.street. A dot at that position means that the attribute is public and may be accessed by code that does not belong to the class.

There is another twigil, !, which makes attributes private. This means that the only way to read or change the value of an attribute is to access it from methods.

Let us return to the House class and change all the twigils of its...

Class methods

In the previous example, we were using the class attribute for keeping the data that is shared between all instances of the class. We were using a method that is working with that attribute.

The idea of class attributes can also be projected on methods. In Perl 6, classes can contain class methods, which are defined with the sub keyword. Such methods have access to all the class attributes, but do not receive an implicit self reference to the object. Consider an example with two classes:

class Address {
my Int $last_assigned_number = 0;
has Int $.housenumber is rw;

our sub get_next() {
return ++$last_assigned_number;
}
}

class House {
has Address $.address is rw;
}

The get_next class method is declared also with the our keyword. This is needed because we want to access the method from external code. By default, the scope will be limited to the...

Inheritance

The next feature of object-oriented programming is inheritance. In this section, we talk about inheritance and related topics in Perl 6.

Inheriting from a class

Inheriting in OOP means creating a new class, which extends another already existing class. The simplest form of inheritance is a child-parent pair of two classes.

In the previous sections, we created the House class. Let us use it as the parent class for another concept. We will create a ModernHouse class, which is a House with a solar roof panel. A bare House, which we created earlier in this chapter, contains four attributes—number of rooms, area, height, and address. The address attribute was an Address object in our previous examples but, in...

Appending objects and classes using roles

Roles are another mechanism in modern OOP. A role is like an external part of the class, which is appended to an existing object or a class, providing some extra attributes and methods. Roles are very close to interfaces in some programming languages.

Let us take a house and make it a floating house. For simplicity, the House class has only one attribute, the area of the house. The Floating role has an attribute that keeps the weight of the floating house and the method that returns a Boolean value if the house is too heavy and is sinking:

class House {
has $.area is rw;
}

role Floating {
has $.weight is rw;

method is_sinking() {
return $!weight > 500 * $.area;
}
}

Syntactically, the only difference in creating a role is the keyword role in place of the class keyword.

From now on, there are two ways of applying a role...

Using introspection to learn more

The Perl 6 object system has a built-in mechanism for introspection, with which you can see what this particular object in hand can do, which class it is implementing, which methods can be used, and so on.

In the previous chapters, we already used one of the mechanisms of introspection—the WHAT method. It returns the type object with information about the type of the object that is located in the container now. We are talking about introspection in the chapter dedicated to the object-oriented programming, but you should keep in mind that in Perl 6, many other simple variables such as strings or integers are also objects.

For example, this is how you can see the type of a string and an integer. The program prints the stringified version of what the WHAT method returns:

say 'string'.WHAT; # (Str)
say 42.WHAT; # (Int)

With...

Method postfix operators

In Chapter 4, Working with Operators, we did not cover the set of special postfix operators, which are related to object-oriented programming. Now it is time to fill that gap. The operators described in this section are the syntactic constructions but they may all be considered postfix operators.

To call a method on an object, the dot operator is used. We have been using it many times in this chapter:

class A {
method m() {
return 42;
}
}

my $o = A.new; # calling the 'new' method
say $o.m(); # calling the 'm' method

If the method does not exist, say, if you call $o.n(), then the call fails:

No such method 'n' for invocant of type 'A'

To prevent the raise of an exception, the .? form of the method call operator can help:

say $o.?m(); # 42
say $o.?n(); # Nil

An existing method is called as usual, while...

Summary

In this chapter, we learnt about object-oriented support in Perl 6. We went through creating a class, adding attributes and methods to it, and making the methods and class data public or private. We then talked about class hierarchy and an alternative approach using roles and also how to use Perl 6 built-in facilities for introspecting the objects. On a set of examples, we examined many techniques of working with complex objects. Finally, the postfix method operators were listed, with which you may create more universal and robust programs.

In the next chapter, exceptions are described. In Perl 6, they are based on classes, so the knowledge from the current chapter will be very useful for better understanding exceptions.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Perl 6 Deep Dive
Published in: Sep 2017Publisher: PacktISBN-13: 9781787282049
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Andrew Shitov

Andrew Shitov has been a Perl enthusiast since the end of the 1990s, and is the organizer of over 30 Perl conferences in eight countries. He worked as a developer and CTO in leading web-development companies, such as Art. Lebedev Studio, Booking dotCom, and eBay, and he learned from the "Fathers of the Russian Internet", Artemy Lebedev and Anton Nossik. Andrew has been following the Perl 6 development since its beginning in 2000. He ran a blog dedicated to the language, published a series of articles in the Pragmatic Perl magazine, and gives talks about Perl 6 at various Perl events. In 2017, he published the Perl 6 at a Glance book by DeepText, which was the first book on Perl 6 published after the first stable release of the language specification.
Read more about Andrew Shitov