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

📄 ch01_08.htm

📁 编程珍珠,里面很多好用的代码,大家可以参考学习呵呵,
💻 HTM
字号:
<html><head><title>List Processing (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="List Processing"><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="ch01_07.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="ch01_01.htm">Chapter 1: An Overview of Perl</a></td><td align="right" valign="top" width="172"><a href="ch01_09.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">1.8. List Processing</h2><p><a name="INDEX-391"></a>Much earlier in this chapter, we mentioned that Perl has two maincontexts, scalar context (for dealing with singular things) and listcontext (for dealing with plural things).  Many of the traditionaloperators we've described so far have been strictly scalar in theiroperation.  They always take singular arguments (or pairs of singulararguments for binary operators) and always produce a singular result,even in list context.  So if you write this:<blockquote><pre class="programlisting">@array = (1 + 2, 3 - 4, 5 * 6, 7 / 8);</pre></blockquote>you know that the list on the right side contains exactly four values,because the ordinary math operators always produce scalar values, evenin the list context provided by the assignment to an array.</p><p>However, other Perl operators can produce either a scalar or a listvalue, depending on their context.  They just "know" whether a scalar ora list is expected of them.  But how will you know that? It turns out tobe pretty easy to figure out, once you get your mind around a few keyconcepts.</p><p><a name="INDEX-392"></a><a name="INDEX-393"></a>First, list context has to be provided by something in the"surroundings".  In the previous example, the list assignment provides it.Earlier we saw that the list of a <tt class="literal">foreach</tt> loop provides it.The <tt class="literal">print</tt> operator also provides it.  But you don't have tolearn these one by one.</p><p>If you look at the various syntax summaries scattered throughout therest of the book, you'll see various operators that are defined totake a <em class="replaceable">LIST</em> as an argument. Those are theoperators that <em class="emphasis">provide</em> a list context.Throughout this book, <em class="replaceable">LIST</em> is used as aspecific technical term to mean "a syntactic construct that provides alist context". For example, if you look up <tt class="literal">sort</tt>,you'll find the syntax summary:<blockquote><pre class="programlisting">sort <em class="replaceable">LIST</em></pre></blockquote>That means that <tt class="literal">sort</tt> provides a list context to its arguments.</p><p>Second, at compile time (that is, while Perl is parsing your programand translating to internal opcodes), any operator that takes a <em class="replaceable">LIST</em>provides a list context to each syntactic element of that <em class="replaceable">LIST</em>.  Soevery top-level operator or entity in the <em class="replaceable">LIST</em> knows at compile timethat it's supposed to produce the best list it knows how to produce.This means that if you say:<blockquote><pre class="programlisting">sort @dudes, @chicks, other();</pre></blockquote>then each of <tt class="literal">@dudes</tt>, <tt class="literal">@chicks</tt>,and <tt class="literal">other()</tt> knows at compile time that it'ssupposed to produce a list value rather than a scalar value.  So thecompiler generates internal opcodes that reflect this.</p><p>Later, at run time (when the internal opcodes are actuallyinterpreted), each of those <em class="replaceable">LIST</em> elementsproduces its list in turn, and then (this is important) all theseparate lists are joined together, end to end, into a single list.And that squashed-flat, one-dimensional list is what is finally handedoff to the function that wanted the <em class="replaceable">LIST</em> inthe first place.  So if <tt class="literal">@dudes</tt> contains<tt class="literal">(Fred,Barney)</tt>, <tt class="literal">@chicks</tt> contains<tt class="literal">(Wilma,Betty)</tt>, and the <tt class="literal">other()</tt>function returns the single-element list <tt class="literal">(Dino)</tt>,then the <em class="replaceable">LIST</em> that <tt class="literal">sort</tt>sees is:<blockquote><pre class="programlisting">(Fred,Barney,Wilma,Betty,Dino)</pre></blockquote>and the <em class="replaceable">LIST</em> that <tt class="literal">sort</tt>returns is:<blockquote><pre class="programlisting">(Barney,Betty,Dino,Fred,Wilma)</pre></blockquote><a name="INDEX-394"></a></p><p><a name="INDEX-395"></a><a name="INDEX-396"></a><a name="INDEX-397"></a><a name="INDEX-398"></a><a name="INDEX-399"></a>Some operators produce lists (like <tt class="literal">keys</tt>), while someconsume them (like <tt class="literal">print</tt>), and others transform listsinto other lists (like <tt class="literal">sort</tt>).  Operators in the lastcategory can be considered filters, except that, unlikein the shell, the flow of data is from right to left, since listoperators operate on arguments passed in from the right.  You canstack up several list operators in a row:<blockquote><pre class="programlisting">print reverse sort map {lc} keys %hash;</pre></blockquote>That takes the keys of <tt class="literal">%hash</tt> and returns them tothe <tt class="literal">map</tt> function, which lowercases all the keys byapplying the <tt class="literal">lc</tt> operator to each of them, andpasses them to the <tt class="literal">sort</tt> function, which sorts them,and passes them to the <tt class="literal">reverse</tt> function, whichreverses the order of the list elements, and passes them to the<tt class="literal">print</tt> function, which prints them.</p><p>As you can see, that's much easier to describe in Perl than in English.</p><p>There are many other ways in which list processing produces morenatural code.  We can't enumerate all the ways here, but for anexample, let's go back to regular expressions for a moment.  We talkedabout using a pattern in a scalar context to see whether it matched,but if instead you use a pattern in a list context, it does somethingelse: it pulls out all the backreferences as a list.  Suppose you'researching through a log file or a mailbox, and you want to parse astring containing a time of the form "12:59:59 am".  You might saythis:<blockquote><pre class="programlisting">($hour, $min, $sec, $ampm) = /(\d+):(\d+):(\d+) *(\w+)/;</pre></blockquote>That's a convenient way to set several variables simultaneously.  Butyou could just as easily say<blockquote><pre class="programlisting">@hmsa = /(\d+):(\d+):(\d+) *(\w+)/;</pre></blockquote>and put all four values into one array.  Oddly, by decoupling the powerof regular expressions from the power of Perl expressions, list contextincreases the power of the language.  We don't often admit it, butPerl is actually an orthogonal language in addition to being a diagonallanguage.  Have your cake, and eat it too.</p><!-- 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="ch01_07.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="ch01_09.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0"></a></td></tr><tr><td align="left" valign="top" width="172">1.7. Regular Expressions</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">1.9. What You Don't Know Won't Hurt You (Much)</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 + -