PERL5 OOP Learning Notes 1th/2 page _perl

Source: Internet
Author: User
Tags constructor scalar
After learning Perl's basic syntax, learning Perl's OOP is a bit of a experience. I don't know if there are any differences between OOP in Perl versions, but I'm a Perl5 of learning, so I write the version number on the title. Because there is no small difference between the OOP part of PHP4 and PHP5, there is a concern.
The two key things to learn about Perl's OOP are package and bless. Just get the two things clear and learn to be half the size.
The package of Perl
It feels like Perl's package and Java are really similar. Java package is based on the directory in classpath, defined and searched by directory for the hierarchical package name. Perl is similar in that it takes the directory in the @inc array as the root and searches for the hierarchical package name by directory. However, one difference is that Perl's package definition does not seem to need to correspond to the directory structure. Specifically what kind of rules I did not study, because it is a good habit to define package by directory structure.
It's a bit more interesting than the Java,perl package. Each layer of Java package corresponds to a directory, and the last is a class file corresponding to the name. Perl is simplified, and package directly refers to directories and file names. Like what
Java, Name.jamesfancy.MyClass, corresponding to the/name/jamesfancy/myclass.class, in the source code is divided into two sentences to write
Copy Code code as follows:

Package name.jamesfancy;
Class MyClass {...}
Package name.jamesfancy;
Class MyClass {...}

Perl, Name::jamesfancy::myclass, is dealing with/name/jamesfancy/myclass.pm, in the source code only one sentence package explains
Copy Code code as follows:

Package name::jamesfancy::myclass;
Package name::jamesfancy::myclass;

As for the contents of the package, that is, variables and subroutines, as for the difference, later on.
Bless function
Bless is used to bind a class to a function that refers to a type variable. It's strange why Perl uses this word, but it doesn't matter, we can think of it as a bit: like a game where a priest adds a buff to someone by blessing his skill, bless binds a class to a variable of a reference type, and this variable is blessed. You have the variables and subroutines in this class.
The use of bless is usually: Bless ($ reference variable, class name);
Reference variables can seem to be any type of reference variable, I tried Scalar,array and hash references, can be successful. Outside of bless, this reference variable can be called an object, and of course it is still a reference, a reference to an object.
It is also important to note that although this object has the variables and subroutines of the class, we should consider the variables and subroutines of the class that it owns as static, in other words, the members of the class. At this point, the subroutine processing will be more special, but at least the class variable, that is, the package variable, is not part of the object. Therefore, the data for all objects is saved in the original data referenced by the object. Since we're all used to the fact that the object data is saved as a key-value pair, the bless reference variable is usually a hash reference.
Is it abstract? Give an example. If you are not familiar with the member functions of OOP, it is not good to read the first sentence in the test function of each class in the following example.
Copy Code code 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 (I ($key, $value) = each%{$this}) {
printf ("%-4s =%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 you can see from the example above, 3 types of references are converted to objects, respectively. The reason to write a Class 3 instead of 1 is primarily to output different types of data in test.

member functions for classes and objects

A member function is a subroutine defined in package. member functions are not static and non-static, but I'd rather everyone think of it as a static function, because although it can be invoked as a class member function, or as a function of an object member, Perl sneaks into an object reference when invoked as an object member function. This also explains why the first phrase in the usual member function is often

Copy Code code as follows:

My $this = Shift ();

Of course, the $this here is just a local variable, not a keyword, and you can replace it with a different name. For example, many people like to use $self, or $me and so on.
What if, for a member function, the class and object are invoked separately? Look at one more example:
Copy Code code as follows:

# test.pl
Package MyClass;

Sub Test {
My ($this, @args) = @_;
Print ('-' x, ' \ n ');
Print ("\ $this is [$this], ref-$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 (...)]

As you can see from the results, the first parameter, regardless of the method invocation, is secretly passed in by Perl. If it is a class call, the first argument is the class. If it is an object invocation, the first argument is the object. Therefore, the only way to compare the results of ref ($this) with the class name is to see what kind of call it is. So, a member function with good fault tolerance, the first to judge the incoming parameters, such as
Copy Code code as follows:

Sub Foo {
My $this = Shift ();
return unless ($this ne ' MyClass ');
# Other statements
}

Here's another question: since the subroutine defined in package is a member function, what's the difference between the package of a class and the package of a class? There is no difference in structure, the only difference is in the process. Perl does not hard-code a class or object at the top of the argument list when calling a subroutine, but when calling a member function, the difference is based on the way you call it.

Call object member Fortunately, $obj->foo (), but when calling a class member, how do you know if it is the calling class member or the subroutine in the package? It depends on the "->" or "::" to call. The following examples can help you understand:
Copy Code code as follows:

# test.pl
Package MyClass;
Use Data::D umper;
Sub Test {
Print ('-' x, ' \ n ');
Print (Dumper (@_));
}

Package main;

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

__end__
----------------------------------------
$VAR 1 = ' MyClass ';
$VAR 2 = ' myclass->test (...) ';
----------------------------------------
$VAR 1 = ' myclass::test (...) ';

Obviously, the subroutine invoked by the "::" is not crammed into a reference class parameter by Perl.

Constructors
Perl's OOP does not specify a specific constructor, so you can think of any subroutine as a constructor, and, of course, what is important. Since the script is not usually written to yourself, it is still the custom to name the constructor new. According to the custom of most OOP languages, the new function usually returns an object or its reference, pointer. So in Perl, this new function returns an object reference, which, of course, is a good habit of including the bless action in the new function. So a simple new function looks like this:
Copy Code code as follows:

Sub New {
My $this = {};
Bless ($this);
}

This new function produces a hash reference, bless it, and returns it. If you are wondering why you do not see the return statement here, it is recommended that you look at the information about the returned value in the subroutine and check the description of the Bless function. Take a look at the complete program to find out how to use the new function.
Current 1/2 page 12 Next read the full text

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.