Perl5 OOP learning notes page 1/2

Source: Internet
Author: User
ArticleDirectory
    • Class and object member functions

After learning the basic syntax of Perl, I learned a little about OOP in Perl. I don't know if there is any difference between the OOP versions of Perl, but I learned perl5, so I wrote the version number in the title. I am worried because I have learned that the OOP part of PhP4 and PhP5 is quite different.
To learn oop of Perl, the two most critical tasks are package and bless. As long as you understand these two things, you will learn the first half.
Perl Package
The Perl Package is similar to Java. Java package uses the directory in classpath as the root, and defines and searches for hierarchical package names by directory. Perl is similar. It uses the directory in the @ INC array as the root and searches for hierarchical package names by directory. However, the definition of Perl package does not need to correspond to the directory structure. I have not studied specific rules, because it is a good habit to define a package by directory structure.
Compared with Java, Perl package is also interesting. Each package of Java corresponds to a directory, and the last class file corresponds to the class name. Perl simplifies, and the package directly references both the Directory and file name. For example
In Java, name. jamesfancy. myclass corresponds to/name/jamesfancy/myclass. Class, Source code It is written in two sentences. CopyCode The Code is as follows: package name. jamesfancy;
Class myclass {....}
Package name. jamesfancy;
Class myclass {....}

In Perl, name: jamesfancy: myclass should deal with/name/jamesfancy/myclass. PM. Only one package in the source code indicatesCopy codeThe Code is as follows: package name: jamesfancy: myclass;
Package name: jamesfancy: myclass;

for the content in the package, that is, the variable and the sub- Program , let's talk about the difference later.
bless function
bless is a function used to bind a class to a referenced type variable. It's strange why Perl uses this word, but it doesn't matter. We can think of it as something like adding a buff to someone through the blessing skills of a game priest, bless binds a class to a variable of the reference type. From then on, this variable is blessed with the variables and subroutines in this class.
bless is generally used: Bless ($ reference variable, Class Name);
reference variable may seem to be any reference type variable. I tried scalar, both array and hash can be referenced successfully. In addition to bless, this referenced variable can be called an object. Of course, it is still a reference and an object reference.
it is worth noting that although this object has class variables and subroutines, we should regard the variables and subroutines of the classes it owns as static. In other words, is a member of the class. At this point, the processing of subprograms is special, but at least class variables, that is, package variables, do not belong to objects. Therefore, the data of all objects is stored in the original data referenced by the object. Since everyone is used to the storage of object data as key-value pairs, the reference variables of bless are generally referenced by hash.
is it abstract? For example. If you do not know enough about the OOP member functions, you can only look at the first sentence of the test function of each class in the following example. copy Code the code is as follows: # test. pl
package testscalar;
sub test {
my $ this = shift ();
Print ("\ Nin testscalar: Test () \ n ");
Print (" scalar: \ N $ {$ this} \ n ");
}

Package testarray;
Sub test {
My $ this = shift ();
Print ("\ Nin testarray: Test () \ n ");
Print ("array: \ n ");
Foreach my $ item (@ {$ this }){
Print ("$ item \ n ");
}
}

Package testhash;
Sub test {
My $ this = shift ();
Print ("\ Nin testhash: Test () \ n ");
Print ("hash: \ n ");
While (My ($ key, $ value) = each % {$ this }){
Printf ("%-4 s = % s \ n", $ key, $ value );
}
}

Package main;

My $ name = "James fancy ";
My $ objscalar =\$ name;
My $ objarray = ['James ', 'fancy', 'jenny '];
My $ objhash = {'name' => 'James ', 'age' => 30 };

Bless ($ objscalar, 'testscalar ');
Bless ($ objarray, 'testarray ');
Bless ($ objhash, 'testhash ');

$ Objscalar-> test ();
$ Objarray-> test ();
$ Objhash-> test ();

_ End __

In testscalar: Test ()
Scalar:
James fancy

In testarray: Test ()
Array:
James
Fancy
Jenny

In testhash: Test ()
Hash:
Name = James
Age = 30

As shown in the preceding example, three types of references are converted into objects. The reason for writing three classes instead of one is to output different types of data in test.

Class and object member functions

A member function is a subroutine defined in a package. Member functions are not static or non-static, but I would rather think of them as static functions, because although they can be called as class member functions, it can also be called using object member functions, but when called as an object member function, Perl secretly passes in object reference. This also explains why the first sentence in a member function is usually

Copy code The Code is as follows: My $ this = shift ();

Of course, $ this is just a local variable, not a keyword. You can also replace it with another name. For example, many people like to use $ self or $ me.
What is the difference between calling a member function using classes and objects? Let's look at another example:Copy codeThe Code is as follows: # test. pl
Package myclass;

Sub test {
My ($ this, @ ARGs) = @_;
Print ('-' x 40, "\ n ");
Print ("\ $ this is [$ this], ref of \ $ this is [", ref ($ this), "] \ n ");
Print ("ARGs: [@ ARGs] \ n ");
}

Package main;

$ OBJ = {};
Bless ($ OBJ, 'myclass ');

Myclass-> test ("myclass-> test (...)");
$ Obj-> test ("\ $ obj-> test (...)");

_ End __
----------------------------------------
$ This is [myclass], ref of $ this is []
ARGs: [myclass-> test (...)]
----------------------------------------
$ This is [myclass = hash (0x178a44)], ref of $ this is [myclass]
ARGs: [$ obj-> test (...)]

The result shows that no matter which method is called, the first parameter is secretly transmitted by Perl. If it is a class call, the first parameter is the class. If it is an object call, the first parameter is this object. Therefore, you only need to compare the results of REF ($ this) with the class name to determine which call is required. Therefore, a member function with good fault tolerance needs to judge the first input parameter at the beginning, suchCopy codeThe Code is as follows: Sub Foo {
My $ this = shift ();
Return unless ($ this ne 'myclass ');
# Other statements
}

There is another question: Since the subroutines defined in the package are all member functions, what is the difference between a package that is not a class and a package that is a class? There is no difference in structure, and the only difference is in processing. When calling a subroutine, Perl does not stick a class or object to the top of the parameter list, but it does when calling a member function. Therefore, the difference is determined by your call method.

It is okay to call the object member to say $ obj-> Foo (). But how do I know whether to call the class member or the subroutine in the package when calling the class member? It depends on whether it is called through "->" or. The following example is helpful:Copy codeThe Code is as follows: # test. pl
Package myclass;
Use Data: dumper;
Sub test {
Print ('-' x 40, "\ n ");
Print (dumper (@_));
}

Package main;

Myclass-> test ("myclass-> test (...)");
Myclass: Test ("myclass: Test (...)");

_ End __
----------------------------------------
$ Var1 = 'myclass ';
$ Var2 = 'myclass-> test (...)';
----------------------------------------
$ Var1 = 'myclass: Test (...)';

Obviously, the subroutine called through ":" Is not inserted by Perl into a parameter of the reference class.

Constructor
Perl's OOP does not specify a special constructor, so you can regard any sub-program as a constructor. Of course, what matters is the content. Since the script is not usually written to you by yourself, you should name the constructor new according to your habits. According to the habits of most OOP languages, the new function usually returns an object or its reference and pointer. Therefore, in Perl, it is a good habit to include the bless action in the new function to return an object reference. Then a simple new function looks like this:Copy codeThe Code is as follows: Sub new {
My $ this = {};
Bless ($ this );
}

This new function generates a hash reference, bless, and returns it. If you are wondering why the return statement is not displayed here, we recommend that you check the information about the return value in the subroutine. By the way, check the description of the bless function. Let's take a look at the complete program to learn how to use the new function.

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.