Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Perl Object-Oriented

Perl Object-Oriented

There are two different implementations of object-oriented programming in Perl:


Basic object-oriented concepts

Object orientation has many basic concepts; here we accept three: object, class, and method.

Perl provides the bless() function, which is used to construct objects. Through bless, a reference is associated with the class name, and returning this reference constructs an object.


Definition of the class

A class is just a simple package.

A package can be used as a class, and the functions in the package can be used as methods of the class.

Perl's packages provide independent namespaces, so method and variable names in different packages do not conflict.

The file extension for Perl classes is .pm.

Next, we create a Person class:



package Person;

The code of a class extends to the last line of the script file, or up to the next package keyword.


Creating and using objects

To create an instance (object) of a class, we need to define a constructor. Most programs use the class name as the constructor, but in Perl any name can be used.

You can use various Perl variables as Perl objects. In most cases we use references to arrays or hashes.

Next, we create a constructor for the Person class using a Perl hash reference.

When creating an object, you need to provide a constructor, which is a subroutine that returns a reference to the object.

The example is as follows:

Example

package

Person

;

sub

new

{

my

$class

=

shift

;

my

$self

=

{

_firstName

=>

shift

,

_lastName

=>

shift

,

_ssn

=>

shift

,

}

;

Output user information

print

"

First name:

$self

->{_firstName}

\n

"

;

print

"

Last name:

$self

->{_lastName}

\n

"

;

print

"

ID:

$self

->{_ssn}

\n

"

;

bless

$self

,

$class

;

return

$self

;

}

Next, we create an object:



$object = new Person( "小明", "王", 23234345);


Define a method

Methods of a Perl class are nothing but Perl subroutines, also commonly known as member functions.

In Perl object-oriented programming, method definitions do not provide any special syntax, but it is stipulated that the first argument of a method is the object or the package it references.

Perl does not provide private variables, but we can manage object data in an auxiliary way.

Next, we define a method to get the name:



sub getFirstName {

    return $self->{_firstName};

}

It can also be written like this:



sub setFirstName {

    my ( $self, $firstName ) = @_;

    $self->{_firstName} = $firstName if defined($firstName);

    return $self->{_firstName};

}

Next, we modify the code of the Person.pm file as follows:

Example

#!/usr/bin/perl

package

Person

;

sub

new

{

my

$class

=

shift

;

my

$self

=

{

_firstName

=>

shift

,

_lastName

=>

shift

,

_ssn

=>

shift

,

}

;

Output user information

print

"

First name:

$self

->{_firstName}

\n

"

;

print

"

Last name:

$self

->{_lastName}

\n

"

;

print

"

ID:

$self

->{_ssn}

\n

"

;

bless

$self

,

$class

;

return

$self

;

}

sub

setFirstName

{

my

(

$self

,

$firstName

)

=

@_

;

$self

->

{

_firstName

}

=

$firstName

if

defined

(

$firstName

)

;

return

$self

->

{

_firstName

}

;

}

sub

getFirstName

{

my

(

$self

)

=

@_

;

return

$self

->

{

_firstName

}

;

}

1

;

The employee.pl script code is as follows:

Example

#!/usr/bin/perl

use Person

;

$object

=

new

Person

(

"

Xiao Ming

"

,

"

Wang

"

,

23234345

)

;

Get the name

$firstName

=

$object

->

getFirstName

(

)

;

print

"

Name before setting:

$firstName

\n

"

;

Set the name using an auxiliary function

$object

->

setFirstName

(

"

Xiaoqiang

"

)

;

Get the name through an auxiliary function

$firstName

=

$object

->

getFirstName

(

)

;

print

"

Name after setting:

$firstName

\n

"

;

After executing the above program, the output is:



$ perl employee.pl

名字:小明

姓氏:王

编号:23234345

设置前姓名为 : 小明

设置后姓名为 : 小强


inheritance

In Perl, class methods are inherited through the @ISA array, which contains the names of other packages (classes); the inheritance of variables must be explicitly set.

Multiple inheritance means that this @ISA array contains multiple class (package) names.

Through @ISA only methods can be inherited, not data.

Next, we create an Employee class that inherits from the Person class.

The Employee.pm file code is as follows:

Example

#!/usr/bin/perl

package

Employee

;

use Person

;

use strict

;

our

@ISA

=

qw(

Person

)

;

Inherit from Person

Now the Employee class contains all the methods and attributes of the Person class. We enter the following code in the main.pl file and execute it:

Example

#!/usr/bin/perl

use Employee

;

$object

=

new

Employee

(

"

Xiao Ming

"

,

"

Wang

"

,

23234345

)

;

Get the name

$firstName

=

$object

->

getFirstName

(

)

;

print

"

Name before setting:

$firstName

\n

"

;

Set the name using an auxiliary function

$object

->

setFirstName

(

"

Xiaoqiang

"

)

;

Get the name through an auxiliary function

$firstName

=

$object

->

getFirstName

(

)

;

print

"

Name after setting:

$firstName

\n

"

;

After executing the above program, the output is:



$ perl main.pl

名字:小明

姓氏:王

编号:23234345

设置前姓名为 : 小明

设置后姓名为 : 小强


Method Overriding

In the above example, the Employee class inherits from the Person class, but if the methods of the Person class cannot meet the requirements, they need to be overridden.

Next, we add some new methods to the Employee class and override the methods of the Person class:

Example

#!/usr/bin/perl

package

Employee

;

use Person

;

use strict

;

our

@ISA

=

qw(

Person

)

;

Inherit from Person

Override constructor

sub

new

{

my

(

$class

)

=

@_

;

Call the parent class's constructor

my

$self

=

$class

->

SUPER

::

new

(

$_

[

1

]

,

$_

[

2

]

,

$_

[

3

]

)

;

Add more attributes

$self

->

{

_id

}

=

undef

;

$self

->

{

_title

}

=

undef

;

bless

$self

,

$class

;

return

$self

;

}

Overridden method

sub

getFirstName

{

my

(

$self

)

=

@_

;

This is a subclass function

print

"

This is a subclass function

\n

"

;

return

$self

->

{

_firstName

}

;

}

Add a method

sub

setLastName

{

my

(

$self

,

$lastName

)

=

@_

;

$self

->

{

_lastName

}

=

$lastName

if

defined

(

$lastName

)

;

return

$self

->

{

_lastName

}

;

}

sub

getLastName

{

my

(

$self

)

=

@_

;

return

$self

->

{

_lastName

}

;

}

1

;

We enter the following code in the main.pl file and execute it:

Example

#!/usr/bin/perl

use Employee

;

$object

=

new

Employee

(

"

Xiao Ming

"

,

"

Wang

"

,

23234345

)

;

Get the name, using the modified constructor

$firstName

=

$object

->

getFirstName

(

)

;

print

"

Name before setting:

$firstName

\n

"

;

Set the name using an auxiliary function

$object

->

setFirstName

(

"

Xiaoqiang

"

)

;

Get the name through an auxiliary function

$firstName

=

$object

->

getFirstName

(

)

;

print

"

Name after setting:

$firstName

\n

"

;

After executing the above program, the output is:



$ perl main.pl

名字:小明

姓氏:王

编号:23234345

这是子类函数

设置前姓名为 : 小明

这是子类函数

设置后姓名为 : 小强


Default loading

If the requested method cannot be found in the current class, all base classes of the current class, or the UNIVERSAL class, then a method named AUTOLOAD() is looked up again. If AUTOLOAD is found, it will be called, and the global variable $AUTOLOAD will be set to the fully qualified name of the missing method.

If that still does not work, Perl declares failure and reports an error.

If you do not want to inherit the base class's AUTOLOAD, it is very simple; just one line:



sub AUTOLOAD;


Destructors and garbage collection

When the last reference to an object is released, the object is automatically destructed.

If you want to do something at destruction time, you can define a method named "DESTROY" in the class. It will be called automatically at the appropriate time and perform additional cleanup actions as you wish.



package MyClass;

...

sub DESTROY

{

    print "MyClass::DESTROY called\n";

}

Perl passes the object reference as the only argument to DESTROY. Note that this reference is read-only, which means you cannot modify it by accessing $[0]. (Translator's note: see perlsub) But the object itself (for example "${$[0]" or "@{$[0]}" and "%{$[0]}", etc.) is still writable.

If you rebless the object reference before the destructor returns, Perl will then call the DESTROY method of the object you reblessed after the destructor returns. This gives you the opportunity to call the destructor of the base class or another class you specify. It should be noted that DESTROY can also be called manually, but usually there is no need to do so.

After the current object is released, other objects contained in it are automatically released.


Perl object-oriented example

We can further understand the application of Perl object orientation through the following example:

Example

#!/usr/bin/perl

The following is a simple class implementation

package

MyClass

;

sub

new

{

print

"

MyClass::new called

\n

"

;

my

$type

=

shift

;

Package name

my

$self

=

{

}

;

Reference to an empty hash

return

bless

$self

,

$type

;

}

sub

DESTROY

{

print

"

MyClass::DESTROY called

\n

"

;

}

sub

MyMethod

{

print

"

MyClass::MyMethod called!

\n

"

;

}

Inheritance implementation

package

MySubClass

;

@ISA

=

qw(

MyClass

)

;

sub

new

{

print

"

MySubClass::new called

\n

"

;

my

$type

=

shift

;

Package name

my

$self

=

MyClass

->

new

;

Reference to an empty hash

return

bless

$self

,

$type

;

}

sub

DESTROY

{

print

"

MySubClass::DESTROY called

\n

"

;

}

sub

MyMethod

{

my

$self

=

shift

;

$self

->

SUPER

::

MyMethod

(

)

;

print

"

MySubClass::MyMethod called!

\n

"

;

}

The main program that calls the above classes

package

main

;

print

"

Call the MyClass method

\n

"

;

$myObject

=

MyClass

->

new

(

)

;

$myObject

->

MyMethod

(

)

;

print

"

Call the MySubClass method

\n

"

;

$myObject2

=

MySubClass

->

new

(

)

;

$myObject2

->

MyMethod

(

)

;

print

"

Create a scoped object

\n

"

;

{

my

$myObject2

=

MyClass

->

new

(

)

;

}

Automatically call the destructor

print

"

Creating objects

\n

"

;

$myObject3

=

MyClass

->

new

(

)

;

undef

$myObject3

;

print

"

Script execution ends...

\n

"

;

Automatically execute the destructor

Running the above program, the output is:



调用 MyClass 方法

MyClass::new called

MyClass::MyMethod called!

调用 MySubClass 方法

MySubClass::new called

MyClass::new called

MyClass::MyMethod called!

   MySubClass::MyMethod called!

创建一个作用域对象

MyClass::new called

MyClass::DESTROY called

创建对象

MyClass::new called

MyClass::DESTROY called

脚本执行结束...

MyClass::DESTROY called

MySubClass::DESTROY called