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

📄 ch03_04.htm

📁 by Randal L. Schwartz and Tom Phoenix ISBN 0-596-00132-0 Third Edition, published July 2001. (See
💻 HTM
字号:
<html><head><title>List Assignment (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 &amp; 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="ch03_03.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="ch03_05.htm"><img alt="Next" border="0" src="../gifs/txtnexta.gif" /></a></td></tr></table></div><h2 class="sect1">3.4. List Assignment</h2><p><a name="INDEX-276" /> <a name="INDEX-277" /> <a name="INDEX-278" />Inmuch the same way as scalar values may be assigned to variables, listvalues may also be assigned to variables:</p><blockquote><pre class="code">($fred, $barney, $dino) = ("flintstone", "rubble", undef);</pre></blockquote><p>All three variables in the list on the left get new values, just asif we did three separate assignments. Since the list is built upbefore the assignment starts, this makes it easy to swap twovariables' values in Perl:<a href="#FOOTNOTE-72">[72]</a></p><blockquote class="footnote"> <a name="FOOTNOTE-72" /><p>[72]As opposed to inlanguages like C, which has no easy way to do this in general. Cprogrammers usually resort to some kind of macro to do this, or use avariable to temporarily hold the value.</p> </blockquote><blockquote><pre class="code">($fred, $barney) = ($barney, $fred); # swap those values($betty[0], $betty[1]) = ($betty[1], $betty[0]);</pre></blockquote><p>But what happens if the number of variables (on the left side of theequals sign) isn't the same as the number of values (from theright side)? In a list assignment, extra values are silentlyignored -- Perl figures that if you wanted those values storedsomewhere, you would have told it where to store them. Alternatively,if you have too many variables, the extras get the value <tt class="literal">undef</tt>.<a href="#FOOTNOTE-73">[73]</a></p><blockquote class="footnote"> <a name="FOOTNOTE-73" /><p>[73]Well, that'strue for scalar variables. Array variables get an empty list, aswe'll see in a moment.</p> </blockquote><blockquote><pre class="code">($fred, $barney) = qw&lt; flintstone rubble slate granite &gt;; # two ignored items($wilma, $dino) = qw[flintstone];                         # $dino gets undef</pre></blockquote><p>Now that we can assign lists, you <em class="emphasis">could</em> build upan array of strings with a line of code like this:<a href="#FOOTNOTE-74">[74]</a></p><blockquote class="footnote"><a name="FOOTNOTE-74" /><p>[74]We're cheating by assuming that the<tt class="literal">rocks</tt> array is empty before this statement. Ifthere were a value in <tt class="literal">$rocks[7]</tt>, say, thisassignment wouldn't affect that element. </p> </blockquote><blockquote><pre class="code">($rocks[0], $rocks[1], $rocks[2], $rocks[3]) = qw/talc mica feldspar quartz/;</pre></blockquote><p>But when you wish to refer to an entire array, Perl has a simplernotation. Just use the <a name="INDEX-279" /> <a name="INDEX-280" />at-sign (<tt class="literal">@</tt>) before the name of the array (and noindex brackets after it) to refer to the entire array at once. Youcan read this as "all of the," so<tt class="literal">@rocks</tt> is "all of therocks."<a href="#FOOTNOTE-75">[75]</a> This works on either side of the assignment operator:</p><blockquote class="footnote"> <a name="FOOTNOTE-75" /><p>[75]Larry claims that he chose the dollarand at-sign because they can be read as <tt class="literal">$calar</tt>(scalar) and <tt class="literal">@rray</tt> (array). If youdon't get that, or remember it that way, no big deal.</p></blockquote><blockquote><pre class="code">@rocks = qw/ bedrock slate lava /;@tiny = ( );                       # the empty list@giant = 1..1e5;                  # a list with 100,000 elements@stuff = (@giant, undef, @giant); # a list with 200,001 elements$dino = "granite";@quarry = (@rocks, "crushed rock", @tiny, $dino);</pre></blockquote><p>That last assignment gives <tt class="literal">@quarry</tt> thefive-element list <tt class="literal">(bedrock, slate, lava, crushed rock,granite)</tt>, since <tt class="literal">@tiny</tt> contributes zeroelements to the list. (In particular, it doesn't put an<tt class="literal">undef</tt> item into thelist -- but we could do that explicitly, as we did with<tt class="literal">@stuff</tt> earlier.) It's also worth noting thatan array name is replaced by the list it contains. An arraydoesn't become an element in the list, because these arrays cancontain only scalars, not other arrays.<a href="#FOOTNOTE-76">[76]</a></p><blockquote class="footnote"> <a name="FOOTNOTE-76" /><p>[76]But when youget into more advanced Perl, you'll learn about a special kindof scalar called a<a name="INDEX-281" />reference. Thatlets us make what are informally called "lists of lists",among other interesting and useful structures. But in that case,you're still not really storing a list into a list;you're storing a reference to an array.</p> </blockquote><p>The value of an array variable that has not yet been assigned is<tt class="literal">( )</tt>, the empty list. Just as new, empty scalarsstart out with <tt class="literal">undef</tt>, new, empty arrays start outwith the empty list.</p><p>It's worth noting that when an array is copied to anotherarray, it's still a list assignment. The lists are simplystored in arrays. For example:</p><blockquote><pre class="code">@copy = @quarry; # copy a list from one array to another</pre></blockquote><a name="lperl3-CHP-3-SECT-4.1" /><div class="sect2"><h3 class="sect2">3.4.1. The pop and push Operators</h3><p>You <em class="emphasis">could</em> add new items to the end of an arrayby simply storing them into elements with new, larger indices. Butreal Perl programmers don't use indices.<a href="#FOOTNOTE-77">[77]</a> So in the next few sections, we'll present someways to work with an array without using indices.</p><blockquote class="footnote"> <a name="FOOTNOTE-77" /><p>[77]Ofcourse, we're joking. But there's a kernel of truth inthis joke. Indexing into arrays is not using Perl's strengths.If you use the <tt class="literal">pop</tt>, <tt class="literal">push</tt>, andsimilar operators that avoid using indexing, your code will generallybe faster than if you use many indices, as well as being more likelyto avoid "off-by-one" errors, often called"fencepost" errors. Occasionally, a beginning Perlprogrammer (wanting to see how Perl's speed compares toC's) will take, say, a sorting algorithm optimized for C (withmany array index operations), rewrite it straightforward in Perl(again, with many index operations) and wonder why it's soslow. The answer is that using a Stradivarius violin to pound nailsshould not be considered a sound construction technique.</p></blockquote><p>One common use of an array is as a stack of information, where newvalues are added to and removed from the right-hand side of the list.(This is the end with the "last" items in the array, theend with the highest index values.) These operations occur oftenenough to have their own special functions.</p><p>The <tt class="literal">pop</tt><a name="INDEX-282" /> operator takes the last<a name="INDEX-283" />element off of an array, andreturns it:</p><blockquote><pre class="code">@array = 5..9;$fred = pop(@array);  # $fred gets 9, @array now has (5, 6, 7, 8)$barney = pop @array; # $barney gets 8, @array now has (5, 6, 7)pop @array;           # @array now has (5, 6). (The 7 is discarded.)</pre></blockquote><p>That last example uses <tt class="literal">pop</tt> "in a voidcontext," which is merely a fancy way of saying the returnvalue isn't going anywhere. There's nothing wrong withusing <tt class="literal">pop</tt> in this way, if that's what youwant.</p><p>If the array is empty, <tt class="literal">pop</tt> will leave it alone(since there is no element to remove), and it will return <tt class="literal">undef</tt>.</p><p>You may have noticed that <tt class="literal">pop</tt> maybe used with or without parentheses. This is a general rule in Perl:as long as the meaning isn't changed by removing the<a name="INDEX-284" />parentheses, they'reoptional.<a href="#FOOTNOTE-78">[78]</a></p><blockquote class="footnote"> <a name="FOOTNOTE-78" /><p>[78]A reader from the educated class willrecognize that this is a tautology. </p> </blockquote><p>The converse operation is <tt class="literal">push</tt><a name="INDEX-285" />, which adds an element (or a list ofelements) to the end of an array:</p><blockquote><pre class="code">push(@array, 0);      # @array now has (5, 6, 0)push @array, 8;       # @array now has (5, 6, 0, 8)push @array, 1..10;   # @array now has those ten new elements@others = qw/ 9 0 2 1 0 /;push @array, @others; # @array now has those five new elements (19 total)</pre></blockquote><p>Note that the first argument to <tt class="literal">push</tt> or the only argument for <tt class="literal">pop</tt> must be an array variable -- pushingand popping would not make sense on a literal list.</p></div><a name="lperl3-CHP-3-SECT-4.2" /><div class="sect2"><h3 class="sect2">3.4.2. The shift and unshift Operators</h3><p>The <tt class="literal">push</tt> and <tt class="literal">pop</tt> operators do things to the end of anarray (or the right side of an array, or the portion with the highestsubscripts, depending upon how you like to think of it). Similarly,the <tt class="literal">unshift</tt><a name="INDEX-286" /> and <tt class="literal">shift</tt><a name="INDEX-287" /> operators perform the correspondingactions on the "start" of the array (or the"left" side of an array, or the portion with the lowestsubscripts). Here are a few examples:</p><blockquote><pre class="code">@array = qw# dino fred barney #;$a = shift(@array);      # $a gets "dino", @array now has ("fred", "barney")$b = shift @array;       # $b gets "fred", @array now has ("barney")shift @array;            # @array is now empty$c = shift @array;       # $c gets undef, @array is still emptyunshift(@array, 5);      # @array now has the one-element list (5)unshift @array, 4;       # @array now has (4, 5);@others = 1..3;unshift @array, @others; # @array now has (1, 2, 3, 4, 5)</pre></blockquote><p>Analogous to <tt class="literal">pop</tt>, <tt class="literal">shift</tt> returns <tt class="literal">undef</tt> if given an empty arrayvariable.<a name="INDEX-288" /><a name="INDEX-289" /><a name="INDEX-290" /></p></div><hr width="684" align="left" /><div class="navbar"><table width="684" border="0"><tr><td align="left" valign="top" width="228"><a href="ch03_03.htm"><img alt="Previous" border="0" src="../gifs/txtpreva.gif" /></a></td><td align="center" valign="top" width="228"><a href="index.htm"><img alt="Home" border="0" src="../gifs/txthome.gif" /></a></td><td align="right" valign="top" width="228"><a href="ch03_05.htm"><img alt="Next" border="0" src="../gifs/txtnexta.gif" /></a></td></tr><tr><td align="left" valign="top" width="228">3.3. List Literals</td><td align="center" valign="top" width="228"><a href="index/index.htm"><img alt="Book Index" border="0" src="../gifs/index.gif" /></a></td><td align="right" valign="top" width="228">3.5. Interpolating Arrays into Strings</td></tr></table></div><hr width="684" align="left" /><img alt="Library Navigation Links" border="0" src="../gifs/navbar.gif" usemap="#library-map" /><p><p><font size="-1"><a href="copyrght.htm">Copyright &copy; 2002</a> O'Reilly &amp; 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 + -