Beginning Perl Reading Notes ~ Chapter 13

Source: Internet
Author: User
Chapter 2: References
  • References are declared as scalar types (named variables starting with $), and reference is obtained using the \ operator.

    • Modifying the referenced variable is equivalent to modifying the reference pointing to the actual data.
    • Take variable reference: My $ scalar_r =\$ scalar;
    • Reference to the list: My $ array_r =\@ array;
    • Reference for hashing: My $ hash_r =\% hash;
  • Solve the problem that the list cannot be nested by referencing:

 

My @ array1 = (10, 20, 30, 40, 50 );
My @ array2 = (1, 2, \ @ array1, 3, 4 );

 

  • Because \ @ array1 is essentially a scalar, the list is not flat and the nested hierarchy is retained.
  • Reference to the anonymous list: Replace () in the list with []: My $ array_r = [1, 2, 3, 4, 5];
  • Reference to anonymous hash: Replace the hash () with {}: My $ hash_r = {Apple => "Pomme", pear => "poire "};
  • Using {$ var_r} To unreference referenced Variables
    • List

 

My @ array = (1, 2, 3, 4, 5 );
My $ array_r =\@ array;
My @ array2 =@{$ array_r}; # copied the array.

 

    • Hash is similar to list
  • For array reference, $ {$ ref} can be abbreviated as $ ref->. For example, you can describe $ {$ ref} [2] to $ ref-> [2]. note $ {ref} [2]} [1] as $ ref-> [2]-> [1], for more information, see $ ref-> [2] [1].
  • Use UNDEF to destroy a reference: UNDEF $ ref; Perl maintains a reference count for the referenced data. When the count is reduced to 0, the referenced data is destroyed and the memory space is released.
  • Using references makes it possible to represent complex data structures. These data structures include matrices (multi-dimensional arrays), linked lists, trees, and graphs.
  • Some ideas: the reference of C/C ++ is mainly for transferring addresses. Unlike pointers and references in C/C ++, Perl references include scalar, list, and hash in Perl) generalized (or unified) representation. After referencing, you can represent scalar, list, and hash as scalar (because the address is essentially an unsigned integer, this is similar to void * in C ). By referencing, you can solve the problem that Perl cannot store lists with nested hierarchies and cannot represent complex data structures.
Chapter 2: modules
  • The module is a Perl source code file. Compared with the common. pl source code file, the module has the following two differences:

    • The extension is not PL, but PM (this is not a mandatory condition)
    • The last sentence is a 1; (or return true; or any statement that returns the true value) Mandatory
  • Do is used to embed a. pl script or. PM module anywhere in the Perl code. The syntax is do "FILENAME". Perl will search for filename in the path of @ INC.
    • If you execute do 'inc. pl' in Main. pl; note that the code in Inc. pl cannot access the lexical variable defined in Main. pl.
  • Require is used to embed a module anywhere in the Perl code. The syntax is require "filename"; or require modulename; when require modulename; is used, modulename is like module: submodule :: subsubmodule, which represents a file. /module/submodule/subsubmodule. PM
    • Unlike do, require only supports embedded modules. Therefore, the require file must end with a true statement.
    • Only one file is embedded once, even if multiple require statements are written for the same file
  • Use is used to embed a module anywhere in Perl code. The syntax is use modulename; modulename is the same as modulename in require.
    • Unlike require, use is executed before compilation. That is to say, even if the module in use is written in the last sentence of the code, it will be executed first.

 

- Do Require Use
Supported Source code Module Module Module
Syntax Do 'filename '; Require 'filename ';
Require modulename;
Use modulename;
Number of processes Embedded several times and processed several times Only once Only once
File does not exist Skip, no error reported Error Error
Execution time Runtime Runtime Compile time (first process)

 

  • The @ INC variable is also a common Perl list and can be changed. Therefore, you can add a path to it by yourself (using unshift or push)
  • The package packagename should be declared at the beginning of the module file. The packagename is like package: subpackage: subsubpackage. For the function sub1 in package: subpackage, the call method is package: subpackage:: subsubpackage: sub1
    • Note that the package declares the module name, while the module names used by require and use are actually path names, which are different from the module names. For example, there is a module named. /m1/test1.pm. The package declaration is package M1: Test2. The package contains a function sub1, which is stored in main. use/require M1: test1 in PL; M1: Test2: sub1 () in calling ()
    • Of course, for clarity and ease of management, the module name and module File Name and path should be consistent
  • You can use the exporter class to simplify the writing of function calls in the package. When you do not use exporter, you must write a call such as package: subpackage: subsubsubpackage: sub1, which is too long-winded. When writing a package, you can inherit exporter:

 

Package Acme: webserver: loggerexporter;
# Acme/webserver/loggerexporter. PM
Use strict;
Use warnings;
# Become an exporter and export the functions
Use exporter;
Use base 'exister ';
Our @ export = QW (open_log close_log write_log log_level );
When you call open_log, you can call the full write operation:
Acme: webserver: loggerexporter: open_log ()
Abbreviated call:
Open_log ()

 

  • You can also declare the module to be imported when using the module:
Use Data: dumper QW (dumper );
# You can directly call dumper ()
Several common packages
  • Data: dumper is a string package that serializes variables into Perl syntax. It is very convenient to serialize the list and hash.
  • File: find is a function that traverses a folder and processes each file in it. Its usage is file: Find (\ & wanted, "/home/Simon /");
    • The first parameter wanted is a callback function that applies to each file. The second parameter is the execution folder.
    • The current directory is switched to the directory where the current file is located each time the callback is executed.
    • The relative path of the current directory is $ file: Find: Dir.
    • $ _ Is the file name of the current file
    • $ File: Find: name indicates the full name (including directory) of the current file)
  • Getopt: STD and getopt: Long are two packages that process command line parameters. You can resolve the abbreviated command line parameters, such as-Al, to two parameters A and L, you can also resolve command line parameters such as-a arg1-l arg2 to hash ing.
  • File: spec is a package that processes path strings, including path string simplification, path overlay, and path parsing.
  • Benchmark is a performance test package. It can be executed several times over a code block to measure the performance parameters.
  • Win32 is a package that encapsulates some Win32 APIs, including Win32: Sound, Win32: tieregistry, etc.
Chapter 2: Object-oriented Perl
  • There is no real "class" in Perl. The so-called class is actually a package.
  • To define a class, declare a package: package person;
  • The class constructor is named new, that is, sub new {...}
  • Initialize the class object through $ OBJ = new person (); or $ OBJ = person-> New ();
  • Constructor sub new points:
    • The first parameter (@ _ [0]) of the parameter table is the class name, and the second parameter is the parameter passed in when the constructor is called.
    • Implement functions similar to member variables by passing in hash
    • After an object reference is generated, you must use the bless () function to convert the referenced type.
    • The last sentence must return the generated object reference.

 

# Class definition
Package person;

Sub new {# at this time _ @ is ('person ', 'name', 'cars', 'gender', 'male ')
$ Classname = shift; # obtain the class name. At this time, $ classname is 'person ', _ @ is ('name', 'cars', 'gender', 'male ')
My $ self = {@ _}; # convert the input parameter to a hash. $ self is ('name' => 'cars', 'gender' => 'male ')
Bless $ self, $ classname # convert reference $ self to $ classname type
Return $ self; # The returned person object is a hash containing all member variables.
}

# Class usage
$ Person = person-> New ('name' => 'cars', 'gender' => 'male ');

 

  • The variables defined in the package are class variables, that is, static member variable, which cannot be accessed directly. You must define the accesser (accessor, that is, the get/set function)
  • Key Points of member functions:
    • The member functions whose names start with underscore _ are private
    • The first parameter of the function (I .e. @ _ [0]) is the object reference, and the second parameter starts as the function parameter.

 

# Class definition
Package person;

Sub new {...} # omitted
Sub _ init {...} # private function
Sub name {
My $ self = shift; # reference the call object
My $ name = shift; # Take the second parameter
$ Self-> {name} = $ name if defined $ name; # If a name is input, set the name to the input value.
Return $ self-> {name}; # Return the name value.
}

# Class usage
$ Person = person-> New ('name' => 'cars', 'gender' => 'male ');
$ Person-> name ('Caesar '); # Set the name to 'Caesar'
Print $ person-> name (), "\ n"; # print the name. 'Caesar 'is printed'

 

  • For object destruction, refer to Chapter 11 to reference the data destruction method.
Postscript

What impressed me with Perl:

  • Simple and Easy-to-use text I/O and regular expressions make Perl a powerful tool for text processing
  • It provides many UNIX APIs and the flexibility of the script language. Perl is suitable for UNIX system management.

I personally think that the two difficulties in Perl are also the failure of Perl:

  • Reference)

    • The automatic one-dimensional List mechanism is inexplicable. In Perl, scalar, list, and hash have different lexical identities ($, @, %, list, and hash content are all used (), the list value is [], and the hash value is {}), after it is referenced, there is a set of different lexical functions for unreferencing, which makes it easy to get dizzy.
  • Object-oriented (OO)
    • The oo mechanism in Perl is a bit half-left, just a few lines that must be written in the constructor:
My $ classname = shift;
My $ self = {@_};
Bless $ self, $ classname;
Return $ self;
    • And my $ self = shift, which must be written in the first sentence of the function, is very annoying and repetitive. If this is really an OO language, this should be done by the compiler.
    • According to the introduction on the Perl page on Wikipedia, oo is a new feature added to Perl 5. This shows that Perl was not designed as an OO programming language at the earliest, therefore, the OO feature in Perl 5 can be seen as an upgrade in procedural languages. For example, the first sentence of each function requires my $ self = shift, which is similar to the this pointer in C ++, except that C ++ is completely revolutionary as a new language, this pointer is automatically provided by the compiler and does not need to be obtained manually. Compared with C ++, the OO in Perl is more like the OO implemented in C language. If you have time, you can go to object-oriented programming with ANSI-C. this book describes the technical details of implementing oo features in C language. "through this book, you can understand C ++, Java, classes, inheritance, instances, connections, methods, objects, and Polymorphism in Python and other object-oriented languages... how are they implemented. it allows you to write beautiful and reusable code through C. "(The above text comes from Douban.com border.
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.