Movatterモバイル変換


[0]ホーム

URL:


perlootut
(source,CPAN)
You are viewing the version of this documentation from Perl 5.30.3.View the latest version

CONTENTS

#NAME

perlootut - Object-Oriented Programming in Perl Tutorial

#DATE

This document was created in February, 2011, and the last major revision was in February, 2013.

If you are reading this in the future then it's possible that the state of the art has changed. We recommend you start by reading the perlootut document in the latest stable release of Perl, rather than this version.

#DESCRIPTION

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

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

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

This document assumes that you already understand the basics of Perl syntax, variable types, operators, and subroutine calls. If you don't understand these concepts yet, please readperlintro first. You should also read theperlsyn,perlop, andperlsub documents.

#OBJECT-ORIENTED FUNDAMENTALS

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

Perl's OO system is class-based. Class-based OO is fairly common. It's used by Java, C++, C#, Python, Ruby, and many other languages. There are other object orientation paradigms as well. JavaScript is the most popular language to use another paradigm. JavaScript's OO system is prototype-based.

#Object

Anobject is a data structure that bundles together data and subroutines which operate on that data. An object's data is calledattributes, and its subroutines are calledmethods. An object can be thought of as a noun (a person, a web service, a computer).

An object represents a single discrete thing. For example, an object might represent a file. The attributes for a file object might include its path, content, and last modification time. If we created an object to 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 seconds since the beginning of the epoch.

The methods associated with a file might includerename() andwrite().

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

#Class

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

All objects belong to a specific class. For example, our/etc/hostname object belongs to theFile class. When we want to create a specific object, we start with its class, andconstruct 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 package which is a class and one which isn't is based on how the package is used. Here's our "class declaration" for theFile class:

package File;

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

my $hostname = File->new(    path          => '/etc/hostname',    content       => "foo\n",    last_mod_time => 1304974868,);

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

#Blessing

As we said earlier, most Perl objects are hashes, but an object can be an instance of any Perl data type (scalar, array, etc.). Turning a plain data structure into an object is done byblessing that data structure using Perl'sbless function.

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

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

use Scalar::Util 'blessed';print blessed($hash);      # undefprint blessed($hostname);  # File

#Constructor

Aconstructor creates a new object. In Perl, a class's constructor is just another method, unlike some other languages, which provide syntax for constructors. Most Perl classes usenew as the name for their constructor:

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

#Methods

You already learned that amethod is a subroutine that operates on an 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 first argument:

sub print_info {    my $self = shift;    print "This file is at ", $self->path, "\n";}$file->print_info;# The file is at /etc/hostname

What makes a method special ishow 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'sinvocant to be passed as the first argument.Invocant is a fancy name for the thing on the left side of the arrow. The invocant can either be a class name or an object. We can also pass additional arguments to the method:

sub print_info {    my $self   = shift;    my $prefix = shift // "This file is at ";    print $prefix, ", ", $self->path, "\n";}$file->print_info("The file is located at ");# The file is located at /etc/hostname

#Attributes

Each class can define itsattributes. When we instantiate an object, we assign values to those attributes. For example, everyFile object has a path. Attributes are sometimes calledproperties.

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

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

You might also see the termsgetter andsetter. These are two types of accessors. A getter gets the attribute's value, while a setter sets it. Another term for a setter ismutator

Attributes are typically defined as read-only or read-write. Read-only attributes can only be set when the object is first created, while read-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, theFile class could return aDateTime object representing that value.

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

#Polymorphism

Polymorphism is a fancy way of saying that objects from two different classes share an API. For example, we could haveFile andWebPage classes which both have aprint_content() method. This method might produce different output for each class, but they share a common 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 can try to call theprint_content() method on an object of either class, andwe 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 existing class. Inheritance lets the new class reuse the methods and attributes of another class.

For example, we could create anFile::MP3 class whichinherits fromFile. AnFile::MP3is-amore specific type ofFile. All mp3 files are files, but not all files are mp3 files.

We often refer to inheritance relationships asparent-child orsuperclass/subclass relationships. Sometimes we say that the child has anis-a relationship with its parent class.

File is asuperclass ofFile::MP3, andFile::MP3 is asubclass ofFile.

package File::MP3;use parent 'File';

Theparent module is one of several ways that Perl lets you define inheritance relationships.

Perl allows multiple inheritance, which means that a class can inherit from multiple parents. While this is possible, we strongly recommend against it. Generally, you can useroles to do everything you can do with multiple inheritance, but in a cleaner way.

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

#Overriding methods and method resolution

Inheritance allows two classes to share code. By default, every method in the parent class is also available in the child. The child can explicitlyoverride a parent's method to provide its own implementation. For example, if we have anFile::MP3 object, it has theprint_info() method fromFile:

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

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

package File::MP3;use parent 'File';sub print_info {    my $self = shift;    print "This file is at ", $self->path, "\n";    print "Its title is ", $self->title, "\n";}$cage->print_info;# The file is at mp3s/My-Body-Is-a-Cage.mp3# 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 class first (File::MP3 in this case). If that class defines the method, then that class's version of the method is called. If not, Perl looks at each parent class in turn. ForFile::MP3, its only parent isFile. IfFile::MP3 does not define the method, butFile does, then Perl calls the method inFile.

IfFile inherited fromDataSource, which inherited fromThing, then Perl would keep looking "up the chain" if necessary.

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

package File::MP3;use parent 'File';sub print_info {    my $self = shift;    $self->SUPER::print_info();    print "Its title is ", $self->title, "\n";}

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

We mentioned multiple inheritance earlier. The main problem with multiple inheritance is that it greatly complicates method resolution. Seeperlobj for more details.

#Encapsulation

Encapsulation is the idea that an object is opaque. When another developer uses your class, they don't need to knowhow it is implemented, they just need to knowwhat it does.

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

Second, when classes are well encapsulated, they become easier to subclass. Ideally, a subclass uses the same APIs to access object data that its parent class uses. In reality, subclassing sometimes involves violating encapsulation, but a good API can minimize the need to do this.

We mentioned earlier that most Perl objects are implemented as hashes under the hood. The principle of encapsulation tells us that we should not rely on this. Instead, we should use accessor methods to access the data in that hash. The object systems that we recommend below all automate 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 references another object. This is calledcomposition, or ahas-a relationship.

Earlier, we mentioned that theFile class'slast_mod_time accessor could return aDateTime object. This is a perfect example of composition. We could go even further, and make thepath andcontent accessors return objects as well. TheFile class would then becomposed of several other objects.

#Roles

Roles are something that a classdoes, rather than something that itis. Roles are relatively new to Perl, but have become rather popular. Roles areapplied 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 andComputer. Both of these things have on/off switches. We want to model that in our class definitions.

We could have both classes inherit from a common parent, likeMachine, but not all machines have on/off switches. We could create a parent class calledHasOnOffSwitch, but that is very artificial. Radios and computers are not specializations of this parent. This parent 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 would define a known API like providingturn_on() andturn_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. InPerl Best Practices (copyright 2004, Published by O'Reilly Media, Inc.), Damian Conway provides a list of criteria to use when deciding if OO is the right fit for your problem:

#PERL OO SYSTEMS

As we mentioned before, Perl's built-in OO system is very minimal, but also quite flexible. Over the years, many people have developed systems which build on top of Perl's built-in system to provide more features and convenience.

We strongly recommend that you use one of these systems. Even the most minimal of them eliminates a lot of repetitive boilerplate. There's really 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't be scared, the "postmodern" label is a callback to Larry's description of Perl as "the first postmodern computer language".

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

Here is ourFile class usingMoose:

package File;use Moose;has path          => ( is => 'ro' );has content       => ( is => 'ro' );has last_mod_time => ( is => 'ro' );sub print_info {    my $self = shift;    print "This file is at ", $self->path, "\n";}

Moose provides a number of features:

Of course,Moose isn't perfect.

Moose can make your code slower to load.Moose itself is not small, and it does alot of code generation when you define your class. This code generation means that your runtime code is as fast as it 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 that must be loaded each time it is executed.

Before you panic, know that many people do useMoose for command-line tools and other startup-sensitive code. We encourage you to tryMoose out first before worrying about startup speed.

Moose also has several dependencies on other modules. Most of these are small stand-alone modules, a number of which have been spun off fromMoose.Moose itself, and some of its dependencies, require a compiler. If you need to install your software on a system without a compiler, or if havingany dependencies is a problem, thenMoose may not be right for you.

#Moo

If you tryMoose and find that one of these issues is preventing you from usingMoose, we encourage you to considerMoo next.Moo implements a subset ofMoose's functionality in a simpler package. For most features that it does implement, the end-user API isidentical toMoose, meaning you can switch fromMoo toMoose quite easily.

Moo does not implement most ofMoose's introspection API, so it's often faster when loading your modules. Additionally, none of its dependencies require XS, so it can be installed on machines without a compiler.

One ofMoo's most compelling features is its interoperability withMoose. When someone tries to useMoose's introspection API on aMoo class or role, it is transparently inflated into aMoose class or role. This makes it easier to incorporateMoo-using code into aMoose code base and vice versa.

For example, aMoose class can subclass aMoo class usingextends or consume aMoo role usingwith.

TheMoose authors hope that one dayMoo can be made obsolete by improvingMoose enough, but for now it provides a worthwhile alternative toMoose.

#Class::Accessor

Class::Accessor is the polar opposite ofMoose. It provides very few features, nor is it self-hosting.

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

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

Here's ourFile class withClass::Accessor:

package File;use Class::Accessor 'antlers';has path          => ( is => 'ro' );has content       => ( is => 'ro' );has last_mod_time => ( is => 'ro' );sub print_info {    my $self = shift;    print "This file is at ", $self->path, "\n";}

Theantlers import flag tellsClass::Accessor that you want to define your attributes usingMoose-like syntax. The only parameter that you can pass tohas isis. We recommend that you use this Moose-like syntax if you chooseClass::Accessor since it means you will have a smoother upgrade path if you later decide to move toMoose.

LikeMoose,Class::Accessor generates accessor methods and a constructor for your class.

#Class::Tiny

Finally, we haveClass::Tiny. This module truly lives up to its name. It has an incredibly minimal API and absolutely no dependencies on any recent Perl. Still, we think it's a lot easier to use than writing your own OO code from scratch.

Here's ourFile class once more:

package File;use Class::Tiny qw( path content last_mod_time );sub print_info {    my $self = shift;    print "This file is at ", $self->path, "\n";}

That's it!

WithClass::Tiny, all accessors are read-write. It generates a constructor for you, as well as the accessors you define.

You can also useClass::Tiny::Antlers forMoose-like syntax.

#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 use Moose, it comes with a full-fledged role implementation. However, if you use one of our other recommended OO modules, you can still use roles withRole::Tiny

Role::Tiny provides some of the same features as Moose's role system, but in a much smaller package. Most notably, it doesn't support any sort of attribute declaration, so you have to do that by hand. Still, it's useful, and works well withClass::Accessor andClass::Tiny

#OO System Summary

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

#Other OO Systems

There are literally dozens of other OO-related modules on CPAN besides those covered here, and you're likely to run across one or more of them if 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 such code, you should readperlobj to understand exactly how Perl's built-in OO works.

#CONCLUSION

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

For small systems,Class::Tiny andClass::Accessor both provide minimal object systems that take care of basic boilerplate for you.

For bigger projects,Moose provides a rich set of features that will let you focus on implementing your business logic.Moo provides a nice alternative toMoose when you want a lot of features but need faster compile time or to avoid XS.

We encourage you to play with and evaluateMoose,Moo,Class::Accessor, andClass::Tiny to see which OO system is right for you.

Perldoc Browser is maintained by Dan Book (DBOOK). Please contact him via theGitHub issue tracker oremail regarding any issues with the site itself, search, or rendering of documentation.

The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via thePerl issue tracker, themailing list, orIRC to report any issues with the contents or format of the documentation.


[8]ページ先頭

©2009-2025 Movatter.jp