Perl object oriented


Release date:2023-10-20 Update date:2023-10-21 Editor:admin View counts:168

Label:

Perl object oriented

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

  • One is based on the anonymous hash table, the essence of each object instance is a reference to the anonymous hash table. In this anonymous hash table, all the instance properties are stored.

  • Second, based on the array approach, when defining a class, we will create an array for each instance property, and the essence of each object instanceis a reference to a row of indexes in these arrays. In these arrays, all the instance properties are stored.

Object-oriented basic concept

There are many basic concepts of object orientation, and here we accept three: objects, classes, and methods.

  • Object: an object is a reference to a data item in a class. .

  • Class: a class is a Perl package that contains classes that provide object methods.

  • Method: the method is a Perl subroutine, and the class name is its first argument.

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

Definition of class

A class is just a simple package.

You can use a package as a class and the functions in the package as methodsof the class.

Perl’s packages provide independent namespaces, so different package methodsdo not conflict with variable names.

The file suffix of the Perl class is .pm .

Next, let’s create a Person class:

package Person;

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

Create and use objects

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

You can use a variety of Perl variables as Perl objects. In most cases, we use reference arrays or hashes.

Next, we will work for Person class creates a constructor that uses a hash reference to Perl.

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

Examples are as follows:

Example

packagePerson;subnew{my$class=shift;my$self={\_firstName=>shift,\_lastName=>shift,\_ssn=>shift,};#
Output user information print"name:$self->{_firstName}\\n";print"surname:
$self->{_lastName}\\n";print"number:$self->{_ssn}\\n";bless$self,$class;return$self;}

Next let’s create an object:

$object = new Person( "Xiaoming", "Wang", 23234345);

Definition method

The method of the Perl class is just a Perl subroutine, commonly known as a member function.

The method definition of Perl in Perl object orientation does not provide any special syntax, but specifies that the first parameter of the method is the object or its referenced package.

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

Next, let’s 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, let’s modify Person.pm code for the file, as follows:

Example

#!/usr/bin/perlpackagePerson;subnew{my$class=shift;my$self={\_firstName=>shift,
\_lastName=>shift,\_ssn=>shift,};#
Output user information print"name:$self->{_firstName}\\n";print"name:
$self->{_lastName}\\n";print"number:$self->{_ssn}\\n";
bless$self,$class;return$self;}subsetFirstName{my($self,
$firstName)=@\_;$self->{\_firstName}=$firstNameifdefined($firstName);
return$self->{\_firstName};}subgetFirstName{my($self)=@\_;
return$self->{\_firstName};}1;

employee.pl script code is as follows:

Example

#!/usr/bin/perluse Person;$object=newPerson("Xiaoming","Wang",23234345);#
Get name$firstName=$object->getFirstName();print"Name before setting as
:$firstName\\n";# Using auxiliary functions to set names $object->setFirstName("Xiaoqiang");#
Obtaining names through auxiliary functions$firstName=$object->getFirstName();print"Set the name to
:$firstName\\n";

After executing the above procedure, the output result is:

$perl employee.pl
Name: Xiaoming
Surname: Wang
Number: 23234345
Name before setting: Xiaoming

Inherit

The class method in Perl passes through the @ISA array inheritance, this array contains the names of other packages (classes), variable inheritance must be explicitly set.

Multi-inheritance. That’s @ISA the array contains multiple class (package) names.

Pass through @ISA can only inherit methods, not data.

Next, let’s create a Employee class inheritance Person class.

Employee.pm file code is as follows:

Example

#!/usr/bin/perlpackageEmployee;use Person;use
strict;our@ISA=qw(Person);# Inherit from Person

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

Example

#/ Usr/bin/plus Employee$ Object=newEmployee ("Xiaoming", "Wang", 23234345)#
Get name $firstName=$object ->getFirstName(); Print "The name before setting is
: $firstName n "; # Use auxiliary functions to set the name $object ->setFirstName (" Xiaoqiang ")#
Obtain the name $firstName=$object ->getFirstName() through the auxiliary function; Print "Set the name to
: $firstName n ";

After executing the above procedure, the output result is:

$perl main.pl
Name: Xiaoming
Surname: Wang
Number: 23234345
Name before setting: Xiaoming
After setting, the name is: Xiaoqiang

Method rewriting

In the above example, the Employee class inherits the Person class,but if Person method of the class cannot meet the requirements, soits method needs to be rewritten.

Next, we are in Employee class, and overrides the Person method ofthe class:

Example

#/ Usr/bin/perlpackageEmployee; Use Person; Use
Strict; our@ISA =Qw (Person)# Inherit from Person#
Rewrite the constructor subnew {my ($class)=@ _#
Call the constructor of the parent class, my $self=$class ->SUPER:: new ($ _ [1], $ _ [2], $ _ [3])#
Add more attributes $self ->{ _id}=undef$ Self ->{ _title}=undef; Bless $self, $class; Return $self;}#
Rewrite method subgetFirstName {my ($self)=@ _#
This is a subclass function print "This is a subclass function n"; Return $self ->{ _firstName};}#
Add method subsetLastName {my ($self, $lastName)=@ _; $self ->{ _lastName}=$lastNameifdefined
($lastName); Return $self ->{ lastName};} SubgetLastName {my ($self)=@ _; return $self ->{ _lastName};} 1;

We’re here main.pl enter the following code in the file and execute:

Example

#/ Usr/bin/plus Employee$ Object=newEmployee ("Xiaoming", "Wang", 23234345)#
Obtain the name using the modified constructor $firstName=$object ->getFirstName(); Print "The name before setting is
: $firstName n "; # Use auxiliary functions to set the name $object ->setFirstName (" Xiaoqiang ")#
Obtain the name $firstName=$object ->getFirstName() through the auxiliary function; Print "Set the name to
: $firstName n ";

After executing the above procedure, the output result is:

$perl main.pl
Name: Xiaoming
Surname: Wang
Number: 23234345
This is a subclass function
Name before setting: Xiaoming
This is a subclass function
After setting, the name is: Xiaoqiang

Load by default

If in the current class, all the base classes of the current class, and UNIVERSAL class, the requested method is not found in the class, and it will look again for a method named AUTOLOAD() way to do it. If you find it, AUTOLOAD is called and the global variable is set at the same time $AUTOLOAD is the fully qualified name of the missing method

If not, then Perl fails and makes an error.

If you don’t want to inherit the base class AUTOLOAD is very simple, just one sentence:

sub AUTOLOAD;

Destructor and garbage collection

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

If you want to do something during destructing, you can define a method called “DESTROY” in the class. It will be called automatically at the right time and perform additional cleanup actions as you want.

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

Perl passes a reference to the object to DESTROY as the only parameter. Note that this reference is read-only, which means that you cannot access the $_[0] to modify it. (translator’s note: see perlsub ) but the object itself (such as "${$_[0]" pr "@{$_[0]}" and "%{$_[0]}" Etc.) it is still writable.

If you revisit before the destructor returns bless if the object is referenced, Perl will then call you after the destructor returns bless of the object of DESTROY method. This gives you the opportunity to callthe base class or the destructor of other classes you specify. What needs to be explained is that DESTROY .It can also be called manually, but it is usually not necessary to do so.

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

Perl object-oriented instance

We can further understand the object-oriented application of Perl through the following examples:

Example

#/ Usr/bin/perl#
The following is a simple class implementation packageMyClass; Subnew {print "MyClass:: new
Called n "; my $type=shift; # Package name my $self={}#
Referencing empty hash returnbless $self, $type;} SubDESTROY {print "MyClass:: DESTROY
Called n ";} subMyMethod {print" MyClass:: MyMethod called! N ";}#
Inherit and implement packageMySubClass@ ISA=qw (MyClass); Subnew {print "MySubClass:: new
Called n "; my $type=shift; # Package name my $self=MyClass ->new#
Referencing empty hash returnbless $self, $type;} SubDESTROY {print "MySubClass:: DESTROY
Called n ";} subMyMethod {my $self=shift; $self ->SUPER:: MyMethod(); print" MySubClass:: MyMethod
Called\ \N ";} # Call the main program packagemain; print" of the above class to call MyClass
Method n "; $myObject=MyClass ->new(); $myObject ->MyMethod(); print" call
MySubClass
Method n "; $myObject 2=MySubClass ->new(); $myObject 2->MyMethod(); print" Create a scope object n ";
{my $myObject 2=MyClass ->new();}#
Automatically call the destructor function print "Create object n"$ MyObject 3=MyClass ->new(); Undef
$myObject 3; Print "Script execution ended... n"#
Automatically execute destructors

Execute the above program, and the output is as follows:

Calling the MyClass method
MyClass:: new called
MyClass:: MyMethod called!
Calling the MySubClass method
MySubClass:: new called
MyClass:: new called
MyClass:: MyMethod called!
MySubClass:: MyMethod called!
Create a scope object
MyClass:: new called
MyClass: DESTROY called
create object
MyClass:: new called
MyClass: DESTROY called
Script execution ended
MyClass: DESTROY called
MySubClass: DESTROY called

Powered by TorCMS (https://github.com/bukun/TorCMS).