📄 ch11_02.htm
字号:
<HTML><HEAD><TITLE>Recipe 11.1. Taking References to Arrays (Perl Cookbook)</TITLE><METANAME="DC.title"CONTENT="Perl Cookbook"><METANAME="DC.creator"CONTENT="Tom Christiansen & Nathan Torkington"><METANAME="DC.publisher"CONTENT="O'Reilly & Associates, Inc."><METANAME="DC.date"CONTENT="1999-07-02T01:40:30Z"><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_01.htm"TITLE="11.0. Introduction"><LINKREL="next"HREF="ch11_03.htm"TITLE="11.2. Making Hashes of Arrays"></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_01.htm"TITLE="11.0. Introduction"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 11.0. Introduction"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_03.htm"TITLE="11.2. Making Hashes of Arrays"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 11.2. Making Hashes of Arrays"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch11-71785">11.1. Taking References to Arrays</A></H2><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch11-pgfId-190">Problem<ACLASS="indexterm"NAME="ch11-idx-1000004792-0"></A><ACLASS="indexterm"NAME="ch11-idx-1000004792-1"></A></A></H3><PCLASS="para">You need to manipulate an array by reference.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch11-pgfId-196">Solution</A></H3><PCLASS="para">To get a reference to an array:</P><PRECLASS="programlisting">$aref = \@array;$anon_array = [1, 3, 5, 7, 9];$anon_copy = [ @array ];@$implicit_creation = (2, 4, 6, 8, 10);</PRE><PCLASS="para">To deference an array reference, precede it with an at sign (<CODECLASS="literal">@</CODE>):</P><PRECLASS="programlisting">push(@$anon_array, 11);</PRE><PCLASS="para">Or use a pointer arrow plus a bracketed subscript for a particular element:</P><PRECLASS="programlisting">$two = $implicit_creation->[0];</PRE><PCLASS="para">To get the last index number by reference, or the number of items in that referenced array:</P><PRECLASS="programlisting">$last_idx = $#$aref;$num_items = @$aref;</PRE><PCLASS="para">Or defensively embracing and forcing context:</P><PRECLASS="programlisting">$last_idx = $#{ $aref };$num_items = scalar @{ $aref };</PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch11-pgfId-224">Discussion</A></H3><PCLASS="para">Here are array references in action:</P><PRECLASS="programlisting"># check whether $someref contains a simple array referenceif (ref($someref) ne 'ARRAY') { die "Expected an array reference, not $someref\n";}print "@{$array_ref}\n"; # print original data@order = sort @{ $array_ref }; # sort itpush @{ $array_ref }, $item; # append new element to orig array </PRE><PCLASS="para">If you can't decide whether to use a reference to a named array or to create a new one, here's a simplistic guideline that will prove right more often than not. Only take a reference to an existing array either to return the reference out of scope, thereby creating an anonymous array, or to pass the array by reference to a function. For virtually all other cases, use <CODECLASS="literal">[@array]</CODE> to create a new array reference with a copy of the old values.</P><PCLASS="para">Automatic reference counting and the backslash operator make a powerful combination:</P><PRECLASS="programlisting">sub array_ref { my @array; return \@array;}$aref1 = array_ref();$aref2 = array_ref();</PRE><PCLASS="para">Each time <CODECLASS="literal">array_ref</CODE> is called, the function allocates a new piece of memory for <CODECLASS="literal">@array</CODE>. If we hadn't returned a reference to <CODECLASS="literal">@array</CODE>, its memory would have been freed when its block, the subroutine, ended. However, because a reference to <CODECLASS="literal">@array</CODE> is still accessible, Perl doesn't free that storage, and we end up with a reference to a piece of memory that can no longer be accessed through the symbol table. Such a piece of memory is called <ICLASS="firstterm">anonymous</I> because no name is associated with it.</P><PCLASS="para">To access a particular element of the array referenced by <CODECLASS="literal">$aref</CODE>, you could write <CODECLASS="literal">$$aref[4]</CODE>, but writing <CODECLASS="literal">$aref->[4]</CODE> is the same thing, and it is clearer.</P><PRECLASS="programlisting">print $array_ref->[$N]; # access item in position N (best)print $$array_ref[$N]; # same, but confusingprint ${$array_ref}[$N]; # same, but still confusing, and ugly to boot</PRE><PCLASS="para">If you have an array reference, you can only access a slice of the referenced array in this way:</P><PRECLASS="programlisting">@$pie[3..5]; # array slice, but a little confusing to read@{$pie}[3..5]; # array slice, easier (?) to read</PRE><PCLASS="para">Array slices, even when accessed through array references, are assignable. In the next line, the array dereference happens first, and then the slice:</P><PRECLASS="programlisting">@{$pie}[3..5] = ("blackberry", "blueberry", "pumpkin");</PRE><PCLASS="para">An array slice is exactly the same as a list of individual array elements. Because you can't take a reference to a list, you can't take a reference to an array slice:</P><PRECLASS="programlisting">$sliceref = \@{$pie}[3..5]; # WRONG!</PRE><PCLASS="para">To iterate through the entire array, use either a <CODECLASS="literal">foreach</CODE> loop or a <CODECLASS="literal">for</CODE> loop:</P><PRECLASS="programlisting">foreach $item ( @{$array_ref} ) { # $item has data}for ($idx = 0; $idx <= $#{ $array_ref }; $idx++) { # $array_ref->[$idx] has data}<ACLASS="indexterm"NAME="ch11-idx-1000004794-0"></A><ACLASS="indexterm"NAME="ch11-idx-1000004794-1"></A></PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch11-pgfId-1000004675">See Also</A></H3><PCLASS="para"><ACLASS="olink"HREF="../prog/ch04_01.htm">Chapter 4</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A>; <ICLASS="filename">perlref </I>(1) and <ICLASS="filename">perllol </I>(1); <ACLASS="xref"HREF="ch02_15.htm"TITLE="Multiplying Matrices">Recipe 2.14</A>; <ACLASS="xref"HREF="ch04_06.htm"TITLE="Iterating Over an Array by Reference">Recipe 4.5</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_01.htm"TITLE="11.0. Introduction"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 11.0. Introduction"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_03.htm"TITLE="11.2. Making Hashes of Arrays"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 11.2. Making Hashes of Arrays"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">11.0. Introduction</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.2. Making Hashes of Arrays</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 © 2002</a> O'Reilly & 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 + -