⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch12_01.htm

📁 By Tom Christiansen and Nathan Torkington ISBN 1-56592-243-3 First Edition, published August 1998
💻 HTM
📖 第 1 页 / 共 2 页
字号:
<HTML><HEAD><METANAME="DC.title"CONTENT="Perl Cookbook"><METANAME="DC.creator"CONTENT="Tom Christiansen &amp; Nathan Torkington"><METANAME="DC.publisher"CONTENT="O'Reilly &amp; Associates, Inc."><METANAME="DC.date"CONTENT="1999-07-02T01:40:58Z"><METANAME="DC.type"CONTENT="Text.Monograph"><METANAME="DC.format"CONTENT="text/html"SCHEME="MIME"><METANAME="DC.source"CONTENT="1-56592-243-3"SCHEME="ISBN"><METANAME="DC.language"CONTENT="en-US"><METANAME="generator"CONTENT="Jade 1.1/O'Reilly DocBook 3.0 to HTML 4.0"><LINKREV="made"HREF="mailto:online-books@oreilly.com"TITLE="Online Books Comments"><LINKREL="up"HREF="index.htm"TITLE="Perl Cookbook"><LINKREL="prev"HREF="ch11_16.htm"TITLE="11.15. Program: Binary Trees"><LINKREL="next"HREF="ch12_02.htm"TITLE="12.1. Defining a Module's Interface"></HEAD><BODYBGCOLOR="#FFFFFF"><img alt="Book Home" border="0" src="gifs/smbanner.gif" usemap="#banner-map" /><map name="banner-map"><area shape="rect" coords="1,-2,616,66" href="index.htm" alt="Perl Cookbook"><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><p><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch11_16.htm"TITLE="11.15. Program: Binary Trees"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 11.15. Program: Binary Trees"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch12_02.htm"TITLE="12.1. Defining a Module's Interface"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 12.1. Defining a Module's Interface"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="chapter"><H1CLASS="chapter"><ACLASS="title"NAME="ch12-17119">12. Packages, Libraries, and Modules</A></H1><DIVCLASS="htmltoc"><P><B>Contents:</B><BR><ACLASS="sect1"HREF="#ch12-32032"TITLE="12.0. Introduction">Introduction</A><BR><ACLASS="sect1"HREF="ch12_02.htm"TITLE="12.1. Defining a Module's Interface">Defining a Module's Interface</A><BR><ACLASS="sect1"HREF="ch12_03.htm"TITLE="12.2. Trapping Errors in require or use">Trapping Errors in require or use</A><BR><ACLASS="sect1"HREF="ch12_04.htm"TITLE="12.3. Delaying use Until Run Time">Delaying use Until Run Time</A><BR><ACLASS="sect1"HREF="ch12_05.htm"TITLE="12.4. Making Variables Private to a Module">Making Variables Private to a Module</A><BR><ACLASS="sect1"HREF="ch12_06.htm"TITLE="12.5. Determining the Caller's Package">Determining the Caller's Package</A><BR><ACLASS="sect1"HREF="ch12_07.htm"TITLE="12.6. Automating Module Clean-Up">Automating Module Clean-Up</A><BR><ACLASS="sect1"HREF="ch12_08.htm"TITLE="12.7. Keeping Your Own Module Directory">Keeping Your Own Module Directory</A><BR><ACLASS="sect1"HREF="ch12_09.htm"TITLE="12.8. Preparing a Module for Distribution">Preparing a Module for Distribution</A><BR><ACLASS="sect1"HREF="ch12_10.htm"TITLE="12.9. Speeding Module Loading with SelfLoader">Speeding Module Loading with SelfLoader</A><BR><ACLASS="sect1"HREF="ch12_11.htm"TITLE="12.10. Speeding Up Module Loading with Autoloader">Speeding Up Module Loading with Autoloader</A><BR><ACLASS="sect1"HREF="ch12_12.htm"TITLE="12.11. Overriding Built-In Functions">Overriding Built-In Functions</A><BR><ACLASS="sect1"HREF="ch12_13.htm"TITLE="12.12. Reporting Errors and Warnings Like Built-Ins">Reporting Errors and Warnings Like Built-Ins</A><BR><ACLASS="sect1"HREF="ch12_14.htm"TITLE="12.13. Referring to Packages Indirectly">Referring to Packages Indirectly</A><BR><ACLASS="sect1"HREF="ch12_15.htm"TITLE="12.14. Using h2ph to Translate C #include Files">Using h2ph to Translate C #include Files</A><BR><ACLASS="sect1"HREF="ch12_16.htm"TITLE="12.15. Using h2xs to Make a Module with C Code">Using h2xs to Make a Module with C Code</A><BR><ACLASS="sect1"HREF="ch12_17.htm"TITLE="12.16. Documenting Your Module with Pod">Documenting Your Module with Pod</A><BR><ACLASS="sect1"HREF="ch12_18.htm"TITLE="12.17. Building and Installing a CPAN Module">Building and Installing a CPAN Module</A><BR><ACLASS="sect1"HREF="ch12_19.htm"TITLE="12.18. Example: Module Template">Example: Module Template</A><BR><ACLASS="sect1"HREF="ch12_20.htm"TITLE="12.19. Program: Finding Versions and Descriptions of Installed Modules">Program: Finding Versions and Descriptions of Installed Modules</A></P><P></P></DIV><DIVCLASS="epigraph"ALIGN="right"><PCLASS="para"ALIGN="right"><I>Like all those possessing a library, Aurelian was aware that he was guilty of not knowing his in its entirety.</I></P><PCLASS="attribution"ALIGN="right">-&nbsp; Jorge Luis Borges <CITECLASS="citetitle">The Theologians</CITE></P></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch12-32032">12.0. Introduction</A></H2><PCLASS="para">Imagine that you have two separate programs, both of which work fine by themselves, and you decide to make a third program that combines the best features from the first two. You copy both programs into a new file or cut and paste selected pieces. You find that the two programs had variables and functions with the same names that should remain separate. For example, both might have an <CODECLASS="literal">init</CODE> function or a global <CODECLASS="literal">$count</CODE> variable. When merged into one program, these separate parts would interfere with each other.</P><PCLASS="para">The solution to this problem is <EMCLASS="emphasis">packages</EM><ACLASS="indexterm"NAME="ch12-idx-1000005125-0"></A>. Perl uses packages to partition the global namespace. The package is the basis for both traditional modules and object-oriented classes. Just as directories contain files, packages contain identifiers. Every global identifier (variables, functions, file and directory handles, and formats) has two parts: its package name and the identifier proper. These two pieces are separated from one another with a double colon. For example, the variable <CODECLASS="literal">$CGI::needs_binmode</CODE> is a global variable named <CODECLASS="literal">$needs_binmode</CODE>, which resides in package <CODECLASS="literal">CGI</CODE>.</P><PCLASS="para">Where the filesystem uses slashes to separate the directory from the filename, Perl uses a double colon (prior to release 5.000, you could only use a single quote mark, as in <CODECLASS="literal">$CGI'needs_bin_mode</CODE>). <CODECLASS="literal">$Names::startup</CODE> is the variable named <CODECLASS="literal">$startup</CODE> in the package <CODECLASS="literal">Names</CODE>, whereas <CODECLASS="literal">$Dates::startup</CODE> is the <CODECLASS="literal">$startup</CODE> variable in package <CODECLASS="literal">Dates</CODE>. Saying <CODECLASS="literal">$startup</CODE> by itself without a package name means the global variable <CODECLASS="literal">$startup</CODE> in the current package. (This assumes that no lexical <CODECLASS="literal">$startup</CODE> variable is currently visible. Lexical variables are explained in <ACLASS="xref"HREF="ch10_01.htm"TITLE="Subroutines">Chapter 10, <CITECLASS="chapter">Subroutines</CITE></A>.) When looking at an unqualified variable name, a lexical takes precedence over a global. Lexicals live in scopes; globals live in packages. If you really want the global instead, you need to fully qualify it.</P><PCLASS="para"><CODECLASS="literal">package</CODE><ACLASS="indexterm"NAME="ch12-idx-1000005126-0"></A> is a compile-time declaration that sets the default package prefix for unqualified global identifiers, just as <CODECLASS="literal">chdir</CODE> sets the default directory prefix for relative pathnames. This effect lasts until the end of the current scope (a brace-enclosed block, file, or <CODECLASS="literal">eval</CODE>). The effect is also terminated by any subsequent package statement in the same scope. (See the following code.) All programs are in package <CODECLASS="literal">main</CODE> until they use a <CODECLASS="literal">package</CODE> statement to change this.</P><PRECLASS="programlisting">package Alpha;$name = &quot;first&quot;;package Omega;$name = &quot;last&quot;;package main;print &quot;Alpha is $Alpha::name, Omega is $Omega::name.\n&quot;;<BCLASS="emphasis.bold">Alpha is first, Omega is last.</B></PRE><PCLASS="para">Unlike user-defined identifiers, built-in variables with punctuation names (like <CODECLASS="literal">$_</CODE> and <CODECLASS="literal">$.</CODE>) and the identifiers STDIN, STDOUT, STDERR, ARGV, ARGVOUT, ENV, INC, and SIG are all forced to be in package <CODECLASS="literal">main</CODE> when unqualified. That way things like STDIN, <CODECLASS="literal">@ARGV</CODE>, <CODECLASS="literal">%ENV</CODE>, and <CODECLASS="literal">$_</CODE> are always the same no matter what package you're in; for example, <CODECLASS="literal">@ARGV</CODE> always means <CODECLASS="literal">@main::ARGV</CODE>, even if you've used <CODECLASS="literal">package</CODE> to change the default package. A fully qualified <CODECLASS="literal">@ElseWhere::ARGV</CODE> would not (and carries no special built-in meaning). Make sure to localize <CODECLASS="literal">$_</CODE> if you use it in your module.<ACLASS="indexterm"NAME="ch12-idx-1000005128-0"></A></P><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch12-chap12_modules_0">Modules</A></H3><PCLASS="para"><ACLASS="indexterm"NAME="ch12-idx-1000005533-0"></A>The unit of software reuse in Perl is the <EMCLASS="emphasis">module</EM>, a file that has a collection of related functions designed to be used by other programs and library modules. Every module has a public interface, a set of variables and functions that outsiders are encouraged to use. From inside the module, the interface is defined by initializing certain package variables that the standard Exporter module looks at. From outside the module, the interface is accessed by importing symbols as a side effect of the <CODECLASS="literal">use</CODE> statement. The public interface of a Perl module is whatever is documented to be public. In the case of undocumented interfaces, it's whatever is vaguely intended to be public. When we talk about modules in this chapter, and traditional modules in general, we mean those that use the Exporter.</P><PCLASS="para">The <CODECLASS="literal">require</CODE><ACLASS="indexterm"NAME="ch12-idx-1000005538-0"></A><ACLASS="indexterm"NAME="ch12-idx-1000005538-1"></A> or <CODECLASS="literal">use</CODE> statements both pull a module into your program, although their semantics are slightly different. <CODECLASS="literal">require</CODE> loads modules at runtime, with a check to avoid the redundant loading of a given module. <CODECLASS="literal">use</CODE> is like <CODECLASS="literal">require</CODE>, with two added properties: compile-time loading and automatic importing.</P><PCLASS="para">Modules included with <CODECLASS="literal">use</CODE> are processed at compile time, but <CODECLASS="literal">require</CODE> processing happens at run time. This is important because if a module that a program needs is missing, the program won't even start because the <CODECLASS="literal">use</CODE> fails during compilation of your script. Another advantage of compile-time <CODECLASS="literal">use</CODE> over run-time <CODECLASS="literal">require</CODE> is that function prototypes in the module's subroutines become visible to the compiler. This matters because only the compiler cares about prototypes, not the interpreter. (Then again, we don't usually recommend prototypes except for replacing built-in commands, which do have them.)</P><PCLASS="para"><CODECLASS="literal">use</CODE> is suitable for giving hints to the compiler because of its compile-time behavior. A <EMCLASS="emphasis">pragma</EM><ACLASS="indexterm"NAME="ch12-idx-1000005131-0"></A> is a special module that acts as directive to the compiler to alter how Perl compiles your code. A pragma's name is always all lowercase, so when writing a regular module instead of a pragma, choose a name that starts with a capital letter. Pragmas supported by Perl 5.004 include autouse, constant, diagnostics, integer, lib, locale, overload, sigtrap, strict, subs, and vars. Each has its own manpage.</P><PCLASS="para"><ACLASS="indexterm"NAME="ch12-idx-1000005132-0"></A>The other difference between <CODECLASS="literal">require</CODE> and <CODECLASS="literal">use</CODE> is that <CODECLASS="literal">use</CODE> performs an implicit <EMCLASS="emphasis">import</EM> on the included module's package. Importing a function or variable from one package to another is a form of aliasing; that is, it makes two different names for the same underlying thing. It's like linking in files from another directory to your current one by the command <EMCLASS="emphasis">ln /somedir/somefile.</EM> Once it's linked in, you no longer have to use the full pathname to access the file. Likewise, an imported symbol no longer needs to be fully qualified by package name (or predeclared with <CODECLASS="literal">use</CODE> <CODECLASS="literal">vars</CODE> or <CODECLASS="literal">use</CODE> <CODECLASS="literal">subs</CODE>). You can use imported variables as though they were part of your package. If you imported <CODECLASS="literal">$English::OUTPUT_AUTOFLUSH</CODE> in the current package, you could refer to it as <CODECLASS="literal">$OUTPUT_AUTOFLUSH</CODE>.</P><PCLASS="para"><ACLASS="indexterm"NAME="ch12-idx-1000005133-0"></A>The required file extension for a Perl module is <CODECLASS="literal">&quot;.pm&quot;</CODE>. The module named FileHandle would be stored in the file <EMCLASS="emphasis">FileHandle.pm</EM>. The full path to the file depends on your include path, which is stored in the global @INC variable. <ACLASS="xref"HREF="ch12_08.htm"TITLE="Keeping Your Own Module Directory">Recipe 12.7</A> shows how to manipulate this array to your own purposes.</P><PCLASS="para">If the module name itself contains one or more double colons, these are translated into your system's directory separator. That means that the File::Find module resides in the file <EMCLASS="emphasis">File/Find.pm</EM> under most filesystems. For example:</P><PRECLASS="programlisting">require &quot;FileHandle.pm&quot;;            # run-time loadrequire FileHandle;                 # &quot;.pm&quot; assumed; same as previoususe FileHandle;                     # compile-time loadrequire &quot;Cards/Poker.pm&quot;;           # run-time loadrequire Cards::Poker;               # &quot;.pm&quot; assumed; same as previoususe Cards::Poker;                   # compile-time load<ACLASS="indexterm"NAME="ch12-idx-1000005130-0"

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -