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

📄 ch05_08.htm

📁 By Tom Christiansen and Nathan Torkington ISBN 1-56592-243-3 First Edition, published August 1998
💻 HTM
字号:
<HTML><HEAD><TITLE>Recipe 5.7. Hashes with Multiple Values Per Key (Perl Cookbook)</TITLE><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:39Z"><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="ch05_01.htm"TITLE="5. Hashes"><LINKREL="prev"HREF="ch05_07.htm"TITLE="5.6. Retrieving from a Hash in Insertion Order"><LINKREL="next"HREF="ch05_09.htm"TITLE="5.8. Inverting 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="ch05_07.htm"TITLE="5.6. Retrieving from a Hash in Insertion Order"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 5.6. Retrieving from a Hash in Insertion Order"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"><ACLASS="chapter"REL="up"HREF="ch05_01.htm"TITLE="5. Hashes"></A></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch05_09.htm"TITLE="5.8. Inverting a Hash"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 5.8. Inverting a Hash"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch05-12773">5.7. Hashes with Multiple Values Per Key</A></H2><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch05-pgfId-684">Problem <ACLASS="indexterm"NAME="ch05-idx-1000006470-0"></A></A></H3><PCLASS="para">You want to store more than one value for each key.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch05-pgfId-690">Solution</A></H3><PCLASS="para">Store an array reference in <CODECLASS="literal">$hash{$key}</CODE>, and put the values into that array.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch05-pgfId-696">Discussion</A></H3><PCLASS="para">You can only store scalar values in a hash. References, however, are scalars. This solves the problem of storing multiple values for one key by making <CODECLASS="literal">$hash{$key}</CODE> a reference to an array containing values for <CODECLASS="literal">$key</CODE>. The normal hash operations &nbsp;-  insertion, deletion, iteration, and testing for existence &nbsp;-  can now be written in terms of array operations like <CODECLASS="literal">push</CODE>, <CODECLASS="literal">splice</CODE>, and <CODECLASS="literal">foreach</CODE>.</P><PCLASS="para">This code shows simple insertion into the hash. It processes the output of <ICLASS="filename">who </I>(1) on Unix machines and outputs a terse listing of users and the ttys they're logged in on:</P><PRECLASS="programlisting">%ttys = ();open(WHO, &quot;who|&quot;)                   or die &quot;can't open who: $!&quot;;while (&lt;WHO&gt;) {    ($user, $tty) = split;    push( @{$ttys{$user}}, $tty );}foreach $user (sort keys %ttys) {    print &quot;$user: @{$ttys{$user}}\n&quot;;}</PRE><PCLASS="para">The heart of the code is the <CODECLASS="literal">push</CODE> line, the multihash version of <CODECLASS="literal">$ttys{$user}</CODE> <CODECLASS="literal">=</CODE> <CODECLASS="literal">$tty</CODE>. We interpolate all the tty names in the <CODECLASS="literal">print</CODE> line with <CODECLASS="literal">@{$ttys{$user}}</CODE>. We'd loop over the anonymous array if, for instance, we wanted to print the owner of each tty:</P><PRECLASS="programlisting">foreach $user (sort keys %ttys) {    print &quot;$user: &quot;, scalar( @{$ttys{$user}} ), &quot; ttys.\n&quot;;    foreach $tty (sort @{$ttys{$user}}) {        @stat = stat(&quot;/dev/$tty&quot;);        $user = @stat ? ( getpwuid($stat[4]) )[0] : &quot;(not available)&quot;;        print &quot;\t$tty (owned by $user)\n&quot;;    }}</PRE><PCLASS="para"><CODECLASS="literal"></CODE><ACLASS="indexterm"NAME="ch05-idx-1000006480-0"></A><ACLASS="indexterm"NAME="ch05-idx-1000006480-1"></A>The <CODECLASS="literal">exists</CODE> function can have two meanings: "Is there at least one value for this key?" and "Does this value exist for this key?" Implementing the second approach requires searching the array for the value. The <CODECLASS="literal">delete</CODE> function and the first sense of <CODECLASS="literal">exists</CODE> are interrelated: If we can guarantee that no anonymous array is ever empty, we can use the built-in <CODECLASS="literal">exists</CODE>. We ensure that no anonymous array is ever empty by checking for such a situation after deleting an element:</P><PRECLASS="programlisting">sub multihash_delete {    my ($hash, $key, $value) = @_;    my $i;    return unless ref( $hash-&gt;{$key} );    for ($i = 0; $i &lt; @{ $hash-&gt;{$key} }; $i++) {        if ($hash-&gt;{$key}-&gt;[$i] eq $value) {            splice( @{$hash-&gt;{$key}}, $i, 1);            last;        }    }    delete $hash-&gt;{$key} unless @{$hash-&gt;{$key}};}</PRE><PCLASS="para">The alternative approach to multivalued hashes is given in <ACLASS="xref"HREF="ch13_01.htm"TITLE="Classes, Objects, and Ties">Chapter 13, <CITECLASS="chapter">Classes, Objects, and Ties</CITE></A>, implemented as tied normal hashes.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch05-pgfId-776">See Also</A></H3><PCLASS="para">The <CODECLASS="literal">splice</CODE>, <CODECLASS="literal">delete</CODE>, <CODECLASS="literal">push</CODE>, <CODECLASS="literal">foreach</CODE>, and <CODECLASS="literal">exists</CODE> functions in <EMCLASS="emphasis">perlf</EM><ICLASS="filename">unc</I> (1) 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>; <ACLASS="xref"HREF="ch11_02.htm"TITLE="Taking References to Arrays">Recipe 11.1</A>; we cover ties in <ACLASS="xref"HREF="ch13_16.htm"TITLE="Creating Magic Variables with tie">Recipe 13.15</A> <ACLASS="indexterm"NAME="ch05-idx-1000006472-0"></A></P></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="ch05_07.htm"TITLE="5.6. Retrieving from a Hash in Insertion Order"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 5.6. Retrieving from a Hash in Insertion Order"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_09.htm"TITLE="5.8. Inverting a Hash"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 5.8. Inverting a Hash"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">5.6. Retrieving from a Hash in Insertion Order</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.8. Inverting 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 + -