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

📄 ch11_10.htm

📁 By Tom Christiansen and Nathan Torkington ISBN 1-56592-243-3 First Edition, published August 1998
💻 HTM
字号:
<HTML><HEAD><TITLE>Recipe 11.9. Constructing Records (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:40:48Z"><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="ch11_01.htm"TITLE="11. References and Records"><LINKREL="prev"HREF="ch11_09.htm"TITLE="11.8. Creating References to Methods"><LINKREL="next"HREF="ch11_11.htm"TITLE="11.10. Reading and Writing Hash Records to Text Files"></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="ch11_09.htm"TITLE="11.8. Creating References to Methods"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 11.8. Creating References to Methods"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"><ACLASS="chapter"REL="up"HREF="ch11_01.htm"TITLE="11. References and Records"></A></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch11_11.htm"TITLE="11.10. Reading and Writing Hash Records to Text Files"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 11.10. Reading and Writing Hash Records to Text Files"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch11-13425">11.9. Constructing Records</A></H2><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch11-pgfId-928">Problem<ACLASS="indexterm"NAME="ch11-idx-1000004843-0"></A></A></H3><PCLASS="para">You want to create a record data type.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch11-pgfId-934">Solution</A></H3><PCLASS="para">Use a reference to an anonymous hash.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch11-pgfId-940">Discussion</A></H3><PCLASS="para">Suppose you wanted to create a data type that contained various data fields, akin to a C <CODECLASS="literal">struct</CODE> or a Pascal RECORD. The easiest way is to use an anonymous hash. For example, here's how to initialize and use that record:</P><PRECLASS="programlisting">$record = {    NAME   =&gt; &quot;Jason&quot;,    EMPNO  =&gt; 132,    TITLE  =&gt; &quot;deputy peon&quot;,    AGE    =&gt; 23,    SALARY =&gt; 37_000,    PALS   =&gt; [ &quot;Norbert&quot;, &quot;Rhys&quot;, &quot;Phineas&quot;],};printf &quot;I am %s, and my pals are %s.\n&quot;,    $record-&gt;{NAME},    join(&quot;, &quot;, @{$record-&gt;{PALS}});</PRE><PCLASS="para">Just having one of these records isn't much fun &nbsp;-  you'd like to build larger structures. For example, you might want to create a <CODECLASS="literal">%ByName</CODE> hash that you could initialize and use this way:</P><PRECLASS="programlisting"># store record$byname{ $record-&gt;{NAME} } = $record;# later on, look up by nameif ($rp = $byname{&quot;Aron&quot;}) {        # false if missing    printf &quot;Aron is employee %d.\n&quot;, $rp-&gt;{EMPNO};}# give jason a new palpush @{$byname{&quot;Jason&quot;}-&gt;{PALS}}, &quot;Theodore&quot;;printf &quot;Jason now has %d pals\n&quot;, scalar @{$byname{&quot;Jason&quot;}-&gt;{PALS}};</PRE><PCLASS="para">That makes <CODECLASS="literal">%byname</CODE> a hash of hashes, because its values are hash references. Looking up employees by name would be easy using such a structure. If we find a value in the hash, we store a reference to the record in a temporary variable, <CODECLASS="literal">$rp</CODE>, which we then use to get any field we want.</P><PCLASS="para">We can use our existing hash tools to manipulate <CODECLASS="literal">%byname</CODE>. For instance, we could use the <CODECLASS="literal">each</CODE> iterator to loop through it in an arbitrary order:</P><PRECLASS="programlisting"># Go through all recordswhile (($name, $record) = each %byname) {    printf &quot;%s is employee number %d\n&quot;, $name, $record-&gt;{EMPNO};}</PRE><PCLASS="para">What about looking employees up by employee number? Just build and use another data structure, an array of hashes called <CODECLASS="literal">@employees</CODE>. If your employee numbers aren't consecutive (for instance, they jump from 1 to 159997) an array would be a bad choice. Instead, you should use a hash mapping employee number to record. For consecutive employee numbers, use an array:</P><PRECLASS="programlisting"># store record$employees[ $record-&gt;{EMPNO} ] = $record;# lookup by idif ($rp = $employee[132]) {    printf &quot;employee number 132 is %s\n&quot;, $rp-&gt;{NAME};}</PRE><PCLASS="para">With a data structure like this, updating a record in one place effectively updates it everywhere. For example, this gives Jason a 3.5% raise:</P><PRECLASS="programlisting">$byname{&quot;Jason&quot;}-&gt;{SALARY} *= 1.035;</PRE><PCLASS="para">This change is reflected in all views of these records. Remember that both <CODECLASS="literal">$byname{&quot;Jason&quot;}</CODE> and <CODECLASS="literal">$employees[132]</CODE> refer to the same record because the references they contain refer to the same anonymous hash.</P><PCLASS="para">How would you select all records matching a particular criterion? This is what <CODECLASS="literal">grep</CODE> is for. Here's how to get everyone with "peon" in their titles or all the 27-year-olds:</P><PRECLASS="programlisting">@peons   = grep { $_-&gt;{TITLE} =~ /peon/i } @employees;@tsevens = grep { $_-&gt;{AGE}   == 27 }      @employees;</PRE><PCLASS="para">Each element of <CODECLASS="literal">@peons</CODE> and <CODECLASS="literal">@tsevens</CODE> is itself a reference to a record, making them arrays of hashes, like <CODECLASS="literal">@employees</CODE>.</P><PCLASS="para">Here's how to print all records sorted in a particular order, say by age:</P><PRECLASS="programlisting"># Go through all recordsforeach $rp (sort { $a-&gt;{AGE} &lt;=&gt; $b-&gt;{AGE} } values %byname) {    printf &quot;%s is age %d.\n&quot;, $rp-&gt;{NAME}, $rp-&gt;{AGE};    # or with a hash slice on the reference    printf &quot;%s is employee number %d.\n&quot;, @$rp{'NAME','EMPNO'};}</PRE><PCLASS="para">Rather than take time to sort them by age, you could just create another view of these records, <CODECLASS="literal">@byage</CODE>. Each element in this array, <CODECLASS="literal">$byage[27]</CODE> for instance, would be an array of all the records with that age. In effect, this is an array of arrays of hashes. You would build it this way:</P><PRECLASS="programlisting"># use @byage, an array of arrays of recordspush @{ $byage[ $record-&gt;{AGE} ] }, $record;</PRE><PCLASS="para">Then you could find them all this way:</P><PRECLASS="programlisting">for ($age = 0; $age &lt;= $#byage; $age++) {    next unless $byage[$age];    print &quot;Age $age: &quot;;    foreach $rp (@{$byage[$age]}) {        print $rp-&gt;{NAME}, &quot; &quot;;    }    print &quot;\n&quot;;}</PRE><PCLASS="para">A similar approach is to use <CODECLASS="literal">map</CODE> to avoid the <CODECLASS="literal">foreach</CODE> loop:</P><PRECLASS="programlisting">for ($age = 0; $age &lt;= $#byage; $age++) {    next unless $byage[$age];    printf &quot;Age %d: %s\n&quot;, $age,        join(&quot;, &quot;, map {$_-&gt;{NAME}} @{$byage[$age]});<ACLASS="indexterm"NAME="ch11-idx-1000004845-0"></A>}</PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch11-pgfId-1000005735">See Also</A></H3><PCLASS="para"><ACLASS="xref"HREF="ch04_14.htm"TITLE="Finding All Elements in an Array Matching Certain Criteria">Recipe 4.13</A>; <ACLASS="xref"HREF="ch11_04.htm"TITLE="Taking References to Hashes">Recipe 11.3</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="ch11_09.htm"TITLE="11.8. Creating References to Methods"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 11.8. Creating References to Methods"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="ch11_11.htm"TITLE="11.10. Reading and Writing Hash Records to Text Files"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 11.10. Reading and Writing Hash Records to Text Files"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">11.8. Creating References to Methods</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">11.10. Reading and Writing Hash Records to Text Files</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 + -