📄 ch10_02.htm
字号:
<HTML><HEAD><TITLE>Recipe 10.1. Accessing Subroutine Arguments (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:39:35Z"><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="ch10_01.htm"TITLE="10. Subroutines"><LINKREL="prev"HREF="ch10_01.htm"TITLE="10.0. Introduction"><LINKREL="next"HREF="ch10_03.htm"TITLE="10.2. Making Variables Private to a Function"></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="ch10_01.htm"TITLE="10.0. Introduction"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 10.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="ch10_01.htm"TITLE="10. Subroutines"></A></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch10_03.htm"TITLE="10.2. Making Variables Private to a Function"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 10.2. Making Variables Private to a Function"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch10-35380">10.1. Accessing Subroutine Arguments</A></H2><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch10-pgfId-74">Problem<ACLASS="indexterm"NAME="ch10-idx-1000004632-0"></A><ACLASS="indexterm"NAME="ch10-idx-1000004632-1"></A></A></H3><PCLASS="para">You have written a function and want to use the arguments supplied by its caller.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch10-pgfId-80">Solution</A></H3><PCLASS="para">All values passed as arguments to a function are in the special array <CODECLASS="literal">@_</CODE><ACLASS="indexterm"NAME="ch10-idx-1000004633-0"></A>. Thus, the first argument to the function is in <CODECLASS="literal">$_[0]</CODE>, the second is in <CODECLASS="literal">$_[1]</CODE>, and so on. The number of arguments is therefore <CODECLASS="literal">scalar(@_)</CODE>.</P><PCLASS="para">For example:</P><PRECLASS="programlisting">sub hypotenuse { return sqrt( ($_[0] ** 2) + ($_[1] ** 2) );}$diag = hypotenuse(3,4); # $diag is 5</PRE><PCLASS="para">Your subroutines will almost always start by copying arguments into named private variables for safer and more convenient access:</P><PRECLASS="programlisting">sub hypotenuse { my ($side1, $side2) = @_; return sqrt( ($side1 ** 2) + ($side2 ** 2) );}</PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch10-pgfId-108">Discussion</A></H3><PCLASS="para">It's been said that programming has only three nice numbers: zero, one, and however many you please. Perl's subroutine mechanism was designed to facilitate writing functions with as many - or as few - elements in the parameter and return lists as you wish. All incoming parameters appear as separate scalar values in the special array <CODECLASS="literal">@_</CODE> , which is automatically local to each function (see <ACLASS="xref"HREF="ch10_14.htm"TITLE="Saving Global Values">Recipe 10.13</A>). To return a value from a subroutine, use the <CODECLASS="literal">return</CODE> statement with an argument. If there is no <CODECLASS="literal">return</CODE> statement, the return value is the result of the last evaluated expression.</P><PCLASS="para">Here are some sample calls to the <CODECLASS="literal">hypotenuse</CODE> function defined in the Solution:</P><PRECLASS="programlisting">print hypotenuse(3, 4), "\n"; # prints 5@a = (3, 4);print hypotenuse(@a), "\n"; # prints 5</PRE><PCLASS="para">If you look at the arguments used in the second call to <CODECLASS="literal">hypotenuse</CODE>, it might appear that only one argument was passed: the array <CODECLASS="literal">@a</CODE>. This isn't what happens - the elements of <CODECLASS="literal">@a</CODE> are copied into the <CODECLASS="literal">@_</CODE> array separately. Similarly, if we called a function with <CODECLASS="literal">(@a,</CODE> <CODECLASS="literal">@b)</CODE>, we'd be giving it all the arguments in both arrays. This is the same principle of flattened lists at work as when we say:</P><PRECLASS="programlisting">@both = (@men, @women);</PRE><PCLASS="para">The scalars in <CODECLASS="literal">@_</CODE> are implicit aliases for the ones passed in, not copies. That means changing the elements of <CODECLASS="literal">@_</CODE> in a subroutine changes the values in the subroutine's caller. This is a holdover from before Perl had proper references.</P><PCLASS="para">So, we can write functions that leave their arguments intact, by copying the arguments to private variables like this:</P><PRECLASS="programlisting">@nums = (1.4, 3.5, 6.7);@ints = int_all(@nums); # @nums unchangedsub int_all { my @retlist = @_; # make safe copy for return for my $n (@retlist) { $n = int($n) } return @retlist;} </PRE><PCLASS="para">We can also write functions that change their caller's variables:</P><PRECLASS="programlisting">@nums = (1.4, 3.5, 6.7);trunc_em(@nums); # @nums now (1,3,6)sub trunc_em { for (@_) { $_ = int($_) } # truncate each argument} </PRE><PCLASS="para">Don't pass constants to this kind of function, as in <CODECLASS="literal">trunc_em(1.4,</CODE> <CODECLASS="literal">3.5,</CODE> <CODECLASS="literal">6.7)</CODE>. If you try, you'll get a run-time exception saying <CODECLASS="literal">Modification</CODE> <CODECLASS="literal">of</CODE> <CODECLASS="literal">a</CODE> <CODECLASS="literal">read-only</CODE> <CODECLASS="literal">value</CODE> <CODECLASS="literal">attempted</CODE> <CODECLASS="literal">at</CODE> <CODECLASS="literal">...</CODE>.</P><PCLASS="para">The built-in functions <CODECLASS="literal">chop</CODE> and <CODECLASS="literal">chomp</CODE> work like this, modifying their caller's variables and returning the character(s) removed. People are used to such functions returning the changed values, so they often write things like:</P><PRECLASS="programlisting">$line = chomp(<>); # WRONG</PRE><PCLASS="para">until they get the hang of how it works. Given this vast potential for confusion, you might want to think twice before modifying <CODECLASS="literal">@</CODE>_ in your <CODECLASS="literal"></CODE><ACLASS="indexterm"NAME="ch10-idx-1000004644-0"></A>subroutines.<ACLASS="indexterm"NAME="ch10-idx-1000004635-0"></A><ACLASS="indexterm"NAME="ch10-idx-1000004635-1"></A></P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch10-pgfId-168">See Also</A></H3><PCLASS="para">The section on <ACLASS="olink"HREF="../prog/ch02_07.htm">"Subroutines"</A> in <ACLASS="olink"HREF="../prog/ch02_01.htm">Chapter 2</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A> and <ICLASS="filename">perlsub </I>(1)</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="ch10_01.htm"TITLE="10.0. Introduction"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 10.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="ch10_03.htm"TITLE="10.2. Making Variables Private to a Function"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 10.2. Making Variables Private to a Function"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">10.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">10.2. Making Variables Private to a Function</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 + -