Cari di Perl 
    Perl Tutorial
Daftar Isi
(Sebelumnya) Perl regular expressions tutorialPerl style guide (Berikutnya)
Tutorials

Object-Oriented Programming in Perl Tutorial

Daftar Isi

NAME

perlootut - Object-Oriented Programming in Perl Tutorial

DATE

This document was created in February, 2011.

DESCRIPTION

This document provides an introduction to object-oriented programmingin Perl. It begins with a brief overview of the concepts behind objectoriented design. Then it introduces several different OO systems fromCPAN which build on top of what Perlprovides.

By default, Perl's built-in OO system is very minimal, leaving you todo most of the work. This minimalism made a lot of sense in 1994, butin the years since Perl 5.0 we've seen a number of common patternsemerge in Perl OO. Fortunately, Perl's flexibility has allowed a richecosystem of Perl OO systems to flourish.

If you want to know how Perl OO works under the hood, the perlobjdocument explains the nitty gritty details.

This document assumes that you already understand the basics of Perlsyntax, variable types, operators, and subroutine calls. If you don'tunderstand these concepts yet, please read perlintro first. Youshould also read the perlsyn, perlop, and perlsub documents.

OBJECT-ORIENTED FUNDAMENTALS

Most object systems share a number of common concepts. You've probablyheard terms like "class", "object, "method", and "attribute" before.Understanding the concepts will make it much easier to read and writeobject-oriented code. If you're already familiar with these terms, youshould still skim this section, since it explains each concept in termsof Perl's OO implementation.

Perl's OO system is class-based. Class-based OO is fairly common. It'sused by Java, C++, C#, Python, Ruby, and many other languages. Thereare other object orientation paradigms as well. JavaScript is the mostpopular language to use another paradigm. JavaScript's OO system isprototype-based.

Object

An object is a data structure that bundles together data andsubroutines which operate on that data. An object's data is calledattributes, and its subroutines are called methods. An object canbe thought of as a noun (a person, a web service, a computer).

An object represents a single discrete thing. For example, an objectmight represent a file. The attributes for a file object might includeits path, content, and last modification time. If we created an objectto represent /etc/hostname on a machine named "foo.example.com",that object's path would be "/etc/hostname", its content would be"foo\n", and it's last modification time would be 1304974868 secondssince the beginning of the epoch.

The methods associated with a file might include rename() andwrite().

In Perl most objects are hashes, but the OO systems we recommend keepyou from having to worry about this. In practice, it's best to consideran object's internal data structure opaque.

Class

A class defines the behavior of a category of objects. A class is aname for a category (like "File"), and a class also defines thebehavior of objects in that category.

All objects belong to a specific class. For example, our/etc/hostname object belongs to the File class. When we want tocreate a specific object, we start with its class, and construct orinstantiate an object. A specific object is often referred to as aninstance of a class.

In Perl, any package can be a class. The difference between a packagewhich is a class and one which isn't is based on how the package isused. Here's our "class declaration" for the File class:

  1. package File;

In Perl, there is no special keyword for constructing an object.However, most OO modules on CPAN use a method named new() toconstruct a new object:

  1. my $hostname = File->new(
  2. path => '/etc/hostname',
  3. content => "foo\n",
  4. last_mod_time => 1304974868,
  5. );

(Don't worry about that -> operator, it will be explainedlater.)

Blessing

As we said earlier, most Perl objects are hashes, but an object can bean instance of any Perl data type (scalar, array, etc.). Turning aplain data structure into an object is done by blessing that datastructure using Perl's bless function.

While we strongly suggest you don't build your objects from scratch,you should know the term bless. A blessed data structure (aka "areferent") is an object. We sometimes say that an object has been"blessed into a class".

Once a referent has been blessed, the blessed function from theScalar::Util core module can tell us its class name. This subroutinereturns an object's class when passed an object, and false otherwise.

  1. use Scalar::Util 'blessed';
  2. print blessed($hash); # undef
  3. print blessed($hostname); # File

Constructor

A constructor creates a new object. In Perl, a class's constructoris just another method, unlike some other languages, which providesyntax for constructors. Most Perl classes use new as the name fortheir constructor:

  1. my $file = File->new(...);

Methods

You already learned that a method is a subroutine that operates onan object. You can think of a method as the things that an object cando. If an object is a noun, then methods are its verbs (save, print,open).

In Perl, methods are simply subroutines that live in a class's package.Methods are always written to receive the object as their firstargument:

  1. sub print_info {
  2. my $self = shift;
  3. print "This file is at ", $self->path, "\n";
  4. }
  5. $file->print_info;
  6. # The file is at /etc/hostname

What makes a method special is how it's called. The arrow operator(->) tells Perl that we are calling a method.

When we make a method call, Perl arranges for the method's invocantto be passed as the first argument. Invocant is a fancy name for thething on the left side of the arrow. The invocant can either be a classname or an object. We can also pass additional arguments to the method:

  1. sub print_info {
  2. my $self = shift;
  3. my $prefix = shift // "This file is at ";
  4. print $prefix, ", ", $self->path, "\n";
  5. }
  6. $file->print_info("The file is located at ");
  7. # The file is located at /etc/hostname

Attributes

Each class can define its attributes. When we instantiate an object,we assign values to those attributes. For example, every File objecthas a path. Attributes are sometimes called properties.

Perl has no special syntax for attributes. Under the hood, attributesare often stored as keys in the object's underlying hash, but don'tworry about this.

We recommend that you only access attributes via accessor methods.These are methods that can get or set the value of each attribute. Wesaw this earlier in the print_info() example, which calls $self->path.

You might also see the terms getter and setter. These are twotypes of accessors. A getter gets the attribute's value, while a settersets it. Another term for a setter is mutator

Attributes are typically defined as read-only or read-write. Read-onlyattributes can only be set when the object is first created, whileread-write attributes can be altered at any time.

The value of an attribute may itself be another object. For example,instead of returning its last mod time as a number, the File classcould return a DateTime object representing that value.

It's possible to have a class that does not expose any publiclysettable attributes. Not every class has attributes and methods.

Polymorphism

Polymorphism is a fancy way of saying that objects from twodifferent classes share an API. For example, we could have File andWebPage classes which both have a print_content() method. Thismethod might produce different output for each class, but they share acommon interface.

While the two classes may differ in many ways, when it comes to theprint_content() method, they are the same. This means that we cantry to call the print_content() method on an object of either class,and we don't have to know what class the object belongs to!

Polymorphism is one of the key concepts of object-oriented design.

Inheritance

Inheritance lets you create a specialized version of an existingclass. Inheritance lets the new class to reuse the methods andattributes of another class.

For example, we could create an File::MP3 class which inheritsfrom File. An File::MP3 is-a more specific type of File.All mp3 files are files, but not all files are mp3 files.

We often refer to inheritance relationships as parent-child orsuperclass/subclass relationships. Sometimes we say that the childhas an is-a relationship with its parent class.

File is a superclass of File::MP3, and File::MP3 is asubclass of File.

  1. package File::MP3;
  2. use parent 'File';

The parent module is one of several ways that Perl lets you defineinheritance relationships.

Perl allows multiple inheritance, which means that a class can inheritfrom multiple parents. While this is possible, we strongly recommendagainst it. Generally, you can use roles to do everything you can dowith multiple inheritance, but in a cleaner way.

Note that there's nothing wrong with defining multiple subclasses of agiven class. This is both common and safe. For example, we might defineFile::MP3::FixedBitrate and File::MP3::VariableBitrate classes todistinguish between different types of mp3 file.

Overriding methods and method resolution

Inheritance allows two classes to share code. By default, every methodin the parent class is also available in the child. The child canexplicitly override a parent's method to provide its ownimplementation. For example, if we have an File::MP3 object, it hasthe print_info() method from File:

  1. my $cage = File::MP3->new(
  2. path => 'mp3s/My-Body-Is-a-Cage.mp3',
  3. content => $mp3_data,
  4. last_mod_time => 1304974868,
  5. title => 'My Body Is a Cage',
  6. );
  7. $cage->print_info;
  8. # The file is at mp3s/My-Body-Is-a-Cage.mp3

If we wanted to include the mp3's title in the greeting, we couldoverride the method:

  1. package File::MP3;
  2. use parent 'File';
  3. sub print_info {
  4. my $self = shift;
  5. print "This file is at ", $self->path, "\n";
  6. print "Its title is ", $self->title, "\n";
  7. }
  8. $cage->print_info;
  9. # The file is at mp3s/My-Body-Is-a-Cage.mp3
  10. # Its title is My Body Is a Cage

The process of determining what method should be used is calledmethod resolution. What Perl does is look at the object's classfirst (File::MP3 in this case). If that class defines the method,then that class's version of the method is called. If not, Perl looksat each parent class in turn. For File::MP3, its only parent isFile. If File::MP3 does not define the method, but File does,then Perl calls the method in File.

If File inherited from DataSource, which inherited from Thing,then Perl would keep looking "up the chain" if necessary.

It is possible to explicitly call a parent method from a child:

  1. package File::MP3;
  2. use parent 'File';
  3. sub print_info {
  4. my $self = shift;
  5. $self->SUPER::print_info();
  6. print "Its title is ", $self->title, "\n";
  7. }

The SUPER:: bit tells Perl to look for the print_info() in theFile::MP3 class's inheritance chain. When it finds the parent classthat implements this method, the method is called.

We mentioned multiple inheritance earlier. The main problem withmultiple inheritance is that it greatly complicates method resolution.See perlobj for more details.

Encapsulation

Encapsulation is the idea that an object is opaque. When anotherdeveloper uses your class, they don't need to know how it isimplemented, they just need to know what it does.

Encapsulation is important for several reasons. First, it allows you toseparate the public API from the private implementation. This means youcan change that implementation without breaking the API.

Second, when classes are well encapsulated, they become easier tosubclass. Ideally, a subclass uses the same APIs to access object datathat its parent class uses. In reality, subclassing sometimes involvesviolating encapsulation, but a good API can minimize the need to dothis.

We mentioned earlier that most Perl objects are implemented as hashesunder the hood. The principle of encapsulation tells us that we shouldnot rely on this. Instead, we should use accessor methods to access thedata in that hash. The object systems that we recommend below allautomate the generation of accessor methods. If you use one of them,you should never have to access the object as a hash directly.

Composition

In object-oriented code, we often find that one object referencesanother object. This is called composition, or a has-arelationship.

Earlier, we mentioned that the File class's last_mod_timeaccessor could return a DateTime object. This is a perfect exampleof composition. We could go even further, and make the path andcontent accessors return objects as well. The File class wouldthen be composed of several other objects.

Roles

Roles are something that a class does, rather than something thatit is. Roles are relatively new to Perl, but have become ratherpopular. Roles are applied to classes. Sometimes we say that classesconsume roles.

Roles are an alternative to inheritance for providing polymorphism.Let's assume we have two classes, Radio and Computer. Both ofthese things have on/off switches. We want to model that in our classdefinitions.

We could have both classes inherit from a common parent, likeMachine, but not all machines have on/off switches. We could createa parent class called HasOnOffSwitch, but that is very artificial.Radios and computers are not specializations of this parent. Thisparent is really a rather ridiculous creation.

This is where roles come in. It makes a lot of sense to create aHasOnOffSwitch role and apply it to both classes. This role woulddefine a known API like providing turn_on() and turn_off()methods.

Perl does not have any built-in way to express roles. In the past,people just bit the bullet and used multiple inheritance. Nowadays,there are several good choices on CPAN for using roles.

When to Use OO

Object Orientation is not the best solution to every problem. In PerlBest Practices (copyright 2004, Published by O'Reilly Media, Inc.),Damian Conway provides a list of criteria to use when deciding if OO isthe right fit for your problem:

  • The system being designed is large, or is likely to become large.

  • The data can be aggregated into obvious structures, especially ifthere's a large amount of data in each aggregate.

  • The various types of data aggregate form a natural hierarchy thatfacilitates the use of inheritance and polymorphism.

  • You have a piece of data on which many different operations areapplied.

  • You need to perform the same general operations on related types ofdata, but with slight variations depending on the specific type of datathe operations are applied to.

  • It's likely you'll have to add new data types later.

  • The typical interactions between pieces of data are best represented byoperators.

  • The implementation of individual components of the system is likely tochange over time.

  • The system design is already object-oriented.

  • Large numbers of other programmers will be using your code modules.

PERL OO SYSTEMS

As we mentioned before, Perl's built-in OO system is very minimal, butalso quite flexible. Over the years, many people have developed systemswhich build on top of Perl's built-in system to provide more featuresand convenience.

We strongly recommend that you use one of these systems. Even the mostminimal of them eliminates a lot of repetitive boilerplate. There'sreally no good reason to write your classes from scratch in Perl.

If you are interested in the guts underlying these systems, check outperlobj.

Moose

Moose bills itself as a "postmodern object system for Perl 5". Don'tbe scared, the "postmodern" label is a callback to Larry's descriptionof Perl as "the first postmodern computer language".

Moose provides a complete, modern OO system. Its biggest influenceis the Common Lisp Object System, but it also borrows ideas fromSmalltalk and several other languages. Moose was created by StevanLittle, and draws heavily from his work on the Perl 6 OO design.

Here is our File class using Moose:

  1. package File;
  2. use Moose;
  3. has path => ( is => 'ro' );
  4. has content => ( is => 'ro' );
  5. has last_mod_time => ( is => 'ro' );
  6. sub print_info {
  7. my $self = shift;
  8. print "This file is at ", $self->path, "\n";
  9. }

Moose provides a number of features:

  • Declarative sugar

    Moose provides a layer of declarative "sugar" for defining classes.That sugar is just a set of exported functions that make declaring howyour class works simpler and more palatable. This lets you describewhat your class is, rather than having to tell Perl how toimplement your class.

    The has() subroutine declares an attribute, and Mooseautomatically creates accessors for these attributes. It also takescare of creating a new() method for you. This constructor knowsabout the attributes you declared, so you can set them when creating anew File.

  • Roles built-in

    Moose lets you define roles the same way you define classes:

    1. package HasOnOfSwitch;
    2. use Moose::Role;
    3. has is_on => (
    4. is => 'rw',
    5. isa => 'Bool',
    6. );
    7. sub turn_on {
    8. my $self = shift;
    9. $self->is_on(1);
    10. }
    11. sub turn_off {
    12. my $self = shift;
    13. $self->is_on(0);
    14. }
  • A miniature type system

    In the example above, you can see that we passed isa => 'Bool'to has() when creating our is_on attribute. This tells Moosethat this attribute must be a boolean value. If we try to set it to aninvalid value, our code will throw an error.

  • Full introspection and manipulation

    Perl's built-in introspection features are fairly minimal. Moosebuilds on top of them and creates a full introspection layer for yourclasses. This lets you ask questions like "what methods does the Fileclass implement?" It also lets you modify your classesprogrammatically.

  • Self-hosted and extensible

    Moose describes itself using its own introspection API. Besidesbeing a cool trick, this means that you can extend Moose usingMoose itself.

  • Rich ecosystem

    There is a rich ecosystem of Moose extensions on CPAN under theMooseXnamespace. In addition, many modules on CPAN already use Moose,providing you with lots of examples to learn from.

  • Many more features

    Moose is a very powerful tool, and we can't cover all of itsfeatures here. We encourage you to learn more by reading the Moosedocumentation, starting withMoose::Manual.

Of course, Moose isn't perfect.

Moose can make your code slower to load. Moose itself is notsmall, and it does a lot of code generation when you define yourclass. This code generation means that your runtime code is as fast asit can be, but you pay for this when your modules are first loaded.

This load time hit can be a problem when startup speed is important,such as with a command-line script or a "plain vanilla" CGI script thatmust be loaded each time it is executed.

Before you panic, know that many people do use Moose forcommand-line tools and other startup-sensitive code. We encourage youto try Moose out first before worrying about startup speed.

Moose also has several dependencies on other modules. Most of theseare small stand-alone modules, a number of which have been spun offfrom Moose. Moose itself, and some of its dependencies, require acompiler. If you need to install your software on a system without acompiler, or if having any dependencies is a problem, then Moosemay not be right for you.

Mouse

If you try Moose and find that one of these issues is preventing youfrom using Moose, we encourage you to consider Mouse next.Mouse implements a subset of Moose's functionality in a simplerpackage. For all features that it does implement, the end-user API isidentical to Moose, meaning you can switch from Mouse toMoose quite easily.

Mouse does not implement most of Moose's introspection API, soit's often faster when loading your modules. Additionally, all of itsrequired dependencies ship with the Perl core, and it can runwithout a compiler. If you do have a compiler, Mouse will use it tocompile some of its code for a speed boost.

Finally, it ships with a Mouse::Tiny module that takes most ofMouse's features and bundles them up in a single module file. Youcan copy this module file into your application's library directory foreasy bundling.

The Moose authors hope that one day Mouse can be made obsolete byimproving Moose enough, but for now it provides a worthwhilealternative to Moose.

Class::Accessor

Class::Accessor is the polar opposite of Moose. It provides veryfew features, nor is it self-hosting.

It is, however, very simple, pure Perl, and it has no non-coredependencies. It also provides a "Moose-like" API on demand for thefeatures it supports.

Even though it doesn't do much, it is still preferable to writing yourown classes from scratch.

Here's our File class with Class::Accessor:

  1. package File;
  2. use Class::Accessor 'antlers';
  3. has path => ( is => 'ro' );
  4. has content => ( is => 'ro' );
  5. has last_mod_time => ( is => 'ro' );
  6. sub print_info {
  7. my $self = shift;
  8. print "This file is at ", $self->path, "\n";
  9. }

The antlers import flag tells Class::Accessor that you want todefine your attributes using Moose-like syntax. The only parameterthat you can pass to has is is. We recommend that you use thisMoose-like syntax if you choose Class::Accessor since it means youwill have a smoother upgrade path if you later decide to move toMoose.

Like Moose, Class::Accessor generates accessor methods and aconstructor for your class.

Object::Tiny

Finally, we have Object::Tiny. This module truly lives up to itsname. It has an incredibly minimal API and absolutely no dependencies(core or not). Still, we think it's a lot easier to use than writingyour own OO code from scratch.

Here's our File class once more:

  1. package File;
  2. use Object::Tiny qw( path content last_mod_time );
  3. sub print_info {
  4. my $self = shift;
  5. print "This file is at ", $self->path, "\n";
  6. }

That's it!

With Object::Tiny, all accessors are read-only. It generates aconstructor for you, as well as the accessors you define.

Role::Tiny

As we mentioned before, roles provide an alternative to inheritance,but Perl does not have any built-in role support. If you choose to useMoose, it comes with a full-fledged role implementation. However, ifyou use one of our other recommended OO modules, you can still useroles with Role::Tiny

Role::Tiny provides some of the same features as Moose's rolesystem, but in a much smaller package. Most notably, it doesn't supportany sort of attribute declaration, so you have to do that by hand.Still, it's useful, and works well with Class::Accessor andObject::Tiny

OO System Summary

Here's a brief recap of the options we covered:

  • Moose

    Moose is the maximal option. It has a lot of features, a bigecosystem, and a thriving user base. We also covered Mouse briefly.Mouse is Moose lite, and a reasonable alternative when Moosedoesn't work for your application.

  • Class::Accessor

    Class::Accessor does a lot less than Moose, and is a nicealternative if you find Moose overwhelming. It's been around a longtime and is well battle-tested. It also has a minimal Moosecompatibility mode which makes moving from Class::Accessor toMoose easy.

  • Object::Tiny

    Object::Tiny is the absolute minimal option. It has no dependencies,and almost no syntax to learn. It's a good option for a super minimalenvironment and for throwing something together quickly without havingto worry about details.

  • Role::Tiny

    Use Role::Tiny with Class::Accessor or Object::Tiny if youfind yourself considering multiple inheritance. If you go withMoose, it comes with its own role implementation.

Other OO Systems

There are literally dozens of other OO-related modules on CPAN besidesthose covered here, and you're likely to run across one or more of themif you work with other people's code.

In addition, plenty of code in the wild does all of its OO "by hand",using just the Perl built-in OO features. If you need to maintain suchcode, you should read perlobj to understand exactly how Perl'sbuilt-in OO works.

CONCLUSION

As we said before, Perl's minimal OO system has led to a profusion ofOO systems on CPAN. While you can still drop down to the bare metal andwrite your classes by hand, there's really no reason to do that withmodern Perl.

For small systems, Object::Tiny and Class::Accessor both provideminimal object systems that take care of basic boilerplate for you.

For bigger projects, Moose provides a rich set of features that willlet you focus on implementing your business logic.

We encourage you to play with and evaluate Moose,Class::Accessor, and Object::Tiny to see which OO system is rightfor you.

 
Source : perldoc.perl.org - Official documentation for the Perl programming language
Site maintained by Jon Allen (JJ)     See the project page for more details
Documentation maintained by the Perl 5 Porters
(Sebelumnya) Perl regular expressions tutorialPerl style guide (Berikutnya)