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

📄 ch02_09.htm

📁 编程珍珠,里面很多好用的代码,大家可以参考学习呵呵,
💻 HTM
字号:
<html><head><title>Hashes (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="Hashes"><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="ch02_08.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="ch02_01.htm">Chapter 2: Bits and Pieces</a></td><td align="right" valign="top" width="172"><a href="ch02_10.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">2.9. Hashes</h2><a name="INDEX-707"></a><p><a name="INDEX-708"></a>As we said earlier, a hash is just a funny kind of array in which youlook values up using key strings instead of numbers.  A hash definesassociations between keys and values, so hashes are often called<em class="emphasis">associative arrays</em> by people who are not lazytypists.</p><p><a name="INDEX-709"></a><a name="INDEX-710"></a>There really isn't any such thing as a hash literal in Perl, but if youassign an ordinary list to a hash, each pair of values in the list willbe taken to indicate one key/value association:<blockquote><pre class="programlisting">%map = ('red',0xff0000,'green',0x00ff00,'blue',0x0000ff);</pre></blockquote>This has the same effect as:<blockquote><pre class="programlisting">%map = ();            # clear the hash first$map{red}   = 0xff0000;$map{green} = 0x00ff00;$map{blue}  = 0x0000ff;</pre></blockquote></p><p><a name="INDEX-711"></a>It is often more readable to use the <tt class="literal">=&gt;</tt> operator betweenkey/value pairs.  The <tt class="literal">=&gt;</tt> operator is just a synonym for acomma, but it's more visually distinctive and also quotes any bareidentifiers to the left of it (just like the identifiers in bracesabove), which makes it convenient for several sorts of operation,including initializing hash variables:<blockquote><pre class="programlisting">%map = (    red   =&gt; 0xff0000,    green =&gt; 0x00ff00,    blue  =&gt; 0x0000ff,);</pre></blockquote>or initializing anonymous hash references to be used as records:<blockquote><pre class="programlisting">$rec = {    NAME  =&gt; 'John Smith',    RANK  =&gt; 'Captain',    SERNO =&gt; '951413',};</pre></blockquote><a name="INDEX-712"></a></p><p>or using named parameters to invoke complicated functions:<blockquote><pre class="programlisting">$field = radio_group(             NAME      =&gt; 'animals',             VALUES    =&gt; ['camel', 'llama', 'ram', 'wolf'],             DEFAULT   =&gt; 'camel',             LINEBREAK =&gt; 'true',             LABELS    =&gt; \%animal_names,         );</pre></blockquote>But we're getting ahead of ourselves again.  Back to hashes.</p><p><a name="INDEX-713"></a><a name="INDEX-714"></a><a name="INDEX-715"></a><a name="INDEX-716"></a>You can use a hash variable (<tt class="literal">%hash</tt>) in a list context, in whichcase it interpolates all its key/value pairs into the list.  Butjust because the hash was initialized in a particular order doesn'tmean that the values come back out in that order.  Hashes areimplemented internally using hash tables for speedy lookup, whichmeans that the order in which entries are stored is dependent onthe internal hash function used to calculate positions in the hashtable, and not on anything interesting.  So the entries come backin a seemingly random order.  (The two elements of each key/valuepair come out in the right order, of course.)   For examples of howto arrange for an output ordering, see the <tt class="literal">keys</tt> function in<a href="ch29_01.htm">Chapter 29, "Functions"</a>.</p><p><a name="INDEX-717"></a>When you evaluate a hash variable in a scalar context, it returns atrue value only if the hash contains any key/value pairs whatsoever.If there are any key/value pairs at all, the value returned is astring consisting of the number of used buckets and the number ofallocated buckets, separated by a slash.  This is pretty much onlyuseful to find out whether Perl's (compiled in) hashing algorithmis performing poorly on your data set.  For example, you stick10,000 things in a hash, but evaluating <tt class="literal">%HASH</tt> in scalar contextreveals "<tt class="literal">1/8</tt>", which means only one out of eight buckets hasbeen touched. Presumably that one bucket contains all 10,000of your items.  This isn't supposed to happen.</p><p><a name="INDEX-718"></a><a name="INDEX-719"></a><a name="INDEX-720"></a><a name="INDEX-721"></a>To find the number of keys in a hash, use the <tt class="literal">keys</tt>function in a scalar context: <tt class="literal">scalar(keys(%HASH))</tt>.</p><p>You can emulate a multidimensional hash by specifying more than onekey within the braces, separated by commas.  The listed keys areconcatenated together, separated by the contents of<tt class="literal">$;</tt> (<tt class="literal">$SUBSCRIPT_SEPARATOR</tt>), whichhas a default value of <tt class="literal">chr(28)</tt>.  The resultingstring is used as the actual key to the hash. These two lines do thesame thing:</p><blockquote><pre class="programlisting">$people{ $state, $county } = $census_results;$people{ join $; =&gt; $state, $county } = $census_results;</pre></blockquote><p><a name="INDEX-722"></a>This feature was originally implemented to support<em class="emphasis">a2p</em>, the <em class="emphasis">awk</em>-to-Perltranslator.  These days, you'd usually just use a real (well, realer)multidimensional array as described in <a href="ch09_01.htm">Chapter 9, "Data Structures"</a>.  One place the old style isstill useful is for hashes tied to DBM files (see<tt class="literal">DB_File</tt> in <a href="ch32_01.htm">Chapter 32, "Standard Modules"</a>),which don't support multidimensional keys.</p><p>Don't confuse multidimensional hash emulations with slices.  The onerepresents a scalar value, and the other represents a list value:<blockquote><pre class="programlisting">$hash{ $x, $y, $z }      # a single value@hash{ $x, $y, $z }      # a slice of three values</pre></blockquote></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="ch02_08.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="ch02_10.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0"></a></td></tr><tr><td align="left" valign="top" width="172">2.8. List Values and Arrays</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">2.10. Typeglobs and Filehandles</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 + -