Perl class is a Perl Package
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. Before doing other things, add the line "1;". When you add other rows, remember to keep "1;" as the last line. This is a required condition for a 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 first method to be added is new (), which must be called when an object is created, and the new () method is the object's constructor.
A constructor is a subprogram of A Class. It returns a reference related to the class name.
package person;
use strict;
sub new {
my $ class = shift ();
print ("Class = $ class \ n");
my $ self = {}; \\ Create a reference to a hash table without keys / values;
$ self-> {"name"} = shift ();
$ self-> {"sex"} = shift ();
bless $ self, $ class; \\ The reference is associated with the class name, the class name is optional
return $ self; \\ The return value points to the reference
}
After returning from new (), the $ self reference is destroyed, but the calling function saves the reference to the hash table, so the reference number of the hash table will not be zero. So that Perl keeps the hash table in memory
#! / usr / bin / perl
push (@ INC, ‘pwd’);
use person;
my $ cup = new person ("Tom", "man");
Comment
The second line \\ adds the current directory to the path search list @INC,
Or push (@ INC, dirname (__ FILE__)) uses File :: Basename module
The third line \\ tells Perl to find the file person.pm in the @INC path and include it in the parsed source file copy.
The fourth line \\ or my $ cup = person-> new ("Tom", "man"); person :: new ("Tom", "man");
note:
Be sure to initialize variables in the constructor;
Be sure to use the my function to create variables in the method;
You must not use local in methods unless you really want to pass variables to other subroutines;
Do not use global variables in class modules.
Perl method is a Perl subroutine
Perl object-oriented programming