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

📄 ch24_03.htm

📁 编程珍珠,里面很多好用的代码,大家可以参考学习呵呵,
💻 HTM
字号:
<html><head><title>Programming with Style (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="Programming with Style"><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="ch24_02.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="ch24_01.htm">Chapter 24: Common Practices</a></td><td align="right" valign="top" width="172"><a href="ch24_04.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">24.3. Programming with Style</h2><p><a name="INDEX-4248"></a><a name="INDEX-4249"></a><a name="INDEX-4250"></a>You'll certainly have your own preferences inregard to formatting, but there are some general guidelines that willmake your programs easier to read, understand, and maintain.</p><p>The most important thing is to run your programs under the<tt class="literal">use warnings</tt> pragma.  (You can turn off unwantedwarnings with <tt class="literal">no warnings</tt>.) You should also alwaysrun under <tt class="literal">use strict</tt> or have a good reason not to.The <tt class="literal">use sigtrap</tt> and even the <tt class="literal">usediagnostics</tt> pragmas may also prove of benefit.</p><p>Regarding aesthetics of code layout, about the only thing Larry caresstrongly about is that the closing brace of a multiline<em class="replaceable">BLOCK</em> should be "outdented" to line upwith the keyword that started the construct.  Beyond that, he hasother preferences that aren't so strong.  Examples in this book(should) all follow these coding conventions:</p><ul><li><p>Use four-column indents.</p></li><li><p><a name="INDEX-4251"></a>An opening brace should be put on the same line as its precedingkeyword, if possible; otherwise, line them up vertically.<blockquote><pre class="programlisting">while ($condition) {        # for short ones, align with keywords    # do something} # if the condition wraps, line up the braces with each otherwhile ($this_condition and $that_condition       and $this_other_long_condition) {    # do something}</pre></blockquote></p></li><li><p><a name="INDEX-4252"></a>Put space before the opening brace of a multiline <em class="replaceable">BLOCK</em>.</p></li><li><p>A short <em class="replaceable">BLOCK</em> may be put on one line, including braces.</p></li><li><p>Omit the semicolon in a short, one-line <em class="replaceable">BLOCK</em>.</p></li><li><p>Surround most operators with space.</p></li><li><p>Surround a "complex" subscript (inside brackets) with space.</p></li><li><p>Put blank lines between chunks of code that do different things.</p></li><li><p>Put a newline between a closing brace and <tt class="literal">else</tt>.</p></li><li><p>Do not put space between a function name and its opening parenthesis.</p></li><li><p>Do not put space before a semicolon.</p></li><li><p>Put space after each comma.</p></li><li><p>Break long lines after an operator (but before <tt class="literal">and</tt> and <tt class="literal">or</tt>, even when spelled <tt class="literal">&amp;&amp;</tt> and <tt class="literal">||</tt>).</p></li><li><p>Line up corresponding items vertically.</p></li><li><p>Omit redundant punctuation as long as clarity doesn't suffer.</p></li></ul><p>Larry has his reasons for each of these things, but he doesn't claimthat everyone else's mind works the same as his does (or doesn't).</p><p>Here are some other, more substantive style issues to think about:</p><ul><li><p>Just because you <em class="emphasis">can</em> do something a particular way doesn't mean you<em class="emphasis">should</em> do it that way.  Perl is designed to give you several ways todo anything, so consider picking the most readable one.  For instance:<blockquote><pre class="programlisting">open(FOO,$foo)  or die "Can't open $foo: $!";</pre></blockquote>is better than:<blockquote><pre class="programlisting">die "Can't open $foo: $!"   unless open(FOO,$foo);</pre></blockquote>because the second way hides the main point of the statement in amodifier.  On the other hand:<blockquote><pre class="programlisting">print "Starting analysis\n" if $verbose;</pre></blockquote>is better than:<blockquote><pre class="programlisting">$verbose and print "Starting analysis\n";</pre></blockquote>since the main point isn't whether the user typed <span class="option">-v</span> or not.</p></li><li><p>Similarly, just because an operator lets you assume default argumentsdoesn't mean that you have to make use of the defaults.  The defaultsare there for lazy programmers writing one-shot programs.  Ifyou want your program to be readable, consider supplying the argument.</p></li><li><p><a name="INDEX-4253"></a>Along the same lines, just because you <em class="emphasis">can</em> omitparentheses in many places doesn't mean that you ought to:<blockquote><pre class="programlisting">return print reverse sort num values %array;return print(reverse(sort num (values(%array))));</pre></blockquote>When in doubt, parenthesize.  At the very least it will let some poorschmuck bounce on the <tt class="literal">%</tt> key in <em class="emphasis">vi</em>.</p><p>Even if <em class="emphasis">you</em> aren't in doubt, consider the mental welfare of theperson who has to maintain the code after you, and who will probably putparentheses in the wrong place.</p></li><li><p><a name="INDEX-4254"></a><a name="INDEX-4255"></a>Don't go through silly contortions to exit a loop at the top or thebottom.  Perl provides the <tt class="literal">last</tt> operator so you can exit in themiddle.  You can optionally "outdent" it to make it more visible:<blockquote><pre class="programlisting">LINE:    for (;;) {        statements;      last LINE if $foo;        next LINE if /^#/;        statements;    }</pre></blockquote></p></li><li><p><a name="INDEX-4256"></a>Don't be afraid to use loop labels--they're there to enhance readabilityas well as to allow multilevel loop breaks.  See the example justgiven.</p></li><li><p><a name="INDEX-4257"></a><a name="INDEX-4258"></a><a name="INDEX-4259"></a>Avoid using <tt class="literal">grep</tt>, <tt class="literal">map</tt>, or backticks in a void context, that is,when you just throw away their return values.  Those functions all havereturn values, so use them.  Otherwise, use a <tt class="literal">foreach</tt> loop or the<tt class="literal">system</tt> function.</p></li><li><p>For portability, when using features that may not be implemented onevery machine, test the construct in an <tt class="literal">eval</tt> to see whether it fails.If you know the version or patch level of a particular feature, you cantest <tt class="literal">$]</tt> (<tt class="literal">$PERL_VERSION</tt> in the English module) to see whether thefeature is there.  The <tt class="literal">Config</tt> module will also let you interrogatevalues determined by the <em class="emphasis">Configure</em> program when Perl was installed.</p></li><li><p>Choose mnemonic identifiers.  If you can't remember what mnemonic means,you've got a problem.</p></li><li><p><a name="INDEX-4260"></a><a name="INDEX-4261"></a><a name="INDEX-4262"></a>Although short identifiers like <tt class="literal">$gotit</tt> are probably okay, use underscoresto separate words.  It is generally much easier to read<tt class="literal">$var_names_like_this</tt> than <tt class="literal">$VarNamesLikeThis</tt>, especially fornon-native speakers of English.  Besides, the same rule works for<tt class="literal">$VAR_NAMES_LIKE_THIS</tt>.</p><p><a name="INDEX-4263"></a><a name="INDEX-4264"></a><a name="INDEX-4265"></a><a name="INDEX-4266"></a>Package names are sometimes an exception to this rule.  Perl informallyreserves lowercase module names for pragmatic modules like <tt class="literal">integer</tt>and <tt class="literal">strict</tt>.  Other modules should begin with a capital letter and usemixed case, but should probably omit underscores due to name-lengthlimitations on certain primitive filesystems.</p></li><li><p>You may find it helpful to use letter case to indicate the scope ornature of a variable. For example:<blockquote><pre class="programlisting">$ALL_CAPS_HERE   # constants only (beware clashes with Perl vars!)  $Some_Caps_Here  # package-wide global/static $no_caps_here    # function scope my() or local() variables</pre></blockquote><a name="INDEX-4267"></a><a name="INDEX-4268"></a></p><p>For various vague reasons, function and method names seem to work bestas all lowercase.  For example, <tt class="literal">$obj-&gt;as_string()</tt>.</p><p>You can use a leading underscore to indicate that a variable or functionshould not be used outside the package that defined it.  (Perl does notenforce this; it's just a form of documentation.)</p></li><li><p>If you have a really hairy regular expression, use the <tt class="literal">/x</tt> modifierand put in some whitespace to make it look a little less like linenoise.</p></li><li><p>Don't use slash as a delimiter when your regular expression already has too many slashes orbackslashes.</p></li><li><p>Don't use quotes as delimiters when your string contains the samekind of quote.  Use the <tt class="literal">q//</tt>, <tt class="literal">qq//</tt>, or <tt class="literal">qx//</tt> pseudofunctions instead.</p></li><li><p><a name="INDEX-4269"></a><a name="INDEX-4270"></a>Use the <tt class="literal">and</tt> and <tt class="literal">or</tt> operators to avoid having to parenthesize listoperators so much and to reduce the incidence of punctuationaloperators like <tt class="literal">&amp;&amp;</tt> and <tt class="literal">||</tt>.  Call your subroutines as ifthey were functions or list operators to avoid excessive ampersands andparentheses.</p></li><li><p>Use here documents instead of repeated <tt class="literal">print</tt> statements.</p></li><li><p>Line up corresponding things vertically, especially if they're too longto fit on one line anyway:<blockquote><pre class="programlisting">$IDX = $ST_MTIME;       $IDX = $ST_ATIME       if $opt_u; $IDX = $ST_CTIME       if $opt_c;     $IDX = $ST_SIZE        if $opt_s;mkdir $tmpdir, 0700 or die "can't mkdir $tmpdir: $!";chdir($tmpdir)      or die "can't chdir $tmpdir: $!";mkdir 'tmp',   0777 or die "can't mkdir $tmpdir/tmp: $!";</pre></blockquote></p></li><li><p>That which we tell you three times is true:</p><blockquote><pre class="programlisting">Always check the return codes of system calls.  <em class="emphasis">Always check the return codes of system calls.</em><em class="emphasis">ALWAYS CHECK THE RETURN CODES OF SYSTEM CALLS!</em></pre></blockquote><p><a name="INDEX-4271"></a><a name="INDEX-4272"></a>Error messages should go to <tt class="literal">STDERR</tt> and should say which programcaused the problem and what the failed call and its arguments were.Most importantly, for failed syscalls, messages should contain thestandard system error message for what went wrong.  Here's a simple butsufficient example:<blockquote><pre class="programlisting">opendir(D, $dir)  or die "Can't opendir $dir: $!";</pre></blockquote></p></li><li><p>Line up your transliterations when it makes sense:<blockquote><pre class="programlisting">tr [abc]   [xyz];</pre></blockquote></p></li><li><p><a name="INDEX-4273"></a><a name="INDEX-4274"></a>Think about reusability.  Why waste brainpower on a one-shot scriptwhen you might want to do something like it again? Consider generalizingyour code.  Consider writing a module or object class.  Consider makingyour code run cleanly with <tt class="literal">use strict</tt> and <span class="option">-w</span> in effect. Considergiving away your code.  Consider changing your whole world view.Consider ... oh, never mind.</p></li><li><p>Be consistent.</p></li><li><p>Be nice.</p></li></ul><a name="INDEX-4275"></a><a name="INDEX-4276"></a><a name="INDEX-4277"></a><!-- BOTTOM NAV BAR --><hr width="515" align="left"><div class="navbar"><table width="515" border="0"><tr><td align="left" valign="top" width="172"><a href="ch24_02.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="index.htm"><img src="../gifs/txthome.gif" alt="Home" border="0"></a></td><td align="right" valign="top" width="172"><a href="ch24_04.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0"></a></td></tr><tr><td align="left" valign="top" width="172">24.2. Efficiency</td><td align="center" valign="top" width="171"><a href="index/index.htm"><img src="../gifs/index.gif" alt="Book Index" border="0"></a></td><td align="right" valign="top" width="172">24.4. Fluent Perl</td></tr></table></div><hr width="515" align="left"><!-- LIBRARY NAV BAR --><img src="../gifs/smnavbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links"><p><font size="-1"><a href="copyrght.htm">Copyright &copy; 2001</a> O'Reilly &amp; Associates. All rights reserved.</font></p><map name="library-map"> <area shape="rect" coords="2,-1,79,99" href="../index.htm"><area shape="rect" coords="84,1,157,108" href="../perlnut/index.htm"><area shape="rect" coords="162,2,248,125" href="../prog/index.htm"><area shape="rect" coords="253,2,326,130" href="../advprog/index.htm"><area shape="rect" coords="332,1,407,112" href="../cookbook/index.htm"><area shape="rect" coords="414,2,523,103" href="../sysadmin/index.htm"></map><!-- END OF BODY --></body></html>

⌨️ 快捷键说明

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