📄 ch05_02.htm
字号:
<html><head><title>Hash Element Access (Learning Perl, 3rd Edition)</title><link rel="stylesheet" type="text/css" href="../style/style1.css" /><meta name="DC.Creator" content="Randal L. Schwartz and Tom Phoenix" /><meta name="DC.Format" content="text/xml" scheme="MIME" /><meta name="DC.Language" content="en-US" /><meta name="DC.Publisher" content="O'Reilly & Associates, Inc." /><meta name="DC.Source" scheme="ISBN" content="0596001320L" /><meta name="DC.Subject.Keyword" content="stuff" /><meta name="DC.Title" content="Learning Perl, 3rd Edition" /><meta name="DC.Type" content="Text.Monograph" /></head><body bgcolor="#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="Learning Perl, 3rd Edition" /><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><table width="684" border="0"><tr><td align="left" valign="top" width="228"><a href="ch05_01.htm"><img alt="Previous" border="0" src="../gifs/txtpreva.gif" /></a></td><td align="center" valign="top" width="228"><a href="index.htm"></a></td><td align="right" valign="top" width="228"><a href="ch05_03.htm"><img alt="Next" border="0" src="../gifs/txtnexta.gif" /></a></td></tr></table></div><h2 class="sect1">5.2. Hash Element Access</h2><p><a name="INDEX-381" /> <a name="INDEX-382" />To access an element of a hash, usesyntax that looks like this:</p><blockquote><pre class="code">$hash{$some_key}</pre></blockquote><p>This is similar to what we used for array access, but here we use<a name="INDEX-383" />curly braces instead of square bracketsaround the subscript (key).<a href="#FOOTNOTE-126">[126]</a> And that key expression is now a string, rather than anumber:</p><blockquote class="footnote"> <a name="FOOTNOTE-126" /><p>[126]Here's a peek intothe mind of Larry Wall: Larry says that we use curly braces insteadof square brackets because we're doing something fancier thanordinary array access, so we should use fancier punctuation. </p></blockquote><blockquote><pre class="code">$family_name{"fred"} = "flintstone";$family_name{"barney"} = "rubble";</pre></blockquote><p><a href="ch05_02.htm#lperl3-CHP-5-FIG-2">Figure 5-2</a> shows how the resulting hash keys areassigned.</p><a name="lperl3-CHP-5-FIG-2" /><div class="figure"><img height="92" alt="Figure 5-2" src="figs/lrnp_0502.gif" width="216" /></div><h4 class="objtitle">Figure 5-2. Assigned hash keys</h4><p>This lets us use code like this:</p><blockquote><pre class="code">foreach $person (qw< barney fred >) { print "I've heard of $person $family_name{$person}.\n";}</pre></blockquote><p>The name of the <a name="INDEX-384" /><a name="INDEX-385" />hash is like any other Perl identifier(letters, digits, and underscores, but can't start with adigit). And it's from a separate namespace; that is,there's no connection between the hash element<tt class="literal">$family_name{"fred"}</tt> and a subroutine<tt class="literal">&family_name</tt>, for example. Of course,there's no reason to confuse everyone by giving everything thesame name. But Perl won't mind if you also have a scalar called<tt class="literal">$family_name</tt> and array elements like<tt class="literal">$family_name[5]</tt>. We humans will have to do as Perldoes; that is, we'll have to look to see what punctuationappears before and after the identifier to see what it means. Whenthere is a <a name="INDEX-386" />dollar sign in front of the name and<a name="INDEX-387" />curly braces afterwards, it's ahash element that's being accessed.</p><p>When choosing the name of a hash, it's often nice to think ofthe word "of" between the name of the hash and the key.As in, "the <tt class="literal">family_name</tt> of<tt class="literal">fred</tt> is<tt class="literal">flintstone</tt><a name="INDEX-388" />". So the hash is named<tt class="literal">family_name</tt>. Then it becomes clear what therelationship is between the keys and their values.</p><p>Of course, the hash key may be any expression, not just the literalstrings and simple scalar variables that we're showing here:</p><blockquote><pre class="code">$foo = "bar";print $family_name{ $foo . "ney" }; # prints "rubble"</pre></blockquote><p>When you store something into an existing hash element, thatoverwrites the previous value:</p><blockquote><pre class="code">$family_name{"fred"} = "astaire"; # gives new value to existing element$bedrock = $family_name{"fred"}; # gets "astaire"; old value is lost</pre></blockquote><p>That's analogous to what happens with arrays and scalars; ifyou store something new into <tt class="literal">$pebbles[17]</tt> or<tt class="literal">$dino</tt>, the old value is replaced. If you storesomething new into <tt class="literal">$family_name{"fred"}</tt>, the oldvalue is replaced as well.</p><p>Hash elements will spring into existence by assignment:</p><blockquote><pre class="code">$family_name{"wilma"} = "flintstone"; # adds a new key (and value)$family_name{"betty"} .= $family_name{"barney"}; # creates the element if needed</pre></blockquote><p>That's also just like what happens with arrays and scalars; ifyou didn't have <tt class="literal">$pebbles[17]</tt> or<tt class="literal">$dino</tt> before, you will have it after you assign toit. If you didn't have <tt class="literal">$family_name{"betty"}</tt>before, you do now.</p><p>And accessing outside the hash gives <tt class="literal">undef</tt>:</p><blockquote><pre class="code">$granite = $family_name{"larry"}; # No larry here: undef</pre></blockquote><p>Once again, this is just like what happens with arrays and scalars;if there's nothing yet stored in<tt class="literal">$pebbles[17]</tt> or <tt class="literal">$dino</tt>,accessing them will yield <tt class="literal">undef</tt>. If there'snothing yet stored in <tt class="literal">$family_name{"larry"}</tt>,accessing it will yield <tt class="literal">undef</tt>.</p><a name="lperl3-CHP-5-SECT-2.1" /><div class="sect2"><h3 class="sect2">5.2.1. The Hash as a Whole</h3><p>To refer to the entire hash, use the <a name="INDEX-389" />percent sign("<tt class="literal">%</tt>") as a prefix. So, the hashwe've been using for the last few pages is actually called<tt class="literal">%family_name</tt>.</p><p>For convenience, a hash may be converted into a list, and back again.Assigning to a hash (in this case, the one from <a href="ch05_01.htm#lperl3-CHP-5-FIG-1">Figure 5-1</a>) is a list-context assignment, where the listis made of key-value pairs:<a href="#FOOTNOTE-127">[127]</a></p><blockquote class="footnote"> <a name="FOOTNOTE-127" /><p>[127]Although any listexpression may be used, it must have an even number of elements,because the hash is made of key-value <em class="emphasis">pairs</em>. Anodd element will likely do something unreliable, although it'sa warnable offense.</p> </blockquote><blockquote><pre class="code">%some_hash = ("foo", 35, "bar", 12.4, 2.5, "hello", "wilma", 1.72e30, "betty", "bye\n");</pre></blockquote><p>The value of the hash (in a list context) is a simple list ofkey-value pairs:</p><blockquote><pre class="code">@any_array = %some_hash;</pre></blockquote><p>We call this<em class="firstterm">unwinding</em><a name="INDEX-390" /><a name="INDEX-391" />the hash; turning it back into a list of key-value pairs. Of course,the pairs won't necessarily be in the same order as theoriginal list:</p><blockquote><pre class="code">print "@any_array\n"; # might give something like this: # betty bye (and a newline) wilma 1.72e+30 foo 35 2.5 hello bar 12.4</pre></blockquote><p>The order is jumbled because Perl keeps the key-value pairs in anorder that's convenient for Perl, so that it can look up any
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -