Latest web development tutorials

Perl Object-Oriented

There are two different Perl to implement object-oriented programming:

  • One anonymous hash table-based approach, the essence of each object instance is a point of reference to an anonymous hash table. In this anonymous hash table to store all the instance properties.
  • The second is based on an array of ways, in the definition of a class, we will create a property for each instance of the array, and the essence of each object instance is a pointer to the array in a row the index reference. In these arrays, the memory of all the instance properties.

Basic concepts of object-oriented

There are many basic concepts of object-oriented, we received three here: objects, classes, and methods.

  • Object: The object is a class reference data items..

  • Class: Class is a Perl package, which contains the object to provide a method of the class.

  • Methods: The method is a Perl subroutine, the class name is its first argument.

Perl provides a bless () function, bless is used to construct the object through a reference and bless the name associated with this class, return this reference to construct an object.


Class definition

A class is just a simple package.

You can use a package as a class, and put the bag as a function of the class method to use.

Perl package provides a separate namespace, method of different packages and variable names do not conflict.

Perl file extension classes for .pm.

Next we create a Person class:

package Person;

Class code range to the last line of the script file, or to a package before the next keyword.


Creating and Using Objects

Create a class instance (object) we need to define a constructor, most programs use the class name as a constructor, Perl can use any name.

You can use a variety of variables as Perl Perl object. In most cases we will use the reference to the array or hash.

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

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

Examples are as follows:

package Person;
sub new
{
    my $class = shift;
    my $self = {
        _firstName => shift,
        _lastName  => shift,
        _ssn       => shift,
    };
    # 输出用户信息
    print "名字:$self->{_firstName}\n";
    print "姓氏:$self->{_lastName}\n";
    print "编号:$self->{_ssn}\n";
    bless $self, $class;
    return $self;
}

Next, we create an object:

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

Definition method

Perl class methods only, but it is a Perl subroutine, also known as member functions.

Object-oriented Perl Perl method definition does not provide any special syntax, but the first parameter specifies the method for the referenced object or package.

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

Next we define a way to get the name:

sub getFirstName {
    return $self->{_firstName};
}

The same can also write:

sub setFirstName {
    my ( $self, $firstName ) = @_;
    $self->{_firstName} = $firstName if defined($firstName);
    return $self->{_firstName};
}

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

#!/usr/bin/perl 

package Person;

sub new
{
    my $class = shift;
    my $self = {
        _firstName => shift,
        _lastName  => shift,
        _ssn       => shift,
    };
    # 输出用户信息
    print "名字:$self->{_firstName}\n";
    print "姓氏:$self->{_lastName}\n";
    print "编号:$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;

employee.pl script code is as follows:

#!/usr/bin/perl

use Person;

$object = new Person( "小明", "王", 23234345);
# 获取姓名
$firstName = $object->getFirstName();

print "设置前姓名为 : $firstName\n";

# 使用辅助函数设置姓名
$object->setFirstName( "小强" );

# 通过辅助函数获取姓名
$firstName = $object->getFirstName();
print "设置后姓名为 : $firstName\n";

After executing the above program, the output is:

$ perl employee.pl
名字:小明
姓氏:王
编号:23234345
设置前姓名为 : 小明
设置后姓名为 : 小强

inherit

Perl class methods in succession by @ISA array, the array which contains other packages (class) name, inherit the variable must be explicitly set.

Multiple inheritance is the @ISA array comprising a plurality of class (package) name.

The method can only be inherited through @ISA, data can not be inherited.

Next we create a class Employee inherits Person class.

Employee.pm file code is as follows:

#!/usr/bin/perl

package Employee;
use Person;
use strict;
our @ISA = qw(Person);    # 从 Person 继承

Now Employee class contains all the methods and properties of the Person class, we enter the following code in main.pl file and execute:

#!/usr/bin/perl

use Employee;

$object = new Employee( "小明", "王", 23234345);
# 获取姓名
$firstName = $object->getFirstName();

print "设置前姓名为 : $firstName\n";

# 使用辅助函数设置姓名
$object->setFirstName( "小强" );

# 通过辅助函数获取姓名
$firstName = $object->getFirstName();
print "设置后姓名为 : $firstName\n";

After executing the above program, the output is:

$ perl main.pl
名字:小明
姓氏:王
编号:23234345
设置前姓名为 : 小明
设置后姓名为 : 小强

Method overrides

The above example, Employee class extends the Person class, but if the Person class methods can not meet the demand, it is necessary to rewrite its methods.

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

#!/usr/bin/perl

package Employee;
use Person;
use strict;
our @ISA = qw(Person);    # 从 Person 继承

# 重写构造函数
sub new {
    my ($class) = @_;

    # 调用父类的构造函数
    my $self = $class->SUPER::new( $_[1], $_[2], $_[3] );
    # 添加更多属性
    $self->{_id}   = undef;
    $self->{_title} = undef;
    bless $self, $class;
    return $self;
}

# 重写方法
sub getFirstName {
    my( $self ) = @_;
    # 这是子类函数
    print "这是子类函数\n";
    return $self->{_firstName};
}

# 添加方法
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 main.pl file and execute:

#!/usr/bin/perl

use Employee;

$object = new Employee( "小明", "王", 23234345);
# 获取姓名,使用修改后的构造函数
$firstName = $object->getFirstName();

print "设置前姓名为 : $firstName\n";

# 使用辅助函数设置姓名
$object->setFirstName( "小强" );

# 通过辅助函数获取姓名
$firstName = $object->getFirstName();
print "设置后姓名为 : $firstName\n";

After executing the above program, the output is:

$ perl main.pl
名字:小明
姓氏:王
编号:23234345
这是子类函数
设置前姓名为 : 小明
这是子类函数
设置后姓名为 : 小强

Loading default

If the class in the current, the current class of all the base class, and class methods UNIVERSAL requested can not be found, then looks for a method named AUTOLOAD () again. If found AUTOLOAD, it will call, while setting the fully qualified name of the global variable $ AUTOLOAD value of the missing methods.

If not, then it failed Perl and error.

If you do not want to inherit the base class AUTOLOAD, very simple, just one sentence:

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 in the destructor when you can a method called "DESTROY" is defined in the class. It will automatically call the appropriate time, and to perform additional cleanup actions according to what you mean.

package MyClass;
...
sub DESTROY
{
    print "MyClass::DESTROY called\n";
}

Perl object reference will be passed to DESTROY as the only parameter. Note that this quote is read-only, which means you can not access the $ _ [0] to modify it. (Translator's Note: See perlsub) but the object itself (such as "$ {$ _ [0]" or "@ {$ _ [0]}" and "% {$ _ [0]}", etc.) or can be written.

If you re-bless the object reference before the destructor returns, Perl will then call you to re-bless DESTROY method of that object after the destructor returns. This allows you to have the opportunity to call the base class or you specify destructor other classes. It should be noted, DESTROY can also be invoked manually, but is usually not necessary.

After the release of the current object, other objects contained in the current object is automatically released.


Examples of object-oriented Perl

We can be further understood by the following examples Perl object-oriented applications:

#!/usr/bin/perl

# 下面是简单的类实现
package MyClass;

sub new
{
   print "MyClass::new called\n";
   my $type = shift;            # 包名
   my $self = {};               # 引用空哈希
   return bless $self, $type;   
}

sub DESTROY
{
   print "MyClass::DESTROY called\n";
}

sub MyMethod
{
   print "MyClass::MyMethod called!\n";
}


# 继承实现
package MySubClass;

@ISA = qw( MyClass );

sub new
{
   print "MySubClass::new called\n";
   my $type = shift;            # 包名
   my $self = MyClass->new;     # 引用空哈希
   return bless $self, $type;  
}

sub DESTROY
{
   print "MySubClass::DESTROY called\n";
}

sub MyMethod
{
   my $self = shift;
   $self->SUPER::MyMethod();
   print "   MySubClass::MyMethod called!\n";
}

# 调用以上类的主程序
package main;

print "调用 MyClass 方法\n";

$myObject = MyClass->new();
$myObject->MyMethod();

print "调用 MySubClass 方法\n";

$myObject2 = MySubClass->new();
$myObject2->MyMethod();

print "创建一个作用域对象\n";
{
  my $myObject2 = MyClass->new();
}
# 自动调用析构函数

print "创建对象\n";
$myObject3 = MyClass->new();
undef $myObject3;

print "脚本执行结束...\n";
# 自动执行析构函数

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