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

📄 ch04_07.htm

📁 by Randal L. Schwartz and Tom Phoenix ISBN 0-596-00132-0 Third Edition, published July 2001. (See
💻 HTM
字号:
<html><head><title>Subroutines (Perl in a Nutshell, 2nd Edition)</title><link rel="stylesheet" type="text/css" href="../style/style1.css" /><meta name="DC.Creator" content="Stephen Spainhour" /><meta name="DC.Format" content="text/xml" scheme="MIME" /><meta name="DC.Language" content="en-US" /><meta name="DC.Publisher" content="O'Reilly &amp; Associates, Inc." /><meta name="DC.Source" scheme="ISBN" content="0596002416L" /><meta name="DC.Subject.Keyword" content="stuff" /><meta name="DC.Title" content="Perl in a Nutshell, 2nd Edition" /><meta name="DC.Type" content="Text.Monograph" /></head><body bgcolor="#ffffff"><img src="gifs/smbanner.gif" usemap="#banner-map" border="0" alt="Book Home" /><map name="banner-map"><area shape="rect" coords="1,-2,616,66" href="index.htm" alt="Java and XSLT" /><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="ch04_06.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0" /></a></td><td align="center" valign="top" width="228" /><td align="right" valign="top" width="228"><a href="ch04_08.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0" /></a></td></tr></table></div><h2 class="sect1">4.7. Subroutines</h2><p><a name="INDEX-704" /><a name="INDEX-705" /><a name="INDEX-706" />Subroutines are declared using one ofthese forms:</p><blockquote><pre class="code">sub <em class="replaceable"><tt>name</em> {<em class="replaceable">block</tt></em>}sub <em class="replaceable"><tt>name</em> (<em class="replaceable">proto</em>) {<em class="replaceable">block</tt></em>}</pre></blockquote><p><a name="INDEX-707" />Prototypes allow you to putconstraints on the arguments you provide to your subroutines.</p><p><a name="INDEX-708" />Youcan also create anonymous subroutines at runtime, which will beavailable for use through a reference:</p><blockquote><pre class="code">$<em class="replaceable"><tt>subref</em> = sub {<em class="replaceable">block</tt></em>};</pre></blockquote><a name="perlnut2-CHP-4-SECT-7.1" /><div class="sect2"><h3 class="sect2">4.7.1. Calling Subroutines</h3><p><a name="INDEX-709" /><a name="INDEX-710" />The ampersand(<tt class="literal">&amp;</tt>) is the identifier used to callsubroutines. Most of the time, however, subroutines can be used in anexpression just like built-in functions. To call subroutinesdirectly:</p><blockquote><pre class="code"><em class="replaceable"><tt>name</em>(<em class="replaceable">args</tt></em>);        # &amp; is optional with parentheses<em class="replaceable"><tt>name</em> <em class="replaceable">args</tt></em>;         # Parens optional if predeclared/imported&amp;<em class="replaceable"><tt>name;</tt></em>             # Passes current @_ to subroutine</pre></blockquote><p>To call subroutines indirectly (by name or by reference): </p><blockquote><pre class="code">&amp;$subref(<em class="replaceable"><tt>args</tt></em>);    # &amp; is not optional on indirect call&amp;$subref;          # Passes current @_ to subroutine</pre></blockquote></div><a name="perlnut2-CHP-4-SECT-7.2" /><div class="sect2"><h3 class="sect2">4.7.2. Passing Arguments</h3><p><a name="INDEX-711" /><a name="INDEX-712" /><a name="INDEX-713" />All arguments to asubroutine are passed as a single, flat list of scalars, and returnvalues are returned the same way. Any arrays or hashes passed inthese lists will have their values interpolated into the flattenedlist.</p><p><a name="INDEX-714" /><a name="INDEX-715" />Any arguments passed to a subroutinecome in as the array <tt class="literal">@_</tt>.</p><p><a name="INDEX-716" />You may usethe explicit <tt class="literal">return</tt> statement to return a valueand leave the subroutine at any point.</p></div><a name="perlnut2-CHP-4-SECT-7.3" /><div class="sect2"><h3 class="sect2">4.7.3. Passing References</h3><p><a name="INDEX-717" /><a name="INDEX-718" />If you want to passmore than one array or hash into or out of a function and maintaintheir integrity, you should pass references as arguments. Thesimplest way to do this is to take your named variables and put abackslash in front of them in the argument list:</p><blockquote><pre class="code">@returnlist = ref_conversion(\@<em class="replaceable"><tt>temps1, </em>\@<em class="replaceable">temps2, </em>\@<em class="replaceable">temps3</tt></em>);</pre></blockquote><p>This sends references to the three arrays to the subroutine (andsaves you the step of creating your own named references to send tothe function). The references to the arrays are passed to thesubroutine as the three-member <tt class="literal">@_</tt> array. Thesubroutine will have to dereference the arguments so that the datavalues may be used.</p><p>Returning references is a simple matter of returning scalars that arereferences. This way, you can return distinct hashes and arrays.</p></div><a name="perlnut2-CHP-4-SECT-7.4" /><div class="sect2"><h3 class="sect2">4.7.4. Private and Local Variables</h3><p><a name="INDEX-719" /><a name="INDEX-720" /><a name="INDEX-721" /><a name="INDEX-722" /><a name="INDEX-723" /><a name="INDEX-724" />Any variables you use in thefunction that aren't declared private are globalvariables. In subroutines, you'll often want to usevariables that won't be used anywhere else in yourprogram, and you don't want them taking up memorywhen the subroutine is not being executed. You also might not want toalter variables in subroutines that might have the same name asglobal variables.</p><p><a name="INDEX-725" /><a name="INDEX-726" />The <tt class="literal">my</tt> functiondeclares variables that are <em class="emphasis">lexically scoped</em>within the subroutine. Lexically scoped variables are privatevariables that exist only within the block or subroutine in whichthey are declared. Outside of their scope, they are invisible andcan't be altered in any way.</p><p>To scope multiple variables at once, use a list in parentheses. Youcan also assign a variable in a <tt class="literal">my</tt> statement:</p><blockquote><pre class="code">my @list = (44, 55, 66);my $cd = "orb";</pre></blockquote><p><a name="INDEX-727" />Dynamicvariables are visible to other subroutines called from within theirscope, are defined with <tt class="literal">local</tt>, and are not privatevariables but global variables with temporary values. When asubroutine is executed, the global value is hidden away, and thelocal value is used. Once the scope is exited, the original globalvalue is used. Most of the time, you will want to use<tt class="literal">my</tt> to localize parameters in a subroutine.</p></div><a name="perlnut2-CHP-4-SECT-7.5" /><div class="sect2"><h3 class="sect2">4.7.5. Prototypes</h3><p><a name="INDEX-728" /><a name="INDEX-729" /><a name="INDEX-730" /><a name="INDEX-731" /><a name="INDEX-732" /><a name="INDEX-733" /><a name="INDEX-734" /><a name="INDEX-735" /><a name="INDEX-736" /><a name="INDEX-737" /><a name="INDEX-738" />Prototypes allow you to design yoursubroutines to take arguments with constraints on the number ofparameters and types of data. To declare a function with prototypes,use the prototype symbols in the declaration line like this:</p><blockquote><pre class="code">sub addem ($$) {...}</pre></blockquote><p>In this case, the function expects two scalar arguments. Thefollowing table gives the various prototypesymbols<a name="INDEX-739" /><a name="INDEX-740" /><a name="INDEX-741" />:</p><a name="ch04-16-fm2xml" /><table border="1" cellpadding="3"><tr><th><p>Symbol</p></th><th><p>Meaning</p></th></tr><tr><td><p><tt class="literal">$</tt></p></td><td><p>Scalar</p></td></tr><tr><td><p><tt class="literal">@</tt></p></td><td><p>List</p></td></tr><tr><td><p><tt class="literal">%</tt></p></td><td><p>Hash</p></td></tr><tr><td><p><tt class="literal">&amp;</tt></p></td><td><p>Anonymous subroutine</p></td></tr><tr><td><p><tt class="literal">*</tt></p></td><td><p>Typeglob</p></td></tr></table><p><p>A backslash placed before one of these symbols forces the argument tobe that exact variable type. For instance, a function that requires ahash variable would be declared like this:</p><blockquote><pre class="code">sub hashfunc (\%);</pre></blockquote><p>Unbackslashed <tt class="literal">@</tt> or <tt class="literal">%</tt> symbolsact exactly alike and will eat up all remaining arguments, forcinglist context. Likewise, a <tt class="literal">$</tt> forces scalar contexton an argument, so taking an array or hash variable for thatparameter would probably yield unwanted results.</p><p><a name="INDEX-742" /><a name="INDEX-743" />Asemicolon separates mandatory arguments from optional arguments. Forexample:</p><blockquote><pre class="code">sub newsplit (\@$;$);</pre></blockquote><p>requires two arguments: an array variable and a scalar. The thirdscalar is optional. Placing a semicolon before <tt class="literal">@</tt>and <tt class="literal">%</tt> is not necessary since lists can be null.</p><p><a name="INDEX-744" />A typeglob prototype symbol(<tt class="literal">*</tt>) will always turn its argument into a referenceto a symbol table entry. It is most often used for filehandles.</p></div><hr width="684" align="left" /><div class="navbar"><table width="684" border="0"><tr><td align="left" valign="top" width="228"><a href="ch04_06.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0" /></a></td><td align="center" valign="top" width="228"><a href="index.htm"><img src="../gifs/txthome.gif" alt="Home" border="0" /></a></td><td align="right" valign="top" width="228"><a href="ch04_08.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0" /></a></td></tr><tr><td align="left" valign="top" width="228">4.6. Regular Expressions</td><td align="center" valign="top" width="228"><a href="index/index.htm"><img src="../gifs/index.gif" alt="Book Index" border="0" /></a></td><td align="right" valign="top" width="228">4.8. References and Complex Data Structures</td></tr></table></div><hr width="684" align="left" /><img src="../gifs/navbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links" /><p><p><font size="-1"><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 + -