📄 ch12_01.htm
字号:
></A></PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch12-chap12_import_export_0">Import/Export Regulations</A></H3><PCLASS="para"><ACLASS="indexterm"NAME="ch12-idx-1000005134-0"></A>The following is a typical setup for a hypothetical module named Cards::Poker that demonstrates how to manage its exports. The code goes in the file named <EMCLASS="emphasis">Poker.pm</EM> within the directory <EMCLASS="emphasis">Cards</EM>: that is, <EMCLASS="emphasis">Cards/Poker.pm</EM>. (See <ACLASS="xref"HREF="ch12_08.htm"TITLE="Keeping Your Own Module Directory">Recipe 12.7</A> for where the <EMCLASS="emphasis">Cards</EM> directory should reside.) Here's that file, with line numbers included for reference:</P><PRECLASS="programlisting">1 package Cards::Poker;2 use Exporter;3 @ISA = ('Exporter');4 @EXPORT = qw(&shuffle @card_deck);5 @card_deck = (); # initialize package global6 sub shuffle { } # fill-in definition later7 1; # don't forget this</PRE><PCLASS="para">Line 1 declares the package that the module will put its global variables and functions in. Typically, a module first switches to a particular package so that it has its own place for global variables and functions, one that won't conflict with that of another program. This <EMCLASS="emphasis">must</EM> be written exactly as the corresponding <CODECLASS="literal">use</CODE> statement will be written when the module is loaded.</P><PCLASS="para">Don't say <CODECLASS="literal">package</CODE> <CODECLASS="literal">Poker</CODE> just because the basename of your file is <EMCLASS="emphasis">Poker.pm</EM>. Rather, say <CODECLASS="literal">package</CODE> <CODECLASS="literal">Cards::Poker</CODE> because your users will say <CODECLASS="literal">use</CODE> <CODECLASS="literal">Cards::Poker</CODE>. This common problem is hard to debug. If you don't make the <CODECLASS="literal">package</CODE> and <CODECLASS="literal">use</CODE> statements exactly the same, you won't see a problem until you try to call imported functions or access imported variables, which will be mysteriously missing.</P><PCLASS="para">Line 2 loads in the <ACLASS="indexterm"NAME="ch12-idx-1000005150-0"></A>Exporter module, which manages your module's public interface as described below. Line 3 initializes the special, per-package array <CODECLASS="literal">@ISA</CODE> to contain the word <CODECLASS="literal">"Exporter"</CODE>. When a user says <CODECLASS="literal">use</CODE> <CODECLASS="literal">Cards::Poker</CODE>, Perl implicitly calls a special method, <CODECLASS="literal">Cards::Poker->import()</CODE>. You don't have an <CODECLASS="literal">import</CODE> method in your package, but that's OK, because the Exporter package does, and you're <EMCLASS="emphasis">inheriting</EM> from it because of the assignment to <CODECLASS="literal">@ISA</CODE> (<EMCLASS="emphasis">is a</EM>). Perl looks at the package's <CODECLASS="literal">@ISA</CODE> for resolution of undefined methods. Inheritance is a topic of <ACLASS="xref"HREF="ch13_01.htm"TITLE="Classes, Objects, and Ties">Chapter 13, <CITECLASS="chapter">Classes, Objects, and Ties</CITE></A>. You may ignore it for now - so long as you put code as shown in lines 2 and 3 into each module you write.</P><PCLASS="para">Line 4 assigns the list <CODECLASS="literal">('&shuffle',</CODE> <CODECLASS="literal">'@card_deck')</CODE> to the special, per-package array <CODECLASS="literal">@EXPORT</CODE>. When someone imports this module, variables and functions listed in that array are aliased into the caller's own package. That way they don't have to call the function <CODECLASS="literal">Poker::Deck::shuffle(23)</CODE> after the import. They can just write <CODECLASS="literal">shuffle(23)</CODE> instead. This won't happen if they load Cards::Poker with <CODECLASS="literal">require</CODE> <CODECLASS="literal">Cards::Poker</CODE>; only a <CODECLASS="literal">use</CODE> imports.</P><PCLASS="para">Lines 5 and 6 set up the package global variables and functions to be exported. (We presume you'll actually flesh out their initializations and definitions more than in these examples.) You're free to add other variables and functions to your module as well, including ones you don't put in the public interface via <CODECLASS="literal">@EXPORT</CODE>. See <ACLASS="xref"HREF="ch12_02.htm"TITLE="Defining a Module's Interface">Recipe 12.1</A> for more about using the Exporter.</P><PCLASS="para">Finally, line 7 is a simple <CODECLASS="literal">1</CODE>, indicating the overall return value of the module. If the last evaluated expression in the module doesn't produce a true value, an exception will be raised. Trapping this is the topic of <ACLASS="xref"HREF="ch12_03.htm"TITLE="Trapping Errors in require or use">Recipe 12.2</A>. Any old true value will do, like 6.02e23 or <CODECLASS="literal">"Because</CODE> <CODECLASS="literal">tchrist</CODE> <CODECLASS="literal">and</CODE> <CODECLASS="literal">gnat</CODE> <CODECLASS="literal">told</CODE> <CODECLASS="literal">us</CODE> <CODECLASS="literal">to</CODE> <CODECLASS="literal">put</CODE> <CODECLASS="literal">this</CODE> <CODECLASS="literal">here"</CODE>; however, <CODECLASS="literal">1</CODE> is the canonical true value used by almost every module.</P><PCLASS="para">Packages group and organize global identifiers. They have nothing to do with privacy. Code compiled in package <CODECLASS="literal">Church</CODE> can freely examine and alter variables in package <CODECLASS="literal">State</CODE>. Package variables are always global and are used for sharing. But that's okay, because a module is more than just a package; it's also a file, and files count as their own scope. So if you want privacy, use lexical variables instead of globals. This is the topic of <ACLASS="xref"HREF="ch12_05.htm"TITLE="Making Variables Private to a Module">Recipe 12.4</A>.<ACLASS="indexterm"NAME="ch12-idx-1000005135-0"></A><ACLASS="indexterm"NAME="ch12-idx-1000005135-1"></A></P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch12-chap12_other_0">Other Kinds of Library Files</A></H3><PCLASS="para"><ACLASS="indexterm"NAME="ch12-idx-1000005136-0"></A>A library is a collection of loosely related functions designed to be used by other programs. It lacks the rigorous semantics of a Perl module. The file extension <CODECLASS="literal">.pl</CODE> indicates that it's a Perl library file. Examples include <EMCLASS="emphasis">syslog.pl</EM> and <EMCLASS="emphasis">chat2.pl</EM>.</P><PCLASS="para">Perl libraries - or in fact, any arbitrary file with Perl code in it - can be loaded in using <CODECLASS="literal">do</CODE> <CODECLASS="literal">'file.pl'</CODE> or with <CODECLASS="literal">require</CODE> <CODECLASS="literal">'file.pl'</CODE>. The latter is preferred in most situations, because unlike <CODECLASS="literal">do</CODE>, <CODECLASS="literal">require</CODE> does implicit error checking. It raises an exception if the file can't be found in your <CODECLASS="literal">@INC</CODE> path, doesn't compile, or if it doesn't return a true value when any initialization code is run. (The last part is what the <CODECLASS="literal">1;</CODE> was for earlier.) Another advantage of <CODECLASS="literal">require</CODE> is that it keeps track of which files have already been loaded in the global hash <CODECLASS="literal">%INC</CODE>. It doesn't reload the file if <CODECLASS="literal">%INC</CODE> indicates that the file has already been read in.</P><PCLASS="para">Libraries work well when used by a program, but problems can arise when libraries use one another. Consequently, simple Perl libraries have been rendered mostly obsolete, replaced by the more modern modules. But some programs still use libraries, usually loading them in with <CODECLASS="literal">require</CODE> instead of <CODECLASS="literal">do</CODE>.</P><PCLASS="para">Other file extensions are occasionally seen in Perl. A <CODECLASS="literal">".ph"</CODE> is used for C header files that have been translated into Perl libraries using the <EMCLASS="emphasis">h2ph</EM> tool, as discussed in <ACLASS="xref"HREF="ch12_15.htm"TITLE="Using h2ph to Translate C #include Files">Recipe 12.14</A>. A <CODECLASS="literal">".xs"</CODE> indicates an augmented C source file, possibly created by the <EMCLASS="emphasis">h2xs</EM> tool, which will be compiled by the <EMCLASS="emphasis">xsubpp</EM> tool and your C compiler into native machine code. This process of creating mixed-language modules is discussed in <ACLASS="xref"HREF="ch12_16.htm"TITLE="Using h2xs to Make a Module with C Code">Recipe 12.15</A>.</P><PCLASS="para">So far we've only talked about traditional modules, which export their interface by allowing the caller direct access to particular subroutines and variables. Most modules fall into this category. But some problems - and some programmers - lend themselves to more intricately designed modules, those involving objects. An object-oriented module seldom uses the import-export mechanism at all. Instead, it provides an object-oriented interface full of constructors, destructors, methods, inheritance, and operator overloading. This is the subject of <ACLASS="xref"HREF="ch13_01.htm"TITLE="Classes, Objects, and Ties">Chapter 13</A>.<ACLASS="indexterm"NAME="ch12-idx-1000005137-0"></A></P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch12-chap12_not_0">Not Reinventing the Wheel</A></H3><PCLASS="para">CPAN, the <ACLASS="indexterm"NAME="ch12-idx-1000005138-0"></A><ACLASS="indexterm"NAME="ch12-idx-1000005138-1"></A>Comprehensive Perl Archive Network, is a gigantic repository of nearly everything about Perl you could imagine, including source, documentation, alternate ports, and above all, modules. Before you write a new module, check with CPAN to see whether one already exists that does what you need. Even if one doesn't, something close enough might give you ideas.</P><PCLASS="para">You can access CPAN at <ACLASS="systemitem.url"HREF="http://www.perl.com/CPAN/CPAN.html">http://www.perl.com/CPAN/CPAN.html</A> (or <ACLASS="systemitem.url"HREF="ftp://www.perl.com/pub/perl/CPAN/CPAN.html ">ftp://www.perl.com/pub/perl/CPAN/CPAN.html </A>). This file briefly describes each of CPAN's modules, but because it's manually edited, it may not always have the very latest modules' descriptions. You can find out about those in the <EMCLASS="emphasis">CPAN/RECENT</EM> or <EMCLASS="emphasis">CPAN/RECENT.html</EM> file.</P><PCLASS="para">The module directory itself is in <EMCLASS="emphasis">CPAN/modules</EM>. It contains indices of all registered modules plus three convenient subdirectories: <EMCLASS="emphasis">by-module</EM>, <EMCLASS="emphasis">by-author</EM>, and <EMCLASS="emphasis">by-category</EM>. All modules are available through each of these, but the <EMCLASS="emphasis">by-category</EM> directory is probably the most useful. There you will find directories covering specific applications areas including operating system interfaces; networking, modems, and interprocess communication; database interfaces; user interfaces; interfaces to other programming languages; authentication, security, and encryption; World Wide Web, HTML, HTTP, CGI, and MIME; images, pixmap and bitmap manipulation, drawing, and graphing - just to name a few.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch12-pgfId-1000005847">See Also</A></H3><PCLASS="para">The sections on <ACLASS="olink"HREF="../prog/ch05_01.htm#PERL2-CH-5-SECT-1">"Packages"</A> and on <ACLASS="olink"HREF="../prog/ch05_02.htm">"Modules"</A> in <ACLASS="olink"HREF="../prog/ch05_01.htm">Chapter 5</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A> and in <ICLASS="filename">perlmod </I>(1)</P></DIV></DIV></DIV><DIVCLASS="htmlnav"><P></P><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><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"><ACLASS="book"HREF="index.htm"TITLE="Perl Cookbook"><IMGSRC="../gifs/txthome.gif"ALT="Perl Cookbook"BORDER="0"></A></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><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">11.15. Program: Binary Trees</TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="index"HREF="index/index.htm"TITLE="Book Index"><IMGSRC="../gifs/index.gif"ALT="Book Index"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228">12.1. Defining a Module's Interface</TD></TR></TABLE><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><FONTSIZE="-1"></DIV<!-- LIBRARY NAV BAR --> <img src="../gifs/smnavbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links"><p> <a href="copyrght.htm">Copyright © 2002</a> O'Reilly & Associates. All rights reserved.</font> </p> <map name="library-map"> <area shape="rect" coords="1,0,85,94" href="../index.htm"><area shape="rect" coords="86,1,178,103" href="../lwp/index.htm"><area shape="rect" coords="180,0,265,103" href="../lperl/index.htm"><area shape="rect" coords="267,0,353,105" href="../perlnut/index.htm"><area shape="rect" coords="354,1,446,115" href="../prog/index.htm"><area shape="rect" coords="448,0,526,132" href="../tk/index.htm"><area shape="rect" coords="528,1,615,119" href="../cookbook/index.htm"><area shape="rect" coords="617,0,690,135" href="../pxml/index.htm"></map> </BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -