PERL5 13th Perl Object-oriented programming

Source: Internet
Author: User
Tags autoload file copy perl interpreter perl script


13th Perl Object-oriented programming

by Flamephoenix

I. Introduction of the Module
Second, the class in Perl
Third, create the class
Four, the constructor function

    • Instance variable


V. Methods
Vi. output of the method
Vii. Invocation of methods
Eight, heavy
Nine, the destruction function
X. Inheritance
Xi. Overloading of methods
12. Some comments on Perl classes and objects

This chapter describes how to use Perl's object-oriented programming (OOP) features and how to build objects, including inheritance, method overloading, and data encapsulation.
I. Introduction of the Module
Module is the Perl package (Pachage). Objects in Perl are based on references to data items in a package. (see chapter X for references).
See Http://www.metronet.com's Perlmod and perlobj.
When you use object-oriented programming in other languages, you declare a class and then create an object (instance) of that class, and all objects of a particular class behave the same way, determined by the class method, and you can create a class by defining a new class or inheriting from an existing class. People who are already familiar with object-oriented programming can encounter many familiar terms here. Perl has always been an object-oriented language, and in PERL5, syntax has changed slightly, and the use of objects has been more normalized.
The following three definitions are essential for understanding how objects, classes, and methods work in Perl.
The. Class is a Perl package that contains classes that provide object methods.
The. method is a Perl subroutine, and the class name is its first parameter.
An. Object is a reference to a data item in a class.
Second, the class in Perl
Again, a Perl class is just a package. When you see a "class" in a Perl document, think of it as a "package". PERL5 syntax can create classes, if you are already familiar with C + +, then most of the syntax you have mastered. The concept differs from PERL4 in that it identifies both the base class and the inheriting class (subclass) with a double colon (::).
An important feature of object-oriented is inheritance. The inheritance attribute in Perl is not exactly the same as other object-oriented languages, it inherits only the method, and you must use your own mechanism to implement the data inheritance.
Because each class is a package, it has its own namespace and its own symbolic name associative array (see chapter X associative arrays), so each class can use its own set of independent symbol names. In combination with a reference to a package, you can use the single quotation mark (') operator to locate a variable in a class, with the positioning of members in a class such as: $class ' $member. In Perl5, you can use double colons instead of single quotes to get references, such as: $class ' $member and $class:: $member the same.
Third, create the class.
This section describes the steps necessary to create a new class. The example used below is to create a simple class called cocoa, whose function is to output the necessary parts of the source code for a simple Java application. Rest assured, this example does not require you to have Java knowledge, but it does not make you a Java expert, the purpose of which is to describe the concept of creating classes.
First, create a package file named cocoa.pm (the extension PM is the default extension for the package, meaning the Perl Module). A module is a package, and a package is a class. Before doing anything else, first add "1;" This line, when you add other lines, remember to keep "1;" As the last line. This is a required condition for the Perl package, otherwise the package will not be processed by Perl. The following is the basic structure of the file.

Package
Cocoa;

#
# Put "require" statements in for all required,imported packages
#

#
# Just Add code here
#

1; # terminate the package with the required 1;

Next, we add a method into the package to make it a class. The first method to be added is new (), which must be called when the object is created, and the new () method is the constructor of the object.
Four, the constructor function
A constructor is a subroutine of a class that returns a reference that is related to the class name. Combining a class name with a reference is called "blessing" an object because the function that establishes the binding is named Bless (), whose syntax is:
Bless yereference [, classname]
Yereference is a reference to the "Blessed" object, classname is an optional, specified object gets the package name of the method, and its default value is the current package name.
The method for creating a build function is to return a reference to an internal structure that has been combined with the class, such as:

Sub New {
My $this = {}; # Create An anonymous hash, and #self points to it.
Bless $this; # Connect The hash to the package Cocoa.
return $this; # Return The reference to the hash.
}

1;

{} Creates a reference to a hash table (that is, an associative array) that does not contain a key/value pair, and the return value is assigned to the local variable $this. The function bless () takes out the reference, tells the object that it refers to cocoa, and finally returns the reference. The return value of the function now points to this anonymous hash table.
When returned from the new () function, the $this reference is destroyed, but the calling function holds a reference to the hash table, so that the reference number of the Hashtable is not zero, allowing Perl to save the hash table in memory. Creating an object can be called as follows:
$cup = new Cocoa;
The following statement is an example of creating an object using the package:

1 #!/usr/bin/perl
2 push (@INC, ' pwd ');
3 Use Cocoa;
4 $cup = new Cocoa;

The first line indicates the location of the Perl interpreter, and in the second row, the current directory is added to the path look-up list @inc for the package to use. You can also create your module in a different directory and indicate the absolute path. For example, if you create a package in/home/test/scripts/, the second line should look like this:
Push (@INC, "/home/test/scripts");
In the third row, include the package cocoa.pm to get the functionality you want in the script. The USE statement tells Perl to look for the file cocoa.pm in the @inc path and include it in the parsed source file copy. Use statements are necessary for using classes. The four-line invocation of the new function creates the object, which is the beauty of Perl, and it is easily confused and powerful. There are several ways to create an object, which you can write:
$cup = Cocoa->new ();
If you are a C programmer, you can use a double colon to force the new () function in the cocoa package, such as:
$cup = Cocoa::new ();
You can add more code to the constructor, such as in cocoa.pm, you can output a simple declaration when each object is created, or you can initialize a variable or set an array or pointer with a constructor.
Attention:

1, must initialize the variable in the constructor function;
2, must use the My function in the method to create variables;
3, must not use local in the method, unless you really want to pass the variable to other subroutines;
4. Be sure not to use global variables in class modules.

Add the declared cocoa constructor as follows:

Sub New {
My $this = {};
print "\ n/* * * Created by COCOA.PM \ n * * Use at own risk";
print "\ n * * This code even get pass the Javac compiler?";
print "\ n **/\ n";
Bless $this;
return $this;
}

You can also simply invoke other functions inside or outside the package to do more initialization work, such as:

Sub New {
My $this = {}
Bless $this;
$this->doinitialization ();
return $this;
}

When you create a class, you should allow it to be inherited, and you should be able to call the new function as the first parameter, then the new function is like the following statement:

Sub New {
my $class = shift; # Get the Request class name
My $this = {};
Bless $this, $class # Use class name to bless () reference
$this->doinitialization (); return $this;
}

This method enables the user to make a call in one of the following three ways:

  • Cocoa::new ()
  • Cocoa->new ()
  • New Cocoa

It is possible to bless a reference object more than once, however, the new class that will be bless inevitably removes the object from the bless reference, which, for C and Pascal programmers, is like assigning a pointer to a allocated piece of memory and assigning the same pointer to another memory without releasing the previous memory. In summary, a Perl object can belong to only one class at a time.
What is the real difference between an object and a reference? Perl objects are bless to belong to a class, references are not, if the reference is bless, it will belong to a class, it becomes an object. Objects know which class they belong to, and references do not belong to any class.

    • Instance variable



The argument to the new () function as a constructor is called an instance variable. Instance variables are used for initialization when each instance of an object is created, for example, a new () function can be used to name each instance of an object.
You can save an instance variable with an anonymous hash table or an anonymous array.
The code for the hash table is as follows:

Sub New {
My $type = shift;
my%parm = @_;
My $this = {};
$this->{' name '} = $parm {' name '};
$this->{' x '} = $parm {' x '};
$this->{' y '} = $parm {' Y '};
Bless $this, $type;
}

The code saved with the array is as follows:

Sub New {
My $type = shift;
my%parm = @_;
My $this = [];
$this->[0] = $parm {' Name '};
$this->[1] = $parm {' x '};
$this->[2] = $parm {' Y '};
Bless $this, $type;
}

When constructing an object, you can pass parameters as follows:
$mug = cocoa::new (' Name ' = ' top ', ' x ' = =, ' y ' = 20);
The operator = = is the same as the comma-operated service, but is good readability. The access methods are as follows:
Print "Name= $mug->{' Name '}\n";
Print "x= $mug->{' x '}\n";
Print "y= $mug->{' y '}\n";
V. Methods
The Perl class method is simply a Perl subroutine, also known as a member function. The Perl method definition does not provide any special syntax, but specifies that the first parameter of the method is the object or its referenced package. There are two methods of Perl: Static and Virtual methods.
The first parameter of a static method is the class name, and the first argument of the virtual method is the reference to the object. The way the method handles the first parameter determines whether it is static or virtual. Static methods generally ignore the first parameter because they already know which class they are in, and the constructor is a static method. A virtual method usually first shift the first parameter to the variable self or this, and then use the value as a normal reference. Such as:

1. Sub Namelister {
2.     My $this = shift;
3.     My ($keys, $value);
4.     while (($key, $value) = each (% $this)) {
5.         print ' \t$key is $value. \ n ";
6.    }
7.}

Vi. output of the method
     if you want to refer to the COCOA.PM package now, you will get a compile error saying that no method is found because the COCOA.PM method has not yet been output. The output method requires the exporter module, adding the following two lines at the beginning of the package:
    require exporter;
     @ISA = QW (exporter);
     These two lines contain the EXPORTER.PM module and add the exporter class name to the @isa array for lookup. Next, you can list your own class methods in the @export array. For example, to output methods Closemain and Declaremain, the statements are as follows:
     @EXPORT = QW (Declaremain, closemain);
The inheritance of the     perl class is implemented through the @isa array. @ISA array does not need to be defined in any package, however, once it is defined, Perl considers it as a special array of directory names. It is similar to the @inc array, @INC is the search path that contains the file. The @ISA array contains the class (package) name, which is searched for in the @isa package when a method is not found in the current package. The @ISA also contains the base class name for the current class inheritance. All methods called in the
     class must belong to the same class or base class defined by the @isa array. If a method is not found in the @isa array, Perl looks in the AutoLoad () subroutine, and this optional subroutine is defined in the current package with a sub. If using the Autoload subroutine, you must use the use Autoload; The statement calls the AUTOLOAD.PM package. The AutoLoad subroutine attempts to mount the called method from the installed Perl library. If AutoLoad also fails, Perl then makes the last attempt to the universal class, and if it still fails, Perl generates an error about the unresolved function.
Vii. Method Invocation
     methods for invoking an object are two methods, one is through the object's reference (virtual method), and the first is to use the class name (static method) directly. Of course the method must have been output. Now add some methods to the cocoa class with the following code:

Package Cocoa;
Require exporter;
@ISA = QW (exporter);
@EXPORT = QW (Setimports, Declaremain, Closemain);
#
# This routine creates the references for imports in Java functions
#
Sub setimports{
My $class = Shift @_;
my @names = @_;
foreach (@names) {
Print "Import". $_ . "; \ n";
}
}
#
# This routine declares the main function in a Java script
#
Sub declaremain{
My $class = Shift @_;
My ($name, $extends, $implements) = @_;
print "\ n public class $name";
if ($extends) {
Print "Extends". $extends;
}
if ($implements) {
Print "Implements". $implements;
}
print "{\ n";
}
#
# This routine declares the main function in a Java script
#
Sub closemain{
Print "} \ n";
}
#
# This subroutine creates the header for the file.
#
Sub New {
My $this = {};
print "\ n \ n * * Created by COCOA.PM \ n * * use at own risk \ n \ n";
Bless $this;
return $this;
}

1;

Now, let's write a simple Perl script that uses this class method, and here's the scripting code that creates a Java applet source code skeleton:

#!/usr/bin/perl
Use Cocoa;
$cup = new Cocoa;
$cup->setimports (' Java.io.InputStream ', ' java.net.* ');
$cup->declaremain ("MSG", "Java.applet.Applet", "Runnable");
$cup->closemain ();

This script creates a Java applet called MSG that expands (extend) the Java.applet.Applet applet and makes it operational (runnable), where the last three lines can be written as follows:

Cocoa::setimports ($cup, ' java.io.InputStream ', ' java.net.* ');
Cocoa::d eclaremain ($cup, "MSG", "Java.applet.Applet", "Runnable");
Cocoa::closemain ($cup);

The results of the operation are as follows:

/*
* * Created by COCOA.PM
* * Use at own risk
*/
Import Java.io.InputStream;
Import java.net.*;

public class MSG extends Java.applet.Applet implements Runnable {
}

Note: If you invoke a method (also called an indirect call) with an operator, the argument must be enclosed in parentheses, such as: $cup->setimports (' Java.io.InputStream ', ' java.net.* '), and a double-colon invocation such as: Cocoa: : Setimports ($cup, ' java.io.InputStream ', ' java.net.* '); parentheses can also be written: Cocoa::setimports $cup, ' java.io.InputStream ', ' Java.net.* ';
Eight, heavy
Sometimes you need to specify which class to use, such as when two different classes have the same method. Suppose the class espresso and Qava both define method grind, you can use the:: operator to specify a method that uses Qava:
$mess = Qava::grind ("Whole", "Lotta", "bags");
Qava::grind ($mess, "whole", "Lotta", "bags");
You can choose which class to use depending on how the program is running, which can be done by using a symbolic reference to invoke:
$method = $local? "Qava::": "Espresso::";
$cup->{$method}grind (@args);
Nine, the destruction function
The number of links to the Perl tracking object, which is automatically destroyed when the last application of an object is released to the memory pool. The destruction of the object occurs when the code stops and the script is about to end. For global variables, destructors occur after the last line of code runs.
If you want to gain control before the object is freed, you can define the Destroy () method. DESTROY () is called before the object is freed, allowing you to do some cleanup work. The DESTROY () function does not automatically call other DESTROY () functions, and Perl does not do the built-in destruction work. If the constructor is multiple Bless,destroy () from the base class, you may need to call the DESTROY () function of the other class. When an object is disposed, all its contained object references are automatically freed and destroyed.
In general, you do not need to define the destroy () function, if necessary, in the form of the following:

Sub DESTROY {
#
# ADD code here.
#
}

For a variety of purposes, Perl uses a simple, reference-based garbage collection system. The number of references to any object must be greater than 0, otherwise the object's memory is freed. When the program exits, Perl has a thorough search and destroy function for garbage collection, and everything in the process is simply deleted. In Unix class systems, this is like redundancy, but this is really necessary in an inline system or multithreaded environment.
X. Inheritance
Class methods are inherited by @isa arrays, and the inheritance of variables must be explicitly set. The following example creates two classes bean.pm and COFFEE.PM, where COFFEE.PM inherits some of the features of BEAN.PM. This example shows how to inherit an instance variable from a base class (or a superclass) by calling the constructor of the base class and adding its own instance variable to the new object.
The BEAN.PM code is as follows:

Package Bean;
Require exporter;
@ISA = QW (exporter);
@EXPORT = QW (Setbeantype);

Sub New {
my $type = shift;
My $this = {};
$this->{' Bean '} = ' Colombian ';
Bless $this, $type;
return $this;
}

#
# This subroutine sets the class name
Sub setbeantype{
My ($class, $name) = @_;
$class->{' Bean '} = $name;
Print "Set bean to $name \ n";
}
1;

In this class, set an anonymous hash table with the $this variable and set the ' Bean ' type to ' Colombian '. Method Setbeantype () is used to change the ' Bean ' type, which uses the $class reference to gain access to the object hash table.
The COFFEE.PM code is as follows:

1  #
2  # The coffee.pm file to illustrate inheritance.
3  #
4  package Coffee;
5  require exporter;
6  require Bean;
7  @ISA = QW (exporter, Bean);
8  @EXPORT = QW (Setimports, Declaremain, Closemain);
9  #
# Set Item
One #
Ten sub setcoffeetype{
  My ($class, $name) = @_;
  $class->{' Coffee '} = $name;
  print "Set coffee type to $name \ n";
 }
#
# constructor
#
+ Sub New {
  my $type = shift;
  My $this = Bean->new (); ##### <-look here!!! # # #
  $this->{' Coffee '} = ' Instant '; Unless told otherwise
  bless $this, $type;
  return $this;
 }
1;

     6th require Bean; The statement contains the bean.pm file and all related functions, Method Setcoffeetype () is used to set local variables $class->{' Coffee ' The value of the}. In constructor new (), $this A pointer to the anonymous hash table returned by BEAN.PM, instead of creating a local one, the following two statements are separate from the hash table created by the Bean.pm constructor, which is independent of the situation and inheritance:
     my $this = {}; #非继承
    my $this = $theSuperClass->new (); #继承
     The following code shows how to invoke an inherited method:

1 #!/usr/bin/perl
2 push (@INC, ' pwd ');
3 Use Coffee;
4 $cup = new Coffee;
5 print "\ n--------------------Initial values------------\ n";
6 print "Coffee: $cup->{' Coffee '} \ n";
7 print "Bean: $cup->{' bean '} \ n";
8 print "\ n--------------------change Bean Type----------\ n";
9 $cup->setbeantype (' Mixed ');
Print "Bean Type is now $cup->{' bean '} \ n";
print "\ n------------------change Coffee Type----------\ n";
$cup->setcoffeetype (' Instant ');
Print "Type of coffee: $cup->{' coffee '} \ n";

The result of this code is output as follows:

--------------------Initial Values------------
Coffee:instant
Bean:colombian
--------------------Change Bean Type----------
Set Bean to Mixed
Bean Type is now Mixed
------------------Change Coffee Type----------
Set Coffee type to Instant
Type of Coffee:instant

The above code first outputs the values of the hash table indexed as ' Bean ' and ' Coffee ' when the object was created, and then calls each member function to change the value before outputting.
The COFFEE.PM method can have more than one parameter, now add the function Makecup () to the module, and the code is as follows:

Sub Makecup {
My ($class, $cream, $sugar, $dope) = @_;
print "\n================================== \ n";
Print "Making a cup \ n";
print "Add cream \ n" if ($cream);
print "Add $sugar sugar cubes\n" if ($sugar);
Print "Making some really addictive coffee;-) \ n" if ($dope);
print "================================== \ n";
}

This function can have three parameters, different numbers, values of parameters produce different results, for example:

1 #!/usr/bin/perl
2 push (@INC, ' pwd ');
3 Use Coffee;
4 $cup = new Coffee;
5 #
6 # with no parameters
7 #
8 print "\ n calling with no parameters: \ n";
9 $cup->makecup;
10 #
One # with one parameter
12 #
print "\ n calling with one parameter: \ n";
$cup->makecup (' 1 ');
15 #
# with Parameters
17 #
print "\ n calling with parameters: \ n";
$cup->makecup (1, ' 2 ');
20 #
# with all three parameters
22 #
print "\ n calling with three parameters: \ n";
$cup->makecup (' 1 ', 3, ' 1 ');

The result output is as follows:

Calling with no parameters:
==================================
Making a cup
==================================
Calling with one parameter:
==================================
Making a cup
ADD Cream
==================================
Calling with parameters:
==================================
Making a cup
ADD Cream
ADD 2 sugar cubes
==================================
Calling with three parameters:
==================================
Making a cup
ADD Cream
ADD 3 sugar cubes
Making some really addictive coffee;-)
==================================

In this example, the parameters of the function Makecup () can be either a string or an integer, and the result is the same, and you can separate the data processing areas of the two types. In the processing of parameters, you can set the default values, or you can give different processing according to the number of actual input parameter values.
Overloads of the Xi. subclass method
The benefit of inheritance is the ability to get the methods of the base class output, and sometimes the method overloads of the base class are needed to get more specific or different functionality. The following method Printtype () is added to the BEAN.PM class, and the code is as follows:

Sub Printtype {
My $class = Shift @_;
Print "The type of Bean is $class->{' bean '} \ n";
}

Then update its @export array to output:
@EXPORT = QW (Setbeantype, Printtype);
Now to call the function Printtype (), there are three ways to invoke it:

$cup->coffee::p rinttype ();
$cup->printtype ();
$cup->bean::p rinttype ();

The output is as follows:

The
type of Bean is Mixed
The type of Bean is Mixed
The type of Bean is Mixed

Why is it all the same? Because the function printtype () is not defined in the subclass, the methods in the base class are actually called. If you want the subclass to have its own printtype () function, it must be defined in the COFFEE.PM class:

#
# This routine prints the type of $class->{' Coffee '}
#
Sub Printtype {
My $class = Shift @_;
Print "The type of Coffee is $class->{' Coffee '} \ n";
}

Then update its @export array:
@EXPORT = QW (Setimports, Declaremain, Closemain, Printtype);
Now the output turns into:

The
type of Coffee is Instant
The type of Coffee is Instant
The type of Bean is Mixed

The method of the base class is now called only if the Bean:: is given, otherwise the method of the subclass is called directly.
So how do you call the base class method if you don't know the base class name? The method is to use pseudo-class reserved word super::. Use syntax within a class method such as: $this->super::function (... argument list ...); , it will look from the list of @isa. Just now the statement with SUPER:: Replace Bean:: Can be written as $cup->super::p Rinttype (); , the result output is the same as:

The
type of Bean is Mixed

12. Some comments on Perl classes and objects
The biggest benefit of OOP is code reuse. OOP uses data encapsulation to hide complex code, and Perl's packages and modules provide data encapsulation through the My function, but Perl does not guarantee that subclasses will not directly access the variables of the base class, which does reduce the benefits of data encapsulation, although this action can be done, but it is a very bad programming style.
Attention:

1. Be sure to access the class variables by means of methods.
2. Do not directly access the class variables from outside the module.

When you write a package, you should ensure that the conditions required by the method are already available or passed to it through parameters. Inside the package, you should ensure that access to global variables is only accessed using references passed by methods. For static or global data to be used by a method, it should be defined in the base class with local (), which is obtained by calling the base class. Sometimes subclasses may need to change this data, and at this point the base class may not know how to look for new data, so it is better to define a reference to that data, and the subclass and base class to change that data by reference.
Finally, you'll see the following ways to work with objects and classes:
Use Coffee::bean;
The meaning of this sentence is "to find bean.pm in the coffee subdirectory of all directories in the @inc array." If you move the bean.pm to the./coffee directory, the example above will work with this use statement. The benefit is that the code for the class is organized in a structured manner. Again, as in the following statement:
Use Another::sub::menu;
means the following subtree:
./another/sub/menu.pm

Previous chapter Next Chapter catalogue

PERL5 13th Perl Object-oriented programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.