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

📄 ch11_02.htm

📁 编程珍珠,里面很多好用的代码,大家可以参考学习呵呵,
💻 HTM
📖 第 1 页 / 共 2 页
字号:
<html><head><title>Creating Modules (Programming Perl)</title><!-- STYLESHEET --><link rel="stylesheet" type="text/css" href="../style/style1.css"><!-- METADATA --><!--Dublin Core Metadata--><meta name="DC.Creator" content=""><meta name="DC.Date" content=""><meta name="DC.Format" content="text/xml" scheme="MIME"><meta name="DC.Generator" content="XSLT stylesheet, xt by James Clark"><meta name="DC.Identifier" content=""><meta name="DC.Language" content="en-US"><meta name="DC.Publisher" content="O'Reilly &amp; Associates, Inc."><meta name="DC.Source" content="" scheme="ISBN"><meta name="DC.Subject.Keyword" content=""><meta name="DC.Title" content="Creating Modules"><meta name="DC.Type" content="Text.Monograph"></head><body><!-- START OF BODY --><!-- TOP BANNER --><img src="gifs/smbanner.gif" usemap="#banner-map" border="0" alt="Book Home"><map name="banner-map"><AREA SHAPE="RECT" COORDS="0,0,466,71" HREF="index.htm" ALT="Programming Perl"><AREA SHAPE="RECT" COORDS="467,0,514,18" HREF="jobjects/fsearch.htm" ALT="Search this book"></map><!-- TOP NAV BAR --><div class="navbar"><table width="515" border="0"><tr><td align="left" valign="top" width="172"><a href="ch11_01.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="ch11_01.htm">Chapter 11: Modules</a></td><td align="right" valign="top" width="172"><a href="ch11_03.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0"></a></td></tr></table></div><hr width="515" align="left"><!-- SECTION BODY --><h2 class="sect1">11.2. Creating Modules</h2><p><a name="INDEX-2298"></a><a name="INDEX-2299"></a><a name="INDEX-2300"></a><a name="INDEX-2301"></a>Earlier, we said that there are two ways for a module to make itsinterface available to your program: by exporting symbols or byallowing method calls.  We'll show you an example of the first stylehere; the second style is for object-oriented modules and is describedin the next chapter.  (Object-oriented modules should export nothing,since the whole idea of methods is that Perl finds them for youautomatically, based on the type of the object.)</p><p>To construct a module called <tt class="literal">Bestiary</tt>, create a file called<em class="emphasis">Bestiary.pm</em> that looks like this:<blockquote><pre class="programlisting">package      Bestiary;require      Exporter;our @ISA       = qw(Exporter);our @EXPORT    = qw(camel);    # Symbols to be exported by defaultour @EXPORT_OK = qw($weight);  # Symbols to be exported on requestour $VERSION   = 1.00;         # Version number### Include your variables and functions heresub camel { print "One-hump dromedary" }$weight = 1024;1;</pre></blockquote>A program can now say <tt class="literal">use Bestiary</tt> to be able toaccess the <tt class="literal">camel</tt> function (but not the<tt class="literal">$weight</tt> variable), and <tt class="literal">use Bestiaryqw(camel $weight)</tt> to access both the function and thevariable.</p><p>You can also create modules that dynamically load code written in C.See <a href="ch21_01.htm">Chapter 21, "Internals and Externals"</a>, for details.</p><h3 class="sect2">11.2.1. Module Privacy and the Exporter</h3><p><a name="INDEX-2302"></a><a name="INDEX-2303"></a><a name="INDEX-2304"></a>Perl does not automatically patrol private/public borders within itsmodules--unlike languages such as C++, Java, and Ada, Perl isn'tobsessed with enforced privacy.  A Perl module would prefer that youstay out of its living room because you weren't invited, not becauseit has a shotgun.</p><p><a name="INDEX-2305"></a><a name="INDEX-2306"></a>The module and its user have a contract, part of which is common lawand part of which is written.  Part of the common law contract is thata module refrain from changing any namespace it wasn't asked tochange.  The written contract for the module (that is, thedocumentation) may make other provisions.  But then, having read thecontract, you presumably know that when you say <tt class="literal">useRedefineTheWorld</tt> you're redefining the world, and you'rewilling to risk the consequences. The most common way to redefineworlds is to use the <tt class="literal">Exporter</tt> module. As we'll seelater in the chapter, you can even redefine built-ins with thismodule.</p><p><a name="INDEX-2307"></a><a name="INDEX-2308"></a><a name="INDEX-2309"></a><a name="INDEX-2310"></a><a name="INDEX-2311"></a>When you <tt class="literal">use</tt> a module, the module typically makessome variables or functions available to your program, or morespecifically, to your program's current package. This act of exportingsymbols from the module (and thus importing them into your program) issometimes called <em class="emphasis">polluting</em> your namespace.  Mostmodules use <tt class="literal">Exporter</tt> to do this; that's whymost modules say something like this near the top:<blockquote><pre class="programlisting">require Exporter;our @ISA = ("Exporter");</pre></blockquote><a name="INDEX-2312"></a>These two lines make the module inherit from the<tt class="literal">Exporter</tt> class.  Inheritance is described in thenext chapter, but all you need to know is our<tt class="literal">Bestiary</tt> module can now export symbols into otherpackages with lines like these:<blockquote><pre class="programlisting">our @EXPORT    = qw($camel %wolf ram);              # Export by defaultour @EXPORT_OK = qw(leopard @llama $emu);           # Export by requestour %EXPORT_TAGS = (                                # Export as group                     camelids =&gt; [qw($camel @llama)],                     critters =&gt; [qw(ram $camel %wolf)],                   );</pre></blockquote></p><p>From the viewpoint of the exporting module, the <tt class="literal">@EXPORT</tt> array contains the names of variables and functions tobe exported by default: what your program gets when it says<tt class="literal">use Bestiary</tt>.  Variables and functions in <tt class="literal">@EXPORT_OK</tt> areexported only when the program specifically requests them in the<tt class="literal">use</tt> statement.  Finally, the key/value pairs in <tt class="literal">%EXPORT_TAGS</tt>allow the program to include particular groups of the symbols listedin <tt class="literal">@EXPORT</tt> and <tt class="literal">@EXPORT_OK</tt>.</p><p>From the viewpoint of the importing package, the <tt class="literal">use</tt> statement specifies a list of symbols to import, a groupnamed in <tt class="literal">%EXPORT_TAGS</tt>, a pattern of symbols, or nothing at all, inwhich case the symbols in <tt class="literal">@EXPORT</tt> would be imported from the moduleinto your program.</p><p>You can include any of these statements to import symbols fromthe <tt class="literal">Bestiary</tt> module:<blockquote><pre class="programlisting">use Bestiary;                    # Import @EXPORT symbolsuse Bestiary ();                 # Import nothinguse Bestiary qw(ram @llama);     # Import the ram function and @llama arrayuse Bestiary qw(:camelids);      # Import $camel and @llamause Bestiary qw(:DEFAULT);       # Import @EXPORT symbolsuse Bestiary qw(/am/);           # Import $camel, @llama, and ramuse Bestiary qw(/^\$/);          # Import all scalarsuse Bestiary qw(:critters !ram); # Import the critters, but exclude ramuse Bestiary qw(:critters !:camelids);                                 # Import critters, but no camelids</pre></blockquote><a name="INDEX-2313"></a>Leaving a symbol off the export lists (or removing itexplicitly from the import list with the exclamation point) does not render it inaccessibleto the program using the module.  The program will always be able toaccess the contents of the module's package by fully qualifying thepackage name, like <tt class="literal">%Bestiary::gecko</tt>.  (Since lexical variables donot belong to packages, privacy is still possible: see "PrivateMethods" in the next chapter.)</p>

⌨️ 快捷键说明

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