Cari di Perl 
    Perl Tutorial
Daftar Isi
(Sebelumnya) Format report chartPerl Tie (Berikutnya)
Language Reference

Object OOP

Daftar Isi

NAME

perlobj - Perl object reference

DESCRIPTION

This document provides a reference for Perl's object orientationfeatures. If you're looking for an introduction to object-orientedprogramming in Perl, please see perlootut.

In order to understand Perl objects, you first need to understandreferences in Perl. See perlref for details.

This document describes all of Perl's object-oriented (OO) featuresfrom the ground up. If you're just looking to write someobject-oriented code of your own, you are probably better served byusing one of the object systems from CPAN described in perlootut.

If you're looking to write your own object system, or you need tomaintain code which implements objects from scratch then this documentwill help you understand exactly how Perl does object orientation.

There are a few basic principles which define object oriented Perl:

1.

An object is simply a data structure that knows to which class itbelongs.

2.

A class is simply a package. A class provides methods that expect tooperate on objects.

3.

A method is simply a subroutine that expects a reference to an object(or a package name, for class methods) as the first argument.

Let's look at each of these principles in depth.

An Object is Simply a Data Structure

Unlike many other languages which support object orientation, Perl doesnot provide any special syntax for constructing an object. Objects aremerely Perl data structures (hashes, arrays, scalars, filehandles,etc.) that have been explicitly associated with a particular class.

That explicit association is created by the built-in bless function,which is typically used within the constructor subroutine of theclass.

Here is a simple constructor:

  1. package File;
  2. sub new {
  3. my $class = shift;
  4. return bless {}, $class;
  5. }

The name new isn't special. We could name our constructor somethingelse:

  1. package File;
  2. sub load {
  3. my $class = shift;
  4. return bless {}, $class;
  5. }

The modern convention for OO modules is to always use new as thename for the constructor, but there is no requirement to do so. Anysubroutine that blesses a data structure into a class is a validconstructor in Perl.

In the previous examples, the {} code creates a reference to anempty anonymous hash. The bless function then takes that referenceand associates the hash with the class in $class. In the simplestcase, the $class variable will end up containing the string "File".

We can also use a variable to store a reference to the data structurethat is being blessed as our object:

  1. sub new {
  2. my $class = shift;
  3. my $self = {};
  4. bless $self, $class;
  5. return $self;
  6. }

Once we've blessed the hash referred to by $self we can startcalling methods on it. This is useful if you want to put objectinitialization in its own separate method:

  1. sub new {
  2. my $class = shift;
  3. my $self = {};
  4. bless $self, $class;
  5. $self->_initialize();
  6. return $self;
  7. }

Since the object is also a hash, you can treat it as one, using it tostore data associated with the object. Typically, code inside the classcan treat the hash as an accessible data structure, while code outsidethe class should always treat the object as opaque. This is calledencapsulation. Encapsulation means that the user of an object doesnot have to know how it is implemented. The user simply callsdocumented methods on the object.

Note, however, that (unlike most other OO languages) Perl does notensure or enforce encapsulation in any way. If you want objects toactually be opaque you need to arrange for that yourself. This canbe done in a varierty of ways, including using Inside-Out objectsor modules from CPAN.

Objects Are Blessed; Variables Are Not

When we bless something, we are not blessing the variable whichcontains a reference to that thing, nor are we blessing the referencethat the variable stores; we are blessing the thing that the variablerefers to (sometimes known as the referent). This is bestdemonstrated with this code:

  1. use Scalar::Util 'blessed';
  2. my $foo = {};
  3. my $bar = $foo;
  4. bless $foo, 'Class';
  5. print blessed( $bar ); # prints "Class"
  6. $bar = "some other value";
  7. print blessed( $bar ); # prints undef

When we call bless on a variable, we are actually blessing theunderlying data structure that the variable refers to. We are notblessing the reference itself, nor the variable that contains thatreference. That's why the second call to blessed( $bar ) returnsfalse. At that point $bar is no longer storing a reference to anobject.

You will sometimes see older books or documentation mention "blessing areference" or describe an object as a "blessed reference", but this isincorrect. It isn't the reference that is blessed as an object; it'sthe thing the reference refers to (i.e. the referent).

A Class is Simply a Package

Perl does not provide any special syntax for class definitions. Apackage is simply a namespace containing variables and subroutines. Theonly difference is that in a class, the subroutines may expect areference to an object or the name of a class as the first argument.This is purely a matter of convention, so a class may contain bothmethods and subroutines which don't operate on an object or class.

Each package contains a special array called @ISA. The @ISA arraycontains a list of that class's parent classes, if any. This array isexamined when Perl does method resolution, which we will cover later.

It is possible to manually set @ISA, and you may see this in olderPerl code. Much older code also uses the base pragma. For new code,we recommend that you use the parent pragma to declare your parents.This pragma will take care of setting @ISA. It will also load theparent classes and make sure that the package doesn't inherit fromitself.

However the parent classes are set, the package's @ISA variable willcontain a list of those parents. This is simply a list of scalars, eachof which is a string that corresponds to a package name.

All classes inherit from the UNIVERSAL class implicitly. TheUNIVERSAL class is implemented by the Perl core, and providesseveral default methods, such as isa(), can(), and VERSION().The UNIVERSAL class will never appear in a package's @ISAvariable.

Perl only provides method inheritance as a built-in feature.Attribute inheritance is left up the class to implement. See theWriting Accessors section for details.

A Method is Simply a Subroutine

Perl does not provide any special syntax for defining a method. Amethod is simply a regular subroutine, and is declared with sub.What makes a method special is that it expects to receive either anobject or a class name as its first argument.

Perl does provide special syntax for method invocation, the -> operator. We will cover this in more detail later.

Most methods you write will expect to operate on objects:

  1. sub save {
  2. my $self = shift;
  3. open my $fh, '>', $self->path() or die $!;
  4. print {$fh} $self->data() or die $!;
  5. close $fh or die $!;
  6. }

Method Invocation

Calling a method on an object is written as $object->method.

The left hand side of the method invocation (or arrow) operator is theobject (or class name), and the right hand side is the method name.

  1. my $pod = File->new( 'perlobj.pod', $data );
  2. $pod->save();

The -> syntax is also used when dereferencing a reference. Itlooks like the same operator, but these are two different operations.

When you call a method, the thing on the left side of the arrow ispassed as the first argument to the method. That means when we call Critter->new(), the new() method receives the string "Critter"as its first argument. When we call $fred->speak(), the $fredvariable is passed as the first argument to speak().

Just as with any Perl subroutine, all of the arguments passed in @_are aliases to the original argument. This includes the object itself.If you assign directly to $_[0] you will change the contents of thevariable that holds the reference to the object. We recommend that youdon't do this unless you know exactly what you're doing.

Perl knows what package the method is in by looking at the left side ofthe arrow. If the left hand side is a package name, it looks for themethod in that package. If the left hand side is an object, then Perllooks for the method in the package that the object has been blessedinto.

If the left hand side is neither a package name nor an object, then themethod call will cause an error, but see the section on Method Call Variations for more nuances.

Inheritance

We already talked about the special @ISA array and the parentpragma.

When a class inherits from another class, any methods defined in theparent class are available to the child class. If you attempt to call amethod on an object that isn't defined in its own class, Perl will alsolook for that method in any parent classes it may have.

  1. package File::MP3;
  2. use parent 'File'; # sets @File::MP3::ISA = ('File');
  3. my $mp3 = File::MP3->new( 'Andvari.mp3', $data );
  4. $mp3->save();

Since we didn't define a save() method in the File::MP3 class,Perl will look at the File::MP3 class's parent classes to find thesave() method. If Perl cannot find a save() method anywhere inthe inheritance hierarchy, it will die.

In this case, it finds a save() method in the File class. Notethat the object passed to save() in this case is still aFile::MP3 object, even though the method is found in the Fileclass.

We can override a parent's method in a child class. When we do so, wecan still call the parent class's method with the SUPERpseudo-class.

  1. sub save {
  2. my $self = shift;
  3. say 'Prepare to rock';
  4. $self->SUPER::save();
  5. }

The SUPER modifier can only be used for method calls. You can'tuse it for regular subroutine calls or class methods:

  1. SUPER::save($thing); # FAIL: looks for save() sub in package SUPER
  2. SUPER->save($thing); # FAIL: looks for save() method in class
  3. # SUPER
  4. $thing->SUPER::save(); # Okay: looks for save() method in parent
  5. # classes

How SUPER is Resolved

The SUPER pseudo-class is resolved from the package where the callis made. It is not resolved based on the object's class. This isimportant, because it lets methods at different levels within a deepinheritance hierarchy each correctly call their respective parentmethods.

  1. package A;
  2. sub new {
  3. return bless {}, shift;
  4. }
  5. sub speak {
  6. my $self = shift;
  7. $self->SUPER::speak();
  8. say 'A';
  9. }
  10. package B;
  11. use parent 'A';
  12. sub speak {
  13. my $self = shift;
  14. $self->SUPER::speak();
  15. say 'B';
  16. }
  17. package C;
  18. use parent 'B';
  19. sub speak {
  20. my $self = shift;
  21. $self->SUPER::speak();
  22. say 'C';
  23. }
  24. my $c = C->new();
  25. $c->speak();

In this example, we will get the following output:

  1. A
  2. B
  3. C

This demonstrates how SUPER is resolved. Even though the object isblessed into the C class, the speak() method in the B classcan still call SUPER::speak() and expect it to correctly look in theparent class of B (i.e the class the method call is in), not in theparent class of C (i.e. the class the object belongs to).

There are rare cases where this package-based resolution can be aproblem. If you copy a subroutine from one package to another, SUPERresolution will be done based on the original package.

Multiple Inheritance

Multiple inheritance often indicates a design problem, but Perl alwaysgives you enough rope to hang yourself with if you ask for it.

To declare multiple parents, you simply need to pass multiple classnames to use parent:

  1. package MultiChild;
  2. use parent 'Parent1', 'Parent2';

Method Resolution Order

Method resolution order only matters in the case of multipleinheritance. In the case of single inheritance, Perl simply looks upthe inheritance chain to find a method:

  1. Grandparent
  2. |
  3. Parent
  4. |
  5. Child

If we call a method on a Child object and that method is not definedin the Child class, Perl will look for that method in the Parentclass and then, if necessary, in the Grandparent class.

If Perl cannot find the method in any of these classes, it will diewith an error message.

When a class has multiple parents, the method lookup order becomes morecomplicated.

By default, Perl does a depth-first left-to-right search for a method.That means it starts with the first parent in the @ISA array, andthen searches all of its parents, grandparents, etc. If it fails tofind the method, it then goes to the next parent in the originalclass's @ISA array and searches from there.

  1. SharedGreatGrandParent
  2. / \
  3. PaternalGrandparent MaternalGrandparent
  4. \ /
  5. Father Mother
  6. \ /
  7. Child

So given the diagram above, Perl will search Child, Father,PaternalGrandparent, SharedGreatGrandParent, Mother, andfinally MaternalGrandparent. This may be a problem because now we'relooking in SharedGreatGrandParent before we've checked all itsderived classes (i.e. before we tried Mother andMaternalGrandparent).

It is possible to ask for a different method resolution order with themro pragma.

  1. package Child;
  2. use mro 'c3';
  3. use parent 'Father', 'Mother';

This pragma lets you switch to the "C3" resolution order. In simpleterms, "C3" order ensures that shared parent classes are never searchedbefore child classes, so Perl will now search: Child, Father,PaternalGrandparent, Mother MaternalGrandparent, and finallySharedGreatGrandParent. Note however that this is not"breadth-first" searching: All the Father ancestors (except thecommon ancestor) are searched before any of the Mother ancestors areconsidered.

The C3 order also lets you call methods in sibling classes with thenext pseudo-class. See the mro documentation for more details onthis feature.

Method Resolution Caching

When Perl searches for a method, it caches the lookup so that futurecalls to the method do not need to search for it again. Changing aclass's parent class or adding subroutines to a class will invalidatethe cache for that class.

The mro pragma provides some functions for manipulating the methodcache directly.

Writing Constructors

As we mentioned earlier, Perl provides no special constructor syntax.This means that a class must implement its own constructor. Aconstructor is simply a class method that returns a reference to a newobject.

The constructor can also accept additional parameters that define theobject. Let's write a real constructor for the File class we usedearlier:

  1. package File;
  2. sub new {
  3. my $class = shift;
  4. my ( $path, $data ) = @_;
  5. my $self = bless {
  6. path => $path,
  7. data => $data,
  8. }, $class;
  9. return $self;
  10. }

As you can see, we've stored the path and file data in the objectitself. Remember, under the hood, this object is still just a hash.Later, we'll write accessors to manipulate this data.

For our File::MP3 class, we can check to make sure that the path we'regiven ends with ".mp3":

  1. package File::MP3;
  2. sub new {
  3. my $class = shift;
  4. my ( $path, $data ) = @_;
  5. die "You cannot create a File::MP3 without an mp3 extension\n"
  6. unless $path =~ /\.mp3\z/;
  7. return $class->SUPER::new(@_);
  8. }

This constructor lets its parent class do the actual objectconstruction.

Attributes

An attribute is a piece of data belonging to a particular object.Unlike most object-oriented languages, Perl provides no special syntaxor support for declaring and manipulating attributes.

Attributes are often stored in the object itself. For example, if theobject is an anonymous hash, we can store the attribute values in thehash using the attribute name as the key.

While it's possible to refer directly to these hash keys outside of theclass, it's considered a best practice to wrap all access to theattribute with accessor methods.

This has several advantages. Accessors make it easier to change theimplementation of an object later while still preserving the originalAPI.

An accessor lets you add additional code around attribute access. Forexample, you could apply a default to an attribute that wasn't set inthe constructor, or you could validate that a new value for theattribute is acceptable.

Finally, using accessors makes inheritance much simpler. Subclasses canuse the accessors rather than having to know how a parent class isimplemented internally.

Writing Accessors

As with constructors, Perl provides no special accessor declarationsyntax, so classes must provide explicitly written accessor methods.There are two common types of accessors, read-only and read-write.

A simple read-only accessor simply gets the value of a singleattribute:

  1. sub path {
  2. my $self = shift;
  3. return $self->{path};
  4. }

A read-write accessor will allow the caller to set the value as well asget it:

  1. sub path {
  2. my $self = shift;
  3. if (@_) {
  4. $self->{path} = shift;
  5. }
  6. return $self->{path};
  7. }

An Aside About Smarter and Safer Code

Our constructor and accessors are not very smart. They don't check thata $path is defined, nor do they check that a $path is a validfilesystem path.

Doing these checks by hand can quickly become tedious. Writing a bunchof accessors by hand is also incredibly tedious. There are a lot ofmodules on CPAN that can help you write safer and more concise code,including the modules we recommend in perlootut.

Method Call Variations

Perl supports several other ways to call methods besides the $object->method() usage we've seen so far.

Method Names as Strings

Perl lets you use a scalar variable containing a string as a methodname:

  1. my $file = File->new( $path, $data );
  2. my $method = 'save';
  3. $file->$method();

This works exactly like calling $file->save(). This can be veryuseful for writing dynamic code. For example, it allows you to pass amethod name to be called as a parameter to another method.

Class Names as Strings

Perl also lets you use a scalar containing a string as a class name:

  1. my $class = 'File';
  2. my $file = $class->new( $path, $data );

Again, this allows for very dynamic code.

Subroutine References as Methods

You can also use a subroutine reference as a method:

  1. my $sub = sub {
  2. my $self = shift;
  3. $self->save();
  4. };
  5. $file->$sub();

This is exactly equivalent to writing $sub->($file). You may seethis idiom in the wild combined with a call to can:

  1. if ( my $meth = $object->can('foo') ) {
  2. $object->$meth();
  3. }

Deferencing Method Call

Perl also lets you use a dereferenced scalar reference in a methodcall. That's a mouthful, so let's look at some code:

  1. $file->${ \'save' };
  2. $file->${ returns_scalar_ref() };
  3. $file->${ \( returns_scalar() ) };
  4. $file->${ returns_sub_ref() };

This works if the dereference produces a string or a subroutinereference.

Method Calls on Filehandles

Under the hood, Perl filehandles are instances of the IO::Handle orIO::File class. Once you have an open filehandle, you can callmethods on it. Additionally, you can call methods on the STDIN,STDOUT, and STDERR filehandles.

  1. open my $fh, '>', 'path/to/file';
  2. $fh->autoflush();
  3. $fh->print('content');
  4. STDOUT->autoflush();

Invoking Class Methods

Because Perl allows you to use barewords for package names andsubroutine names, it sometimes interprets a bareword's meaningincorrectly. For example, the construct Class->new() can beinterpreted as either 'Class'->new() or Class()->new().In English, that second interpretation reads as "call a subroutinenamed Class(), then call new() as a method on the return value ofClass()". If there is a subroutine named Class() in the currentnamespace, Perl will always interpret Class->new() as the secondalternative: a call to new() on the object returned by a call toClass()

You can force Perl to use the first interpretation (i.e. as a methodcall on the class named "Class") in two ways. First, you can append a:: to the class name:

  1. Class::->new()

Perl will always interpret this as a method call.

Alternatively, you can quote the class name:

  1. 'Class'->new()

Of course, if the class name is in a scalar Perl will do the rightthing as well:

  1. my $class = 'Class';
  2. $class->new();

Indirect Object Syntax

Outside of the file handle case, use of this syntax is discouraged,as it can confuse the Perl interpreter. See below for more details.

Perl suports another method invocation syntax called "indirect object"notation. This syntax is called "indirect" because the method comesbefore the object it is being invoked on.

This syntax can be used with any class or object method:

  1. my $file = new File $path, $data;
  2. save $file;

We recommend that you avoid this syntax, for several reasons.

First, it can be confusing to read. In the above example, it's notclear if save is a method provided by the File class or simply asubroutine that expects a file object as its first argument.

When used with class methods, the problem is even worse. Because Perlallows subroutine names to be written as barewords, Perl has to guesswhether the bareword after the method is a class name or subroutinename. In other words, Perl can resolve the syntax as either File->new( $path, $data ) or new( File( $path, $data ) ).

To parse this code, Perl uses a heuristic based on what package namesit has seen, what subroutines exist in the current package, whatbarewords it has previously seen, and other input. Needless to say,heuristics can produce very surprising results!

Older documentation (and some CPAN modules) encouraged this syntax,particularly for constructors, so you may still find it in the wild.However, we encourage you to avoid using it in new code.

You can force Perl to interpret the bareword as a class name byappending "::" to it, like we saw earlier:

  1. my $file = new File:: $path, $data;

bless, blessed, and ref

As we saw earlier, an object is simply a data structure that has beenblessed into a class via the bless function. The bless functioncan take either one or two arguments:

  1. my $object = bless {}, $class;
  2. my $object = bless {};

In the first form, the anonymous hash is being blessed into the classin $class. In the second form, the anonymous hash is blessed intothe current package.

The second form is strongly discouraged, because it breaks the abilityof a subclass to reuse the parent's constructor, but you may still runacross it in existing code.

If you want to know whether a particular scalar refers to an object,you can use the blessed function exported by Scalar::Util, whichis shipped with the Perl core.

  1. use Scalar::Util 'blessed';
  2. if ( defined blessed($thing) ) { ... }

If $thing refers to an object, then this function returns the nameof the package the object has been blessed into. If $thing doesn'tcontain a reference to a blessed object, the blessed functionreturns undef.

Note that blessed($thing) will also return false if $thing hasbeen blessed into a class named "0". This is a possible, but quitepathological. Don't create a class named "0" unless you know whatyou're doing.

Similarly, Perl's built-in ref function treats a reference to ablessed object specially. If you call ref($thing) and $thingholds a reference to an object, it will return the name of the classthat the object has been blessed into.

If you simply want to check that a variable contains an objectreference, we recommend that you use defined blessed($object), sinceref returns true values for all references, not just objects.

The UNIVERSAL Class

All classes automatically inherit from the UNIVERSAL class, which isbuilt-in to the Perl core. This class provides a number of methods, allof which can be called on either a class or an object. You can alsochoose to override some of these methods in your class. If you do so,we recommend that you follow the built-in semantics described below.

  • isa($class)

    The isa method returns true if the object is a member of theclass in $class, or a member of a subclass of $class.

    If you override this method, it should never throw an exception.

  • DOES($role)

    The DOES method returns true if its object claims to perform therole $role. By default, this is equivalent to isa. This method isprovided for use by object system extensions that implement roles, likeMoose and Role::Tiny.

    You can also override DOES directly in your own classes. If youoverride this method, it should never throw an exception.

  • can($method)

    The can method checks to see if the class or object it was called onhas a method named $method. This checks for the method in the classand all of its parents. If the method exists, then a reference to thesubroutine is returned. If it does not then undef is returned.

    If your class responds to method calls via AUTOLOAD, you may want tooverload can to return a subroutine reference for methods which yourAUTOLOAD method handles.

    If you override this method, it should never throw an exception.

  • VERSION($need)

    The VERSION method returns the version number of the class(package).

    If the $need argument is given then it will check that the currentversion (as defined by the $VERSION variable in the package) is greaterthan or equal to $need; it will die if this is not the case. Thismethod is called automatically by the VERSION form of use.

    1. use Package 1.2 qw(some imported subs);
    2. # implies:
    3. Package->VERSION(1.2);

    We recommend that you use this method to access another package'sversion, rather than looking directly at $Package::VERSION. Thepackage you are looking at could have overridden the VERSION method.

    We also recommend using this method to check whether a module has asufficient version. The internal implementation uses the versionmodule to make sure that different types of version numbers arecompared correctly.

AUTOLOAD

If you call a method that doesn't exist in a class, Perl will throw anerror. However, if that class or any of its parent classes defines anAUTOLOAD method, that AUTOLOAD method is called instead.

AUTOLOAD is called as a regular method, and the caller will not knowthe difference. Whatever value your AUTOLOAD method returns isreturned to the caller.

The fully qualified method name that was called is available in the$AUTOLOAD package global for your class. Since this is a global, ifyou want to refer to do it without a package name prefix under strict'vars', you need to declare it.

  1. # XXX - this is a terrible way to implement accessors, but it makes
  2. # for a simple example.
  3. our $AUTOLOAD;
  4. sub AUTOLOAD {
  5. my $self = shift;
  6. # Remove qualifier from original method name...
  7. my $called = $AUTOLOAD =~ s/.*:://r;
  8. # Is there an attribute of that name?
  9. die "No such attribute: $called"
  10. unless exists $self->{$called};
  11. # If so, return it...
  12. return $self->{$called};
  13. }
  14. sub DESTROY { } # see below

Without the our $AUTOLOAD declaration, this code will not compileunder the strict pragma.

As the comment says, this is not a good way to implement accessors. It's slow and too clever by far. However, you may see this as a way toprovide accessors in older Perl code. See perlootut forrecommendations on OO coding in Perl.

If your class does have an AUTOLOAD method, we strongly recommendthat you override can in your class as well. Your overridden canmethod should return a subroutine reference for any method that yourAUTOLOAD responds to.

Destructors

When the last reference to an object goes away, the object isdestroyed. If you only have one reference to an object stored in alexical scalar, the object is destroyed when that scalar goes out ofscope. If you store the object in a package global, that object may notgo out of scope until the program exits.

If you want to do something when the object is destroyed, you candefine a DESTROY method in your class. This method will always becalled by Perl at the appropriate time, unless the method is empty.

This is called just like any other method, with the object as the firstargument. It does not receive any additional arguments. However, the$_[0] variable will be read-only in the destructor, so you cannotassign a value to it.

If your DESTROY method throws an error, this error will be ignored.It will not be sent to STDERR and it will not cause the program todie. However, if your destructor is running inside an eval {} block,then the error will change the value of $@.

Because DESTROY methods can be called at any time, you shouldlocalize any global variables you might update in your DESTROY. Inparticular, if you use eval {} you should localize $@, and if youuse system or backticks, you should localize $?.

If you define an AUTOLOAD in your class, then Perl will call yourAUTOLOAD to handle the DESTROY method. You can prevent this bydefining an empty DESTROY, like we did in the autoloading example.You can also check the value of $AUTOLOAD and return without doinganything when called to handle DESTROY.

Global Destruction

The order in which objects are destroyed during the global destructionbefore the program exits is unpredictable. This means that any objectscontained by your object may already have been destroyed. You shouldcheck that a contained object is defined before calling a method on it:

  1. sub DESTROY {
  2. my $self = shift;
  3. $self->{handle}->close() if $self->{handle};
  4. }

You can use the ${^GLOBAL_PHASE} variable to detect if you arecurrently in the global destruction phase:

  1. sub DESTROY {
  2. my $self = shift;
  3. return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
  4. $self->{handle}->close();
  5. }

Note that this variable was added in Perl 5.14.0. If you want to detectthe global destruction phase on older versions of Perl, you can use theDevel::GlobalDestruction module on CPAN.

If your DESTROY method issues a warning during global destruction,the Perl interpreter will append the string " during globaldestruction" the warning.

During global destruction, Perl will always garbage collect objectsbefore unblessed references. See PERL_DESTRUCT_LEVEL in perlhacktipsfor more information about global destruction.

Non-Hash Objects

All the examples so far have shown objects based on a blessed hash.However, it's possible to bless any type of data structure or referent,including scalars, globs, and subroutines. You may see this sort ofthing when looking at code in the wild.

Here's an example of a module as a blessed scalar:

  1. package Time;
  2. use strict;
  3. use warnings;
  4. sub new {
  5. my $class = shift;
  6. my $time = time;
  7. return bless \$time, $class;
  8. }
  9. sub epoch {
  10. my $self = shift;
  11. return ${ $self };
  12. }
  13. my $time = Time->new();
  14. print $time->epoch();

Inside-Out objects

In the past, the Perl community experimented with a technique called"inside-out objects". An inside-out object stores its data outside ofthe object's reference, indexed on a unique property of the object,such as its memory address, rather than in the object itself. This hasthe advantage of enforcing the encapsulation of object attributes,since their data is not stored in the object itself.

This technique was popular for a while (and was recommended in DamianConway's Perl Best Practices), but never achieved universaladoption. The Object::InsideOut module on CPAN provides acomprehensive implementation of this technique, and you may see it orother inside-out modules in the wild.

Here is a simple example of the technique, using theHash::Util::FieldHash core module. This module was added to the coreto support inside-out object implementations.

  1. package Time;
  2. use strict;
  3. use warnings;
  4. use Hash::Util::FieldHash 'fieldhash';
  5. fieldhash my %time_for;
  6. sub new {
  7. my $class = shift;
  8. my $self = bless \( my $object ), $class;
  9. $time_for{$self} = time;
  10. return $self;
  11. }
  12. sub epoch {
  13. my $self = shift;
  14. return $time_for{$self};
  15. }
  16. my $time = Time->new;
  17. print $time->epoch;

Pseudo-hashes

The pseudo-hash feature was an experimental feature introduced inearlier versions of Perl and removed in 5.10.0. A pseudo-hash is anarray reference which can be accessed using named keys like a hash. Youmay run in to some code in the wild which uses it. See the fieldspragma for more information.

SEE ALSO

A kinder, gentler tutorial on object-oriented programming in Perl canbe found in perlootut. You should also check out perlmodlib forsome style guides on constructing both modules and classes.

 
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) Format report chartPerl Tie (Berikutnya)