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

📄 ch08_02.htm

📁 编程珍珠,里面很多好用的代码,大家可以参考学习呵呵,
💻 HTM
📖 第 1 页 / 共 2 页
字号:
<html><head><title>Creating References (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="Creating References"><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="ch08_01.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="ch08_01.htm">Chapter 8: References</a></td><td align="right" valign="top" width="172"><a href="ch08_03.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">8.2. Creating References</h2><p><a name="INDEX-1974"></a><a name="INDEX-1975"></a>There are several ways to create references, most of which we willdescribe before explaining how to use (dereference) the resultingreferences.</p><a name="ch08-sect-bo"></a><h3 class="sect2">8.2.1. The Backslash Operator</h3><a name="INDEX-1976"></a><p><a name="INDEX-1977"></a>You can create a reference to any named variable or subroutine with abackslash.  (You may also use it on an anonymous scalar value like<tt class="literal">7</tt> or <tt class="literal">"camel"</tt>, although you won'toften need to.)  This operator works like the <tt class="literal">&amp;</tt>(address-of) operator in C--at least at first glance.</p><p>Here are some examples:<blockquote><pre class="programlisting">$scalarref = \$foo;$constref  = \186_282.42;$arrayref  = \@ARGV;$hashref   = \%ENV;$coderef   = \&amp;handler;$globref   = \*STDOUT;</pre></blockquote>The backslash operator can do more than produce a single reference.It will generate a whole list of references if applied to a list.See the section <a href="ch08_03.htm#ch08-sect-tricks">Section 8.3.6, "Other Tricks You Can Do with Hard References"</a> for details.</p><h3 class="sect2">8.2.2. Anonymous Data</h3><a name="INDEX-1978"></a><a name="INDEX-1979"></a><p>In the examples just shown, the backslash operator merely makes aduplicate of a reference that is already held in a variable name--withone exception.  The <tt class="literal">186_282.42</tt> isn't referenced by a namedvariable--it's just a value.  It's one of those <em class="emphasis">anonymous</em> referentswe mentioned earlier.  Anonymous referents are accessed only throughreferences.  This one happens to be a number, but you can createanonymous arrays, hashes, and subroutines as well.</p><h3 class="sect3">8.2.2.1. The anonymous array composer</h3><p><a name="INDEX-1980"></a><a name="INDEX-1981"></a><a name="INDEX-1982"></a>You can create a reference to an anonymous array with square brackets:<blockquote><pre class="programlisting">$arrayref = [1, 2, ['a', 'b', 'c', 'd']];</pre></blockquote>Here we've composed an anonymous array of threeelements, whose final element is a reference to an anonymous array offour elements (depicted in <a href="ch08_02.htm#perl3-fig-array-of-arrays">Figure 8-2</a>).  (The multidimensional syntaxdescribed later can be used to access this.  For example, <tt class="literal">$arrayref-&gt;[2][1]</tt> would have the value "<tt class="literal">b</tt>".)</p><a name="perl3-fig-array-of-arrays"></a><div class="figure"></div><h4 class="objtitle">Figure 8.2. A reference to an array, whose third element is itself an array reference</h4><p>We now have one way to represent the table at the beginning of thechapter:<blockquote><pre class="programlisting">$table = [ [ "john", 47, "brown", 186],           [ "mary", 23, "hazel", 128],           [ "bill", 35, "blue",  157] ];</pre></blockquote>Square brackets work like this only where the Perl parser is expectinga term in an expression. They should not be confused with the bracketsin an expression like <tt class="literal">$array[6]</tt>--although themnemonic association with arrays is intentional.  Inside a quotedstring, square brackets don't compose anonymous arrays; instead, theybecome literal characters in the string.  (Square brackets do stillwork for subscripting in strings, or you wouldn't be able to printstring values like <tt class="literal">"VAL=$array[6]\n"</tt>.  And to betotally honest, you can in fact sneak anonymous array composers intostrings, but only when embedded in a larger expression that is beinginterpolated.  We'll talk about this cool feature later in the chapterbecause it involves dereferencing as well as referencing.)</p><h3 class="sect3">8.2.2.2. The anonymous hash composer</h3><p><a name="INDEX-1983"></a><a name="INDEX-1984"></a><a name="INDEX-1985"></a>You can create a reference to an anonymous hash with braces:<blockquote><pre class="programlisting">$hashref = {    'Adam'   =&gt; 'Eve',    'Clyde'  =&gt; $bonnie,    'Antony' =&gt; 'Cleo' . 'patra',};</pre></blockquote>For the values (but not the keys) of the hash, you can freely mixother anonymous array, hash, and subroutine composers to produce ascomplicated a structure as you like.</p><p>We now have another way to represent the table at the beginningof the chapter:<blockquote><pre class="programlisting">$table = {            "john" =&gt; [ 47, "brown", 186 ],            "mary" =&gt; [ 23, "hazel", 128 ],            "bill" =&gt; [ 35, "blue",  157 ],};</pre></blockquote>That's a hash of arrays.  Choosing the best data structure is a trickybusiness, and the next chapter is devoted to it.  But as a teaser, wecould even use a hash of hashes for our table:<blockquote><pre class="programlisting">$table = {           "john" =&gt; { age    =&gt; 47,                       eyes   =&gt; "brown",                       weight =&gt; 186,                     },           "mary" =&gt; { age    =&gt; 23,                       eyes   =&gt; "hazel",                       weight =&gt; 128,                     },           "bill" =&gt; { age    =&gt; 35,                       eyes   =&gt; "blue",                       weight =&gt; 157,                     }, };</pre></blockquote>As with square brackets, braces work like this only where the Perlparser is expecting a term in an expression. They should not beconfused with the braces in an expression like<tt class="literal">$hash{key}</tt>--although the mnemonic association withhashes is (again) intentional.  The same caveats apply to theuse of braces within strings.</p><p>There is one additional caveat which didn't apply to square brackets.Since braces are also used for several other things (including blocks),you may occasionally have to disambiguate braces at the beginning of astatement by putting a <tt class="literal">+</tt> or a <tt class="literal">return</tt> in front, so that Perl realizesthe opening brace isn't starting a block.  For example, if you wanta function to make a new hash and return a reference to it, you havethese options:<blockquote><pre class="programlisting">sub hashem {        { @_ } }   # Silently WRONG -- returns @_.sub hashem {       +{ @_ } }   # Ok.sub hashem { return { @_ } }   # Ok.</pre></blockquote></p><h3 class="sect3">8.2.2.3. The anonymous subroutine composer</h3><p><a name="INDEX-1986"></a><a name="INDEX-1987"></a><a name="INDEX-1988"></a>You can create a reference to an anonymous subroutine by using <tt class="literal">sub</tt>without a subroutine name:<blockquote><pre class="programlisting">$coderef = sub { print "Boink!\n" };  # Now &amp;$coderef prints "Boink!"</pre></blockquote>Note the presence of the semicolon, required here toterminate the expression.  (It isn't required after the more commonusage of <tt class="literal">sub</tt><em class="replaceable">NAME</em><tt class="literal">{}</tt> that declares and defines a named subroutine.)A nameless <tt class="literal">sub {}</tt> is not so much a declaration asit is an operator--like <tt class="literal">do {}</tt> or <tt class="literal">eval{}</tt>--except that the code inside isn't executed immediately.Instead, it just generates a reference to the code, which in ourexample is stored in <tt class="literal">$coderef</tt>.  However, no matterhow many times you execute the line shown above,<tt class="literal">$coderef</tt> will still refer to the same anonymoussubroutine.<a href="#FOOTNOTE-2">[2]</a></p><blockquote class="footnote">

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -