📄 ch13_08.htm
字号:
<html><head><title>Using Simple Modules (Learning Perl, 3rd Edition)</title><link rel="stylesheet" type="text/css" href="../style/style1.css" /><meta name="DC.Creator" content="Randal L. Schwartz and Tom Phoenix" /><meta name="DC.Format" content="text/xml" scheme="MIME" /><meta name="DC.Language" content="en-US" /><meta name="DC.Publisher" content="O'Reilly & Associates, Inc." /><meta name="DC.Source" scheme="ISBN" content="0596001320L" /><meta name="DC.Subject.Keyword" content="stuff" /><meta name="DC.Title" content="Learning Perl, 3rd Edition" /><meta name="DC.Type" content="Text.Monograph" /></head><body bgcolor="#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="Learning Perl, 3rd Edition" /><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><table width="684" border="0"><tr><td align="left" valign="top" width="228"><a href="ch13_07.htm"><img alt="Previous" border="0" src="../gifs/txtpreva.gif" /></a></td><td align="center" valign="top" width="228"><a href="index.htm"></a></td><td align="right" valign="top" width="228"><a href="ch13_09.htm"><img alt="Next" border="0" src="../gifs/txtnexta.gif" /></a></td></tr></table></div><h2 class="sect1">13.8. Using Simple Modules</h2><p><a name="INDEX-931" />Suppose<a name="INDEX-932" />thatyou've got a long filename like<em class="filename">/usr/local/bin/perl</em> in your program, and youneed to find out the <em class="firstterm">basename.</em> That'seasy enough, since the basename is everything after the last slash(it's just "<em class="filename">perl</em>" in thiscase):</p><blockquote><pre class="code">my $name = "/usr/local/bin/perl";(my $basename = $name) =~ s#.*/##; # Oops!</pre></blockquote><p>As we saw earlier, first Perl will do the assignment inside theparentheses, then it will do the substitution. The substitution issupposed to replace any string ending with a slash (that is, thedirectory name portion) with an empty string, leaving just thebasename.</p><p>And if you try this, it seems to work. Well, it<em class="emphasis">seems</em> to, but actually, there are threeproblems.</p><p>First, a Unix file or directory name could contain a newlinecharacter. (It's not something that's likely to happen byaccident, but it's permitted.) So, since the regular expressiondot ("<tt class="literal">.</tt>") can't match a newline,a filename like the string<tt class="literal">"/home/fred/flintstone\n/brontosaurus"</tt> won'twork right -- that code would think the basename is<tt class="literal">"flintstone\n/brontosaurus"</tt>. You could fix thatwith the <tt class="literal">/s</tt> option to the pattern (if youremembered about this subtle and infrequent case), making thesubstitution look like this: <tt class="literal">s#.*/##s</tt></p><p>The second problem is that this is Unix-specific. It assumes that theforward slash will always be the directory separator, as it is onUnix, and not the backslash or colon that some systems use.</p><p>And the third (and biggest) problem with this is that we'retrying to solve a problem that someone else has already solved. Perlcomes with a number of <em class="firstterm">modules</em>, which aresmart extensions to Perl that add to its functionality. And if thosearen't enough, there are many other useful modules available on<a name="INDEX-933" />CPAN, with new ones being added everyweek. You (or, better yet, your system administrator) can installthem if you need their functionality.</p><p>In the rest of this section, we'll show you how to use some ofthe features of a couple of simple modules that come with Perl.(There's more that these modules can do; this is just anoverview to illustrate the general principles of how to use a simplemodule.)</p><p>Alas, we can't show you everything you'd need to knowabout using modules in general, since you'd have to understandadvanced topics like references and objects in order to use somemodules.<a href="#FOOTNOTE-298">[298]</a> But this section should prepare you for using many simplemodules. Further information on some interesting and useful modulesis included in <a href="appb_01.htm">Appendix B, "Beyond the Llama"</a>.</p><blockquote class="footnote"> <a name="FOOTNOTE-298" /><p>[298]As we'll see in the next few pages,though, you may be able to use a module that uses objects andreferences without having to understand those advanced topics.</p></blockquote><a name="lperl3-CHP-13-SECT-8.1" /><div class="sect2"><h3 class="sect2">13.8.1. The File::Basename Module</h3><p><a name="INDEX-934" /> <a name="INDEX-935" />In the previous example, we foundthe basename of a filename in a way that's not portable. Weshowed that something that seemed straightforward was susceptible tosubtle mistaken assumptions (here, the assumption was that newlineswould never appear in file or directory names). And we werere-inventing the wheel, solving a problem that others have solved(and debugged) many times before us.</p><p>Here's a better way to extract the basename of a filename. Perlcomes with a module called <tt class="literal">File::Basename</tt>. Withthe command <i class="command">perldoc File::Basename</i>, or with yoursystem's documentation system, you can read about what it does.That's the first step when using a new module. (It'soften the third and fifth step, as well.)</p><p>Soon you're ready to use it, so you declare it with a<tt class="literal">use</tt> directive near the top of yourprogram:<a href="#FOOTNOTE-299">[299]</a></p><blockquote class="footnote"> <a name="FOOTNOTE-299" /><p>[299]It's traditional to declare modulesnear the top of the file, since that makes it easy for themaintenance programmer to see which modules you'll be using.That greatly simplifies matters when it's time to install yourprogram on a new machine, for example.</p> </blockquote><blockquote><pre class="code">use File::Basename;</pre></blockquote><p>During compilation, Perl sees that line and loads up the module. Now,it's as if Perl has some new functions that you may use in theremainder of your program.<a href="#FOOTNOTE-300">[300]</a> The one we wanted in the earlier example is the<tt class="literal">basename</tt> function itself:</p><blockquote class="footnote"> <a name="FOOTNOTE-300" /><p>[300]You guessed it:there's more to the story, having to do with packages and fullyqualified names. When your programs are growing beyond a few hundredlines in the main program (not counting code in modules), which isquite large in Perl, you should probably read up about these advancedfeatures. Start with the <em class="emphasis">perlmod</em> manpage.</p></blockquote><blockquote><pre class="code">my $name = "/usr/local/bin/perl";my $basename = basename $name; # gives 'perl'</pre></blockquote><p>Well, that worked for Unix. What if our program were running onMacPerl or Windows or VMS, to name a few? There's noproblem -- this module can tell which kind of machine you'reusing, and it uses that machine's filename rules by default.(Of course, you'd have that machine's kind of filenamestring in <tt class="literal">$name</tt>, in that case.)</p><p>There are some related functions also provided by this module. One isthe <tt class="literal">dirname</tt><a name="INDEX-936" /> function, whichpulls the directory name from a full filename. The module also letsyou separate a filename from its extension, or change the default setof filename rules.<a href="#FOOTNOTE-301">[301]</a></p><blockquote class="footnote"> <a name="FOOTNOTE-301" /><p>[301]You might need to change thefilename rules if you were trying to work with a Unix machine'sfilenames from a Windows machine -- perhaps while sending commandsover an FTP connection, for example.</p> </blockquote></div><a name="lperl3-CHP-13-SECT-8.2" /><div class="sect2"><h3 class="sect2">13.8.2. Using Only Some Functions from a Module</h3><p>Suppose you discovered that when you went to add the<tt class="literal">File::Basename</tt> module to your existing program,you already have a subroutine called<tt class="literal">&dirname</tt> -- that is, you already have asubroutine with the same name as one of the<a name="INDEX-937" />module'sfunctions.<a href="#FOOTNOTE-302">[302]</a> Now there'strouble, because the new <tt class="literal">dirname</tt> is<em class="emphasis">also</em> implemented as a Perl subroutine (insidethe module). What do you do?</p><blockquote class="footnote"> <a name="FOOTNOTE-302" /><p>[302]Well, it's not likely that you wouldalready have a <tt class="literal">&dirname</tt> subroutine that youuse for another purpose, but this is just an example. Some modulesoffer hundreds (really!) of new functions, making a name collisionthat much more frequent.</p> </blockquote>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -