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

📄 ch09_04.htm

📁 编程珍珠,里面很多好用的代码,大家可以参考学习呵呵,
💻 HTM
字号:
<html><head><title>Hashes of 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 of 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="ch09_03.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="ch09_01.htm">Chapter 9: Data Structures</a></td><td align="right" valign="top" width="172"><a href="ch09_05.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">9.4. Hashes of Hashes</h2><p><a name="INDEX-2140"></a><a name="INDEX-2141"></a><a name="INDEX-2142"></a><a name="INDEX-2143"></a>A multidimensional hash is the most flexible of Perl's nestedstructures.  It's like building up a record that itself contains otherrecords.  At each level, you index into the hash with a string (quotedwhen necessary).  Remember, however, that the key/value pairs in thehash won't come out in any particular order; you can use the <tt class="literal">sort</tt>function to retrieve the pairs in whatever order you like.</p><h3 class="sect2">9.4.1. Composition of a Hash of Hashes</h3><p>You can create a hash of anonymous hashes as follows:<blockquote><pre class="programlisting">%HoH = (    flintstones =&gt; {        husband   =&gt; "fred",        pal       =&gt; "barney",    },    jetsons =&gt; {        husband   =&gt; "george",        wife      =&gt; "jane",        "his boy" =&gt; "elroy",  # Key quotes needed.    },    simpsons =&gt; {        husband   =&gt; "homer",        wife      =&gt; "marge",        kid       =&gt; "bart",    },);</pre></blockquote>To add another anonymous hash to <tt class="literal">%HoH</tt>, you can simply say:<a name="INDEX-2144"></a><blockquote><pre class="programlisting">$HoH{ mash } = {    captain  =&gt; "pierce",    major    =&gt; "burns",    corporal =&gt; "radar",};</pre></blockquote></p><h3 class="sect2">9.4.2. Generation of a Hash of Hashes</h3><p><a name="INDEX-2145"></a><a name="INDEX-2146"></a>Here are some techniques for populating a hash of hashes.  To read froma file with the following format:<blockquote><pre class="programlisting">flintstones: husband=fred pal=barney wife=wilma pet=dino</pre></blockquote>you could use either of the following two loops:<blockquote><pre class="programlisting">while ( &lt;&gt; ) {    next unless s/^(.*?):\s*//;    $who = $1;    for $field ( split ) {        ($key, $value) = split /=/, $field;        $HoH{$who}{$key} = $value;    }}while ( &lt;&gt; ) {    next unless s/^(.*?):\s*//;    $who = $1;    $rec = {};    $HoH{$who} = $rec;    for $field ( split ) {        ($key, $value) = split /=/, $field;        $rec-&gt;{$key} = $value;    }}</pre></blockquote>If you have a subroutine <tt class="literal">get_family</tt> that returns a list ofkey/value pairs, you can use it to stuff <tt class="literal">%HoH</tt> with either ofthese three snippets:<blockquote><pre class="programlisting">for $group ( "simpsons", "jetsons", "flintstones" ) {    $HoH{$group} = { get_family($group) };}for $group ( "simpsons", "jetsons", "flintstones" ) {    @members = get_family($group);    $HoH{$group} = { @members };}sub hash_families {    my @ret;    for $group ( @_ ) {        push @ret, $group, { get_family($group) };    }    return @ret;}%HoH = hash_families( "simpsons", "jetsons", "flintstones" );</pre></blockquote>You can append new members to an existing hash like so:<blockquote><pre class="programlisting">%new_folks = (    wife =&gt; "wilma",    pet  =&gt; "dino";);for $what (keys %new_folks) {    $HoH{flintstones}{$what} = $new_folks{$what};}</pre></blockquote></p><h3 class="sect2">9.4.3. Access and Printing of a Hash of Hashes</h3><p><a name="INDEX-2147"></a><a name="INDEX-2148"></a><a name="INDEX-2149"></a><a name="INDEX-2150"></a>You can set a key/value pair of a particular hash as follows:<blockquote><pre class="programlisting">$HoH{flintstones}{wife} = "wilma";</pre></blockquote>To capitalize a particular key/value pair, apply a substitution toan element:<blockquote><pre class="programlisting">$HoH{jetsons}{'his boy'} =~ s/(\w)/\u$1/;</pre></blockquote>You can print all the families by looping through the keys of theouter hash and then looping through the keys of the inner hash:<blockquote><pre class="programlisting">for $family ( keys %HoH ) {    print "$family: ";    for $role ( keys %{ $HoH{$family} } ) {         print "$role=$HoH{$family}{$role} ";    }    print "\n";}</pre></blockquote><a name="INDEX-2151"></a><a name="INDEX-2152"></a>In very large hashes, it may be slightly faster to retrieve bothkeys and values at the same time using <tt class="literal">each</tt> (which precludes sorting):<blockquote><pre class="programlisting">while ( ($family, $roles) = each %HoH ) {    print "$family: ";    while ( ($role, $person) = each %$roles ) {        print "$role=$person ";    }    print "\n";}</pre></blockquote>(Unfortunately, it's the large hashes that really need to be sorted, oryou'll never find what you're looking for in the printout.)  You cansort the families and then the roles as follows:<blockquote><pre class="programlisting">for $family ( sort keys %HoH ) {    print "$family: ";    for $role ( sort keys %{ $HoH{$family} } ) {         print "$role=$HoH{$family}{$role} ";    }    print "\n";}</pre></blockquote>To sort the families by the number of members (instead ofASCIIbetically (or utf8ically)), you can use <tt class="literal">keys</tt> in a scalar context:<blockquote><pre class="programlisting">for $family ( sort { keys %{$HoH{$a}} &lt;=&gt; keys %{$HoH{$b}} } keys %HoH ) {    print "$family: ";    for $role ( sort keys %{ $HoH{$family} } ) {         print "$role=$HoH{$family}{$role} ";    }    print "\n";}</pre></blockquote>To sort the members of a family in some fixed order, you can assignranks to each:<blockquote><pre class="programlisting">$i = 0;for ( qw(husband wife son daughter pal pet) ) { $rank{$_} = ++$i }for $family ( sort { keys %{$HoH{$a}} &lt;=&gt; keys %{$HoH{$b}} } keys %HoH ) {    print "$family: ";    for $role ( sort { $rank{$a} &lt;=&gt; $rank{$b} } keys %{ $HoH{$family} } ) {        print "$role=$HoH{$family}{$role} ";    }    print "\n";}</pre></blockquote><a name="INDEX-2153"></a><a name="INDEX-2154"></a><a name="INDEX-2155"></a></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="ch09_03.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="ch09_05.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0"></a></td></tr><tr><td align="left" valign="top" width="172">9.3. Arrays of Hashes</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">9.5. Hashes of Functions</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 + -