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

📄 ch05_01.htm

📁 By Tom Christiansen and Nathan Torkington ISBN 1-56592-243-3 First Edition, published August 1998
💻 HTM
字号:
<HTML><HEAD><METANAME="DC.title"CONTENT="Perl Cookbook"><METANAME="DC.creator"CONTENT="Tom Christiansen &amp; Nathan Torkington"><METANAME="DC.publisher"CONTENT="O'Reilly &amp; Associates, Inc."><METANAME="DC.date"CONTENT="1999-07-02T01:32:24Z"><METANAME="DC.type"CONTENT="Text.Monograph"><METANAME="DC.format"CONTENT="text/html"SCHEME="MIME"><METANAME="DC.source"CONTENT="1-56592-243-3"SCHEME="ISBN"><METANAME="DC.language"CONTENT="en-US"><METANAME="generator"CONTENT="Jade 1.1/O'Reilly DocBook 3.0 to HTML 4.0"><LINKREV="made"HREF="mailto:online-books@oreilly.com"TITLE="Online Books Comments"><LINKREL="up"HREF="index.htm"TITLE="Perl Cookbook"><LINKREL="prev"HREF="ch04_20.htm"TITLE="4.19. Program: permute"><LINKREL="next"HREF="ch05_02.htm"TITLE="5.1. Adding an Element to a Hash"></HEAD><BODYBGCOLOR="#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="Perl Cookbook"><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><p><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch04_20.htm"TITLE="4.19. Program: permute"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 4.19. Program: permute"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch05_02.htm"TITLE="5.1. Adding an Element to a Hash"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 5.1. Adding an Element to a Hash"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="chapter"><H1CLASS="chapter"><ACLASS="title"NAME="ch05-38793">5. Hashes</A></H1><DIVCLASS="htmltoc"><P><B>Contents:</B><BR><ACLASS="sect1"HREF="#ch05-22072"TITLE="5.0. Introduction">Introduction</A><BR><ACLASS="sect1"HREF="ch05_02.htm"TITLE="5.1. Adding an Element to a Hash">Adding an Element to a Hash</A><BR><ACLASS="sect1"HREF="ch05_03.htm"TITLE="5.2. Testing for the Presence of a Key in a Hash">Testing for the Presence of a Key in a Hash</A><BR><ACLASS="sect1"HREF="ch05_04.htm"TITLE="5.3. Deleting from a Hash">Deleting from a Hash</A><BR><ACLASS="sect1"HREF="ch05_05.htm"TITLE="5.4. Traversing a Hash">Traversing a Hash</A><BR><ACLASS="sect1"HREF="ch05_06.htm"TITLE="5.5. Printing a Hash">Printing a Hash</A><BR><ACLASS="sect1"HREF="ch05_07.htm"TITLE="5.6. Retrieving from a Hash in Insertion Order">Retrieving from a Hash in Insertion Order</A><BR><ACLASS="sect1"HREF="ch05_08.htm"TITLE="5.7. Hashes with Multiple Values Per Key">Hashes with Multiple Values Per Key</A><BR><ACLASS="sect1"HREF="ch05_09.htm"TITLE="5.8. Inverting a Hash">Inverting a Hash</A><BR><ACLASS="sect1"HREF="ch05_10.htm"TITLE="5.9. Sorting a Hash">Sorting a Hash</A><BR><ACLASS="sect1"HREF="ch05_11.htm"TITLE="5.10. Merging Hashes">Merging Hashes</A><BR><ACLASS="sect1"HREF="ch05_12.htm"TITLE="5.11. Finding Common or Different Keys in Two Hashes">Finding Common or Different Keys in Two Hashes</A><BR><ACLASS="sect1"HREF="ch05_13.htm"TITLE="5.12. Hashing References">Hashing References</A><BR><ACLASS="sect1"HREF="ch05_14.htm"TITLE="5.13. Presizing a Hash">Presizing a Hash</A><BR><ACLASS="sect1"HREF="ch05_15.htm"TITLE="5.14. Finding the Most Common Anything">Finding the Most Common Anything</A><BR><ACLASS="sect1"HREF="ch05_16.htm"TITLE="5.15. Representing Relationships Between Data">Representing Relationships Between Data</A><BR><ACLASS="sect1"HREF="ch05_17.htm"TITLE="5.16. Program: dutree">Program: dutree</A></P><P></P></DIV><DIVCLASS="epigraph"ALIGN="right"><PCLASS="para"ALIGN="right"><I>Doing linear scans over an associative array is like trying to club someone to death with a loaded Uzi.</I></P><PCLASS="attribution"ALIGN="right">-&nbsp;Larry Wall </P></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch05-22072">5.0. Introduction</A></H2><PCLASS="para"><ACLASS="indexterm"NAME="ch05-idx-1000006415-0"></A>People and parts of computer programs interact in all sorts of ways. Single scalar variables are like hermits, living a solitary existence whose only meaning comes from within the individual. Arrays are like cults, where multitudes marshal themselves under the name of a charismatic leader. In the middle lies the comfortable, intimate ground of the one-to-one relationship that is the hash. (Older documentation for Perl often called hashes <ICLASS="firstterm">associative arrays</I><ACLASS="indexterm"NAME="ch05-idx-1000006417-0"></A>, but that's a mouthful. Other languages that support similar constructs sometimes use different terms for them; you may hear about <ICLASS="firstterm">hash tables</I>, <ICLASS="firstterm">tables</I>, <ICLASS="firstterm">dictionaries</I>, <ICLASS="firstterm">mappings</I>, or even <ICLASS="firstterm">alists</I>, depending on the language.)</P><PCLASS="para">Unfortunately, this isn't a relationship of equals. Hashes are an <ICLASS="firstterm">of</I> relationship, like saying "Andy is the boss of Nat," "The blood pressure of our patient is 112/62," and "The name of journal ISSN 1087-903X is <EMCLASS="emphasis">The Perl Journal</EM>." Hashes only give convenient ways to access values for "Nat's boss" and "1087-903X's name"; you can't ask "Whose boss is Andy?" Finding the answer to that question is a recipe in this chapter.</P><PCLASS="para">Fortunately, hashes have their benefits, just like relationships. Hashes are a built-in data type in Perl. Their use reduces many complex algorithms to simple variable accesses. They are also fast and convenient ways to build indices and quick lookup tables.</P><PCLASS="para">It's time to put a name to these notions. The relationship embodied in a hash is a good thing to use for its name. For instance, the relationships in the examples above are <ICLASS="firstterm">boss of</I>, <ICLASS="firstterm">blood pressure of</I>, and <ICLASS="firstterm">name of</I>. We'd give them Perl names <CODECLASS="literal">%boss</CODE>, <CODECLASS="literal">%blood_ pressure</CODE>, and <CODECLASS="literal">%name</CODE>. Where a lone scalar has <CODECLASS="literal">$</CODE> as its type identifier and an entire array has <CODECLASS="literal">@</CODE>, a hash has <CODECLASS="literal">%</CODE>.</P><PCLASS="para">Only use the <CODECLASS="literal">%</CODE><ACLASS="indexterm"NAME="ch05-idx-1000006418-0"></A> when referring to the hash as a whole, such as <CODECLASS="literal">%boss</CODE>. When referring to the value for a key, it's a single scalar value and so a <CODECLASS="literal">$</CODE> is called for, just as when referring to one element of an array you also use a <CODECLASS="literal">$</CODE>. This means that "the boss of Nat" would be written as <CODECLASS="literal">$boss{&quot;Nat&quot;}</CODE>.</P><PCLASS="para"><ACLASS="indexterm"NAME="ch05-idx-1000006419-0"></A><ACLASS="indexterm"NAME="ch05-idx-1000006419-1"></A><ACLASS="indexterm"NAME="ch05-idx-1000006419-2"></A>A regular array uses whole numbers for indices, but the indices of a hash are always strings. Its values may be any arbitrary scalar values, including references. Using references as values, you can create hashes that hold not merely strings or numbers, but also arrays, other hashes, or objects. (Or rather, references to arrays, hashes, or objects.)</P><PCLASS="para"><ACLASS="indexterm"NAME="ch05-idx-1000006454-0"></A>A hash can be initialized with a list, where elements of the list are key and value pairs:</P><PRECLASS="programlisting">%age = ( &quot;Nat&quot;,   24,         &quot;Jules&quot;, 25,         &quot;Josh&quot;,  17  );</PRE><PCLASS="para">This is equivalent to:</P><PRECLASS="programlisting">$age{&quot;Nat&quot;}   = 24;$age{&quot;Jules&quot;} = 25;$age{&quot;Josh&quot;}  = 17;</PRE><PCLASS="para">To make it easier to read and write hash initializations, the <CODECLASS="literal">=&gt;</CODE><ACLASS="indexterm"NAME="ch05-idx-1000006420-0"></A><ACLASS="indexterm"NAME="ch05-idx-1000006420-1"></A> operator, sometimes known as a<CODECLASS="literal"> </CODE><ICLASS="firstterm">comma arrow</I><CODECLASS="literal">, was created. Mostly it behaves as a better-looking comma. For example, you can write a hash initialization this way:</CODE></P><PRECLASS="programlisting">%food_color = (               &quot;Apple&quot;  =&gt; &quot;red&quot;,               &quot;Banana&quot; =&gt; &quot;yellow&quot;,               &quot;Lemon&quot;  =&gt; &quot;yellow&quot;,               &quot;Carrot&quot; =&gt; &quot;orange&quot;              );</PRE><PCLASS="para">(This particular hash is used in many examples in this chapter.) This initialization is also an example of <EMCLASS="emphasis">hash-list equivalence </EM> &nbsp;-   hashes behave in some ways as though they were lists of key-value pairs. We'll use this in a number of recipes, including the merging and inverting recipes.</P><PCLASS="para">Unlike a regular comma, the comma arrow has a special property: It quotes any word preceding it, which means you can safely omit the quotes and improve legibility. Single-word hash keys are also automatically quoted, which means you can write <CODECLASS="literal">$hash{somekey}</CODE> instead of <CODECLASS="literal">$hash{&quot;somekey&quot;}</CODE>. You could rewrite the preceding initialization of <CODECLASS="literal">%food_color</CODE> as:</P><PRECLASS="programlisting">%food_color = (                Apple  =&gt; &quot;red&quot;,                Banana =&gt; &quot;yellow&quot;,                Lemon  =&gt; &quot;yellow&quot;,                Carrot =&gt; &quot;orange&quot;               );</PRE><PCLASS="para">One important issue to be aware of regarding hashes is that their elements are stored in an internal order convenient for efficient retrieval. This means that no matter what order you insert your data, it will come out in an unpredictable disorder.<ACLASS="indexterm"NAME="ch05-idx-1000006421-0"></A></P><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch05-pgfId-1000005714">See Also</A></H3><PCLASS="para">The <CODECLASS="literal">unshift</CODE> and <CODECLASS="literal">splice</CODE> functions in <EMCLASS="emphasis">perlfunc (1) </EM>and <ACLASS="olink"HREF="../prog/ch03_01.htm">Chapter 3</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A>; the discussions of closures in <EMCLASS="emphasis">perlsub (1)</EM> and <EMCLASS="emphasis">perlref  (1)</EM>; and <ACLASS="olink"HREF="../prog/ch04_01.htm">Chapter 4</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A></P></DIV></DIV></DIV><DIVCLASS="htmlnav"><P></P><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch04_20.htm"TITLE="4.19. Program: permute"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 4.19. Program: permute"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="book"HREF="index.htm"TITLE="Perl Cookbook"><IMGSRC="../gifs/txthome.gif"ALT="Perl Cookbook"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch05_02.htm"TITLE="5.1. Adding an Element to a Hash"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 5.1. Adding an Element to a Hash"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">4.19. Program: permute</TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="index"HREF="index/index.htm"TITLE="Book Index"><IMGSRC="../gifs/index.gif"ALT="Book Index"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228">5.1. Adding an Element to a Hash</TD></TR></TABLE><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><FONTSIZE="-1"></DIV<!-- LIBRARY NAV BAR --> <img src="../gifs/smnavbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links"><p> <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 + -