Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use object-oriented programming of Perl

2025-02-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how to use Perl object-oriented programming. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

A brief introduction to the module

The module is the Perl package (pachage). Objects in Perl are based on references to data items in the package. (for references, see Chapter x references).

See http://www.metronet.com 's perlmod and perlobj for details.

When object-oriented programming in other languages, first declare a class and then create objects (instances) of that class. All objects of a particular class behave in the same way, determined by class methods. 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, the syntax has changed slightly to standardize the use of objects.

The following three definitions are critical to 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 * parameters.

The ◆ object is a reference to a data item in a class.

2. Classes in Perl

Again, a Perl class is just a package. When you see a reference to "class" in the Perl document, just think of it as a "package". The syntax of Perl5 can create classes, and if you are already familiar with Clippers, you have mastered most of the syntax. Unlike Perl4, the concept is to use a double colon (::) to identify base classes and inherited classes (subclasses).

An important feature of object-oriented is inheritance. The inheritance feature in Perl is not exactly the same as other object-oriented languages, it only inherits methods, you must use your own mechanism to achieve data inheritance.

Because each class is a package, it has its own namespace and its own associative array of symbolic names (see Chapter x associative array for details), so each class can use its own independent set of symbolic names. In conjunction with package references, you can use the single quotation mark (') operator to locate variables in a class, such as: $class'$member. In Perl5, you can use double colons instead of single quotation marks to get references, such as: $class'$member is the same as $class::$member.

Third, create classes.

This section describes the necessary steps to create a new class. The following example is to create a simple class called Cocoa, whose function is to output the necessary part of the source code for a simple Java application. Rest assured, this example does not require you to have knowledge of Java, but it does not make you an Java expert, and its purpose is to talk about the concept of creating classes.

First, create a package file named Cocoa.pm (the extension pm is the default extension of the package, meaning PerlModule). A module is a package, and a package is a class. Add the line "1;" before doing anything else, and when you add other lines, remember to keep "1;" as a line. This is a necessary condition for the Perl package, otherwise the package will not be processed by Perl.

Next, we add a method to the package to make it a class. The * 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.

4. The constructor of Perl object-oriented programming

The constructor is a subroutine of a class that returns a reference related to the class name. Combining a class name with a reference is called a "blessing" object, because the function that establishes the union is called bless (), and its syntax is:

BlessYeReference [, classname]

YeReference is a reference to the "blessed" object, and classname is optional, specifying the package name of the object's get method, whose default value is the current package name.

The method to create a build function is to return a reference to the internal structure that has been combined with the class, such as:

Subnew {my$this= {}; # Createananonymoushash,and#selfpointstoit. Bless$this;#ConnectthehashtothepackageCocoa. Return$this;#Returnthereferencetothehash. } 1

{} create a reference to a hash table (that is, an associative array) without key / value pairs, and the return value is assigned to the local variable $this. The function bless () fetches the reference and tells the object that it refers to Cocoa,*** and returns the reference. The return value of the function now points to the anonymous hash table.

After returning from the new () function, the $this reference is destroyed, but the calling function saves the reference to the hash table, so the number of references to the hash table will not be zero, causing Perl to keep the hash table in memory. You can call to create an object as follows:

$cup=newCocoa

The following statement is an example of creating an object using the package:

1 2push 2push (@ INC,'pwd'); 3 useCocoa; 4$ cup=newCocoa

The * line indicates the location of the Perl interpreter. In the second line, add the current directory to the path lookup list @ INC for use when looking for packages. You can also create your modules in different directories and indicate the absolute path. For example, if you create a package at / home/test/scripts/, the second line should be as follows:

Push (@ INC, "/ home/test/scripts")

In the third line, include the package Cocoa.pm to get the functionality needed in the script. The use statement tells Perl to find the file Cocoa.pm in the @ INC path and include it in the parsed copy of the source file. Use statements are required to use classes. The fourth line calls the new function to create an object, which is the beauty of Perl, its confusion, and its power. There are several ways to create an object, and you can write:

$cup=cocoa- > new ()

If you are a C programmer, you can use double colons 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, and you can use the constructor to initialize variables or set arrays or pointers.

Note:

1. Be sure to initialize variables in the constructor

2. Be sure to use the my function to create variables in the method

3. Never use local in a method unless you really want to pass variables to other subroutines

4. Never use global variables in the class module.

Plus the declared Cocoa constructor is as follows:

Subnew {my$this= {}; print "\ nn**Didthiscodeevengetpassthejavaccompiler *\ n**CreatedbyCocoa.pm\ n**Useatownrisk"; print "\ n**Didthiscodeevengetpassthejavaccompiler?"; print "\ nrabbit /\ n"; bless$this; return$this;}

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

Subnew {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 with the class name as * * arguments, so the new function looks like the following statement:

Subnew {my$class=shift;#Gettherequestclassname my$this= {}; bless$this,$class#Useclassnametobless () reference $this- > doInitialization (); return$this;}

This method allows the user to make calls in one of three ways:

Cocoa::new ()

Cocoa- > new ()

NewCocoa

You can bless a reference object multiple times, however, the new class that will be bless must remove the object from the bless reference. For C and Pascal programmers, this is like assigning a pointer to an allocated piece of memory and then assigning the same pointer to another piece of memory without freeing the previous one. In short, a Perl object can only belong to one class at a time.

What is the real difference between an object and a reference? The Perl object is bless to belong to a class, but the reference is not. If the reference is bless, it will belong to a class and become an object. An object knows which class it belongs to, while a reference does not belong to any class.

Instance variables of Perl object-oriented programming

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, you can use the new () function to give each instance of the object a name.

Instance variables can be saved using an anonymous hash table or an anonymous array.

The code for using the hash table is as follows:

Subnew {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 in the array is as follows:

Subnew {my$type=shift; my%parm=@_; my$this= []; $this- > [0] = $parm {'Name'}; $this- > [1] = $parm {' x'}; $this- > [2] = $parm {'y'}; bless$this,$type;}

When you construct an object, you can pass parameters as follows:

$mug=Cocoa::new ('Name'= >' top','x'= > 10 minute minute = > 20)

The operator = > has the same function as a comma server, but has good readability. The access method is as follows:

Print "Name=$mug- > {'Name'}\ n"

Print "xdistinct mug-> {'x'}\ n"

Print "yearly destroy mug-> {'y'}\ n"

5. The method of Perl object-oriented programming

The method of the Perl class is nothing more than a Perl subroutine, commonly known as a member function. Perl's method definition does not provide any special syntax, but specifies that the * parameters of the method are objects or their referenced packages. There are two methods for Perl: static and virtual.

The parameters of the static method are class names and the parameters of the virtual method are references to the object. The way a method handles * parameters determines whether it is static or virtual. Static methods generally ignore * parameters because they already know which class they are in, and the constructor is the static method. Virtual methods usually first shift * * parameters into variables self or this, and then use the value as a normal reference. Such as:

1.subnameLister {2. T$keyis$value transfer; 3.my ($keys,$value); 4.while (($key,$value) = each (% $this)) {5.print "\ t$keyis$value.\ n"; 6.} 7.}

VI. Output of the method

If you want to reference the Cocoa.pm package now, you will get a compilation error saying that the method was not found, because the Cocoa.pm method has not been output yet. The output method requires the Exporter module, adding the following two lines to the beginning of the package:

RequireExporter

@ ISA=qw (Exporter)

These two lines contain the upper Exporter.pm module and add the Exporter class name to the @ Isa array for lookup. Then list your own class methods in the @ export array. For example, if you want to output methods closeMain and declareMain, the statement is as follows:

@ EXPORT=qw (declareMain,closeMain)

The inheritance of the Perl class is achieved through the @ Isa array. The @ Isa array does not need to be defined in any package, however, once it is defined, Perl treats it as a special array of directory names. It is similar to the @ Inc array, where @ INC is the path to the containing file. The @ Isa array contains the name of the class (package). When a method is not found in the current package, look for it in the package in @ ISA. The @ ISA also contains the base class name inherited by the current class.

All methods called in a class must belong to the same class or the base class defined by the @ ISA array. If a method is not found in the @ Isa array, Perl looks for it in the AUTOLOAD () subroutine, an optional subroutine defined with sub in the current package. If you use the AUTOLOAD subroutine, you must call the autoload.pm package with the useAutoload; statement. The AUTOLOAD subroutine attempts to load the called method from the installed Perl library. If AUTOLOAD also fails, Perl makes another attempt to the UNIVERSAL class, and if it still fails, Perl generates an error about the unparsed function.

7. Method invocation

There are two ways to call a method of an object, one is through the reference to the object (virtual method), and the other is to directly use the class name (static method). Of course, the method must have been output.

Now that we write a simple Perl script that uses the method of this class, here is the script code to create a skeleton of the Javaapplet source code:

#! / usr/bin/perl useCocoa; $cup=newCocoa; $cup- > setImports ('java.io.InputStream','java.net.*'); $cup- > declareMain ("Msg", "java.applet.Applet", "Runnable"); $cup- > closeMain () This script creates a Javaapplet called Msg, which extends (extend) the java.applet.Applet applet and makes it runnable (runnable), where * three lines can also be written as follows: Cocoa::setImports ($cup,'java.io.InputStream','java.net.*'); Cocoa::declareMain ($cup, "Msg", "java.applet.Applet", "Runnable"); Cocoa::closeMain ($cup) The running results are as follows: / * * CreatedbyCocoa.pm * * Useatownrisk * / importjava.io.InputStream; importjava.net.*; publicclassMsgextendsjava.applet.AppletimplementsRunnable {}

Note: if you call a method (also called indirectly) with the-> operator, the parameters must be enclosed in parentheses, such as: $cup- > setImports ('java.io.InputStream','java.net.*'); and double colon calls such as: Cocoa::setImports ($cup,'java.io.InputStream','java.net.*'); you can also remove the parentheses and write: Cocoa::setImports$cup,'java.io.InputStream','java.net.*'.

VIII. Overloading of Perl object-oriented programming

Sometimes you need to specify the method of which class to use, such as when two different classes have methods of the same name. Assuming that both the classes Espresso and Qava define the method grind, you can specify the method that uses Qava with the:: operator:

$mess=Qava::grind ("whole", "lotta", "bags")

Qava::grind ($mess, "whole", "lotta", "bags")

You can choose which class's method to use according to the running of the program, which can be done by using symbolic references to call:

$method=$local? "Qava::": "Espresso::"

$cup- > {$method} grind (@ args)

9. The destructor of Perl object-oriented programming

Perl tracks the number of links to an object, and when an application of an object is released to the memory pool, the object is automatically destroyed. The object is destructed after the code stops and the script is about to end. For global variables, destructing occurs after a single line of code runs.

If you want to gain control before the object is released, you can define the DESTROY () method. DESTROY () is called before the object will be released, allowing you to do some cleanup work. The DESTROY () function does not automatically call other DESTROY () functions, and Perl does not do built-in destructing work. If the constructor bless,DESTROY () multiple times from the base class, you may need to call the DESTROY () function of another class. When an object is released, all object references contained in it are automatically released and destroyed.

In general, there is no need to define the DESTROY () function, which, if necessary, looks like this:

SubDESTROY {# # Addcodehere. #}

Perl uses a simple, reference-based garbage collection system for a variety of purposes. The number of references to any object must be greater than zero, otherwise the memory of the object will be freed. When the program exits, a thorough find and destroy function of Perl is garbage collected, and everything in the process is simply deleted. This may seem redundant in systems of the UNIX class, but it is really necessary in embedded systems or multithreaded environments.

X. inheritance

Class methods inherit through the @ ISA array, and variable inheritance must be explicitly set. The following example creates two classes, Bean.pm and Coffee.pm, where Coffee.pm inherits some of the functions of Bean.pm. This example demonstrates how to inherit an instance variable from a base class (or superclass) by calling the constructor of the base class and adding its own instance variable to the new object.

11. Overloading of subclass methods

The advantage of inheritance is that you can get the functionality of the methods that the base class outputs, and sometimes you need to overload the methods of the base class to get more specific or different functionality. Let's add the method printType () to the Bean.pm class with the following code:

SubprintType {my$class=shift@_; print "ThetypeofBeanis$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 call it:

$cup- > Coffee::printType ()

$cup- > printType ()

$cup- > Bean::printType ()

The outputs are as follows:

ThetypeofBeanisMixed

ThetypeofBeanisMixed

ThetypeofBeanisMixed

Why are they 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, you must define it in the Coffee.pm class:

# # Thisroutineprintsthetypeof$class- > {'Coffee'} # subprintType {my$class=shift@_; print "ThetypeofCoffeeis$class- > {' Coffee'}\ n";}

Then update its @ export array:

@ EXPORT=qw (setImports,declareMain,closeMain,printType)

Now the output is as follows:

ThetypeofCoffeeisInstant

ThetypeofCoffeeisInstant

ThetypeofBeanisMixed

Now the method of the base class is called only when the Bean:: is given, otherwise the method of the subclass is called directly.

So how to call the base class method if you don't know the base class name? The way to do this is to use the pseudo class to reserve the word SUPER::. Use syntax such as $this- > SUPER::function (.. argumentlist...) within class methods, which will look in the @ ISA list. Instead of Bean:: with SUPER::, the statement just now can be written as $cup- > SUPER::printType ();, and the output is the same as:

ThetypeofBeanisMixed

XII. Some comments on Perl classes and objects

The benefit of OOP is code reuse. OOP uses data encapsulation to hide some complex code, and Perl packages and modules provide data encapsulation functionality through my functions, 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.

Note:

1. Be sure to access class variables through methods.

2. Do not access class variables directly from outside the module.

When writing a package, you should ensure that the conditions required by the method are in place or passed to it through parameters. Within the package, you should ensure that access to global variables is accessed only by references passed through the method. The static or global data to be used by the method should be defined with local () in the base class, and the subclass is obtained by calling the base class. Sometimes, a subclass may need to change this data, and the base class may not know how to find new data, so * defines a reference to the data, and both the subclass and the base class change the data by reference.

*, you will see the following ways to use objects and classes:

Usecoffee::Bean

Look for Bean.pm in the Coffee subdirectory of all the directories in the @ INC array. If you move Bean.pm to the. / Coffee directory, the above example will use this use statement to work. This has the advantage of organizing the code of the class in an organized manner. For example, the following statement:

UseAnother::Sub::Menu

This means that the subdirectory tree is as follows:

. / Another/Sub/Menu.pm

This is the end of this article on "how to use Perl object-oriented programming". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report