Perl 14th PERL5 Packages and modules

Source: Internet
Author: User
Tags perl interpreter posix


14th Chapter PERL5 Packages and modules

by Flamephoenix

First, Require function
1. Require functions and sub-Libraries
2. Specify the Perl version with require
Second, the package
1, the definition of the package
2, switch between the package
3. Main Package
4, the package reference
5. No current package specified
6. Packages and subroutines
7. Define private data with package
8. Package and System variables
9. Access Symbol table
Third, the module
1. Create a module
2. Import Module
3. Pre-defined modules

First, Require function
You can use the Require function to split a program into multiple files and create a library of functions. For example, in myfile.pl, there is a defined Perl function, which can be require ("myfile.pl"); Included in the program. When the Perl interpreter sees this statement, it looks for the file myfile.pl in the directory specified by the built-in array variable @inc. If found, the statement in the file is executed, otherwise the program terminates and outputs an error message:
Can ' t find myfile.pl in @INC
As a subroutine invocation parameter, the value of the last expression in the file becomes the return value, and the Require function checks to see if it is zero and terminates if it is zero. For example, the final statement of myfile.pl is:
Print ("Hello, world!\n");
$var = 0;
Because the last statement value is zero, the Perl interpreter outputs the following error message and launches:
Myfile.pl did not reture true value
You can pass parameters such as simple variables or array elements to require, such as:

@reqlist = ("file1.pl", "file2.pl", "file3.pl");
Require ($reqlist [$]);
Require ($reqlist [$]);
Require ($reqlist [$]);

You can also not specify a file name, which is:
Require
At this point, the value of the variable $_ is passed as the file name to require.
Note: If there are multiple directories in @inc that contain the same file, only the first one is included.
1. Require functions and sub-Libraries
You can use the Require function to create a sub-library that can be used for all Perl programs, in the following steps:

A, determine the storage sub-Library directory
B. Put the subroutine in a separate file and place the file in the Sub-Library directory
C, the end of each file with a non-0-value statement, the simplest way is the statement 1;
D. require contains one or more required files in the main program.
E. When running the main program, specify the sub-Library directory with the-I option, or add the directory to the @inc array before calling require.

For example, suppose your Perl sub-Library is stored in the directory/u/perldir, and the subroutine mysub stored in the file mysub.pl. Now to include the file:
Unshift (@INC, "/u/perldir");
Require ("mysub.pl");
The call to Unshift adds the directory/u/perldir to the @inc array, and the call to require includes the contents of the mysub.pl file as part of the program.
Attention:

1. You should use Unshift to add directories to the @inc instead of push. Because push is added to the end of @inc, the directory will be last searched.
2. If your library file name has the same name as a file in/usr/local/lib/perl, it will not be included because require contains only the first of the files with the same name.

2. Specify the Perl version with require
In Perl 5, you can use the Require statement to specify the Perl version that the program needs to run. When the Perl interpreter sees require followed by a number, it runs the program only if its version is above or equal to that number. For example, the following statement indicates that the program runs only if the Perl interpreter is version 5.001 or higher:
Require 5.001;
Second, the package
The Perl program stores the names of variables and subroutines in the symbol table, and the collection of names in the Perl symbol table is called the package.
1, the definition of the package
In a program you can define multiple packages, each with a separate symbol table with the following definition syntax:
Package mypack;
This statement defines a package named Mypack, from which all variables and subroutine names are stored in the associated symbol table, until another package statement is encountered.
Each symbol table has its own set of variables, subroutine names, and the names of the groups are irrelevant, so you can use the same variable names in different packages and represent different variables. Such as:

$var = 14;
Package mypack;
$var = 6;

The first statement creates a variable $var and stores it in the main symbol table, and the third statement creates another variable with the same name $var and stores it in the symbol table of the Mypack package.
2, switch between the package
You can switch back and forth between packages at any time in the program, such as:

1: #!/usr/local/bin/perl
2:
3:package Pack1;
4: $var = 26;
5:package Pack2;
6: $var = 34;
7:package Pack1;
8:print ("$var \ n");

The results of the operation are as follows:

$ program
26
$

The third line defines the package Pack1, the fourth row creates the variable $var, is stored in the symbol table of the package Pack1, the fifth line defines the new package Pack2, and the sixth row creates another variable $var, stored in the symbol table of the package Pack2. In this way, two separate $var are stored in different packages. The seventh line also specifies Pack1 as the current package, because the package pack1 has been defined so that all variables and subroutines are defined and called by the name stored in the package's symbol table. Therefore, the call to $var on line eighth is a $var in the Pack1 package with a value of 26.
3. Main Package
The default symbol table for the name of the storage variable and subroutine is associated with the package named Main. If other packages are defined in the program, you can reassign the main package when you want to switch back to using the default symbol table:
Package main;
In this way, the next program seems to have never defined a package, and the names of variables and subroutines are stored as usual.
4, the package reference
In a package, you can refer to variables or subroutines in other packages by adding a package name and a single quotation mark to the variable name, such as:

Package
Mypack;
$var = 26;
Package main;
Print ("$mypack ' var\n");

Here, $mypack ' var is the variable $var in the Mypack package.
Note: In Perl 5, the package name and variable name are separated by a double colon, which is $mypack::var. Single quotation marks are still supported in the way they are quoted, but may not be supported in future versions.
5. No current package specified
In Perl 5, you can specify no current package with the following statement:
Package
At this point, all variables must explicitly indicate the owning package name, otherwise it will be invalid-error.
$mypack:: var = 21; #ok
$var = 21; #error-no Current Package
This is not the case until the current package is specified with the packages statement.
6. Packages and subroutines
The definition of a package affects all statements in the program, including subroutines, such as:

Package
Mypack;
Subroutine MySub {
Local ($myvar);
# stuff goes here
}

Here, mysub and MyVar are all part of the package mypack. In the package mypack out with subroutine MySub, specify the package: $mypack ' mysub.
You can switch packages in a subroutine:

Package pack1;
Subroutine MySub {
$var 1 = 1;
Package Pack2;
$var 1 = 2;
}

This code creates two variable $var1, one in package Pack1, and one in Package Pack2, in which local variables in the package can only be used in statement blocks such as their defined subroutines, just like normal local variables.
7. Define private data with package
The most common use of a package is to use a file that contains the global variables used by subroutines and subroutines, to define such packages for subroutines, to ensure that the global variables used by subroutines are not used elsewhere, and that such data is private data. Further, you can ensure that the package name is not available elsewhere. Private Data examples:

1:package Privpack;
2: $valtoprint = 46;
5 |
4:package main;
5: # This function was the link to the outside world.
6:sub Printval {
7: &privpack ' Printval ();
8:}
9:
10:package Privpack;
11:sub Printval {
12:print ("$valtoprint \ n");
13:}
14:
15:package main;
16:1; # return value for require

This subroutine can produce output only after calling Printval.
The document is divided into two parts: parts and private parts that are connected to the outside world. The former is the default main package, which is the package privpack. The subroutine Printval defined in line 6th to 8th can be called by another program or subroutine. Printval the value of the output variable $valtoprint, this variable is defined and used only in the package privpack. 15th, 16 line to ensure that it is used by other programs with require statement is working normally, 15 will be the current package set back to the default package main,16 row return non-0 value so that require does not error.
8. Package and System variables
The following variables work in the main package even if they are called from other packages:

  • File variables stdin, STDOUT, STDERR and ARGV
  • Variables%env,%inc, @INC, $ARGV and @ARGV
  • Other system variables that contain special characters

9. Access Symbol table
Find the symbol table in the program available array%_package, where the package is the name of the packages to which the symbol table you want to access belongs. For example,%_main contains the default symbol table.
It is usually not necessary to find the symbol table yourself.

Third, the module
Most large programs are split into multiple parts, each of which typically contains one or more sub-programs and related variables that perform a specific task or multiple tasks. Parts that assemble variables and subroutines are called program modules.
1. Create a module
In Perl 5, you create a module with packages by creating a package and having it in a file with the same name. For example, a package named Mymodult is stored in the file mymodult.pm (the extension. PM represents the Perl Module). The following example module Mymodult contains subroutines myfunc1 and MYFUNC2 and variables $myvar1 and $myvar2.

1: #!/usr/local/bin/perl
2:
3:package mymodule;
4:require exporter;
5: @ISA = QW (exporter);
6: @EXPORT = QW (myfunc1 myfunc2);
7: @EXPORT_OK = QW ($myvar 1 $myvar 2);
8:
9:sub myfunc1 {
:   $myvar 1 + = 1;
11:}
:
13:sub myfunc2 {
:   $myvar 2 + = 2; 
:}

Line 3rd to 7th is the standard way to define Perl modules. Line 3rd defines the package, and line 4th contains the built-in Perl module exporter,6, 7 rows of subroutines and variable outputs to connect with the outside world. Line 6th creates a special array named @export, in which subroutines can be called by other programs, where MYFUNC1 and MYFUNC2 can be accessed. Any other subroutine defined in the module but not assigned to the array @export is private and can only be called inside the module. Line 7th creates another special array named @export_ok, which contains variables that can be accessed by external programs, which contain $myvar1 and $myvar2.
2. Import Module
Import the module into your Perl program using the USE statement, the following sentence imports the MyModule module:
Use MyModule;
In this way, the subroutines and variables in the module MyModule can be used.
To cancel the import module using the no statement, the following sentence cancels the import of the MyModule module:
No mymodule;
Here is an example of importing a module and canceling an import, using an integer module that requires all numeric operations to be based on integers, and the floating-point numbers are converted to integers before the operation.

1: #!/usr/local/bin/perl
2:
3:use integer;
4: $result = 2.4 + 2.4;
5:print ("$result \ n");
6:
7:no integer;
8: $result = 2.4 + 2.4;
9:print ("$result \ n");

The program output is as follows:

$ program
4
4.8
$

If the use or no statement appears in a statement block, it only works within the valid range of the block, such as:

Use
integer;
$result 1 = 2.4 + 2.4;
if ($result 1 = = 4) {
no integer;
$result 2 = 3.4 + 3.4;
}
$result 3 = 4.4 + 4.4;

The resulting output is as follows:

4
6.8
8

Here, the no statement is valid only in the IF statement, and the IF statement still uses the integer module, so 4.4 is converted to 4 before adding.
3. Pre-defined modules
Perl 5 provides many useful pre-defined modules that can be canceled with the use Import and no statements. Here are some of the most useful modules in the library:

Integer Using integer arithmetic
Diagnostics Output more diagnostic information (warning)
中文版 Allow English names to be used as aliases for system variables
Env Perl module for importing environment variables
Posix The POSIX standard (IEEE 1003.1) Perl interface
Socket Socket processing mechanism for loading C language

A complete list of predefined modules is available in the Perl documentation.
Note: Perl 5 users around the world have written many useful modules, and the Perl documentation for CPAN (comprehensive Perl Archive Network) has its complete list. For more information on CPAN, see its website: http://www.perl.com/perl/CPAN/README.html.

Previous chapter Next Chapter catalogue

Perl 14th PERL5 Packages and modules

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.