📄 ch04_11.htm
字号:
<html><head><title>The return Operator (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="ch04_10.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="ch04_12.htm"><img alt="Next" border="0" src="../gifs/txtnexta.gif" /></a></td></tr></table></div><h2 class="sect1">4.11. The return Operator</h2><p><a name="INDEX-362" />The <tt class="literal">return</tt> operatorimmediately returns a value from a subroutine:</p><blockquote><pre class="code">my @names = qw/ fred barney betty dino wilma pebbles bamm-bamm /;my $result = &which_element_is("dino", @names);sub which_element_is { my($what, @list) = @_; foreach (0..$#list) { # indices of @list's elements if ($what eq $list[$_]) { return $_; # return early once found } } -1; # element not found (return is optional here)}</pre></blockquote><p>This subroutine is being used to find the index of"<tt class="literal">dino</tt>" in the array<tt class="literal">@names</tt>. First, the <tt class="literal">my</tt>declaration names the parameters: there's<tt class="literal">$what</tt>, which is what we're searching for,and <tt class="literal">@list</tt>, a list of values to search within.That's a copy of the array <tt class="literal">@names</tt>, in thiscase. The <tt class="literal">foreach</tt> loop steps through the indicesof <tt class="literal">@list</tt> (the first index is <tt class="literal">0</tt>,and the last one is <tt class="literal">$#list</tt>, as we saw in <a href="ch03_01.htm">Chapter 3, "Lists and Arrays "</a>). </p><p>Each time through the <tt class="literal">foreach</tt> loop, we check tosee whether the string in <tt class="literal">$what</tt> is equal<a href="#FOOTNOTE-118">[118]</a> to theelement from <tt class="literal">@list</tt> at the current index. Ifit's equal, we return that index at once. This is the mostcommon use of the keyword <tt class="literal">return</tt> in Perl -- toreturn a value immediately, without executing the rest of thesubroutine.</p><blockquote class="footnote"><a name="FOOTNOTE-118" /><p>[118]You noticed that we used the string equality test,<tt class="literal">eq</tt>, instead of the numeric equality test,<tt class="literal">==</tt>, didn't you?</p> </blockquote><p>But what if we never found that element? In that case, the author ofthis subroutine has chosen to return <tt class="literal">-1</tt> as a"value not found" code. It would be more Perlish,perhaps, to return <tt class="literal">undef</tt> in that case, but thisprogrammer used <tt class="literal">-1</tt>. Saying <tt class="literal">return-1</tt> on that last line would be correct, but the word<tt class="literal">return</tt> isn't really needed.</p><p>Some programmers like to use <tt class="literal">return</tt> every timethere's a return value, as a means of documenting that it is areturn value. For example, you might use <tt class="literal">return</tt>when the return value is not the last line of the subroutine, such asin the subroutine <tt class="literal">&list_from_fred_to_barney</tt>,earlier in this chapter. It's not really needed, but itdoesn't hurt anything. However, many Perl programmers believeit's just an extra seven characters of typing. So you'llneed to be able to read code written by both kinds of programmers.</p><p>If <tt class="literal">return</tt> is used with no expression, that willreturn an empty value -- <tt class="literal">undef</tt> in a scalarcontext, or an empty list in a list context. <tt class="literal">return ()</tt> does the same, in case you want to be explicit.</p><a name="lperl3-CHP-4-SECT-11.1" /><div class="sect2"><h3 class="sect2">4.11.1. Omitting the Ampersand</h3><p>As promised, now we'll tell you the rule for when a subroutinecall can omit the <a name="INDEX-363" /> <a name="INDEX-364" />ampersand.If the compiler sees the subroutine definition before invocation, orif Perl can tell from the syntax that it's a subroutine call,the subroutine can be called without an ampersand, just like abuiltin function. (But there's a catch hidden in that rule, aswe'll see in a moment.)</p><p>This means that if Perl can see that it's a subroutine callwithout the ampersand, from the syntax alone, that's generallyfine. That is, if you've got the parameter list in parentheses,it's got to be a function<a href="#FOOTNOTE-119">[119]</a> call:</p><blockquote class="footnote"> <a name="FOOTNOTE-119" /><p>[119]In this case, thefunction is the subroutine <tt class="literal">&shuffle</tt>. But itmay be a built-in function, as we'll see in a moment.</p></blockquote><blockquote><pre class="code">my @cards = shuffle(@deck_of_cards); # No & necessary on &shuffle</pre></blockquote><p>Or if Perl's internal compiler has already seen the subroutinedefinition, that's generally okay, too; in that case, you caneven omit the parentheses around the argument list:</p><blockquote><pre class="code">sub division { $_[0] / $_[1]; # Divide first param by second}my $quotient = division 355, 113; # Uses &division</pre></blockquote><p>This works because of the rule that parentheses may always beomitted, except when doing so would change the meaning of the code.</p><p>But don't put that subroutine declaration<em class="emphasis">after</em> the invocation, or the compilerwon't know what the attempted invocation of<tt class="literal">division</tt> is all about. The compiler has to see thedefinition before the invocation in order to use the subroutine callas if it were a builtin.</p><p>That's not the catch, though. The catch is this: if thesubroutine has the same name as a Perl builtin, you<em class="emphasis">must</em> use the ampersand to call it. With anampersand, you're sure to call the subroutine; without it, youcan get the subroutine <em class="emphasis">only</em> if there's nobuiltin with the same name:</p><blockquote><pre class="code">sub chomp { print "Munch, munch!";}&chomp; # That ampersand is not optional!</pre></blockquote><p>Without the ampersand, we'd be calling the builtin<tt class="literal">chomp</tt>, even though we've defined thesubroutine <tt class="literal">&chomp</tt>. So, the real rule to use isthis one: until you know the names of all of Perl's builtin<a name="INDEX-365" /> <a name="INDEX-366" />functions, <em class="emphasis">always</em> usethe ampersand on function calls. That means that you will use it foryour first hundred programs or so. But when you see someone else hasomitted the ampersand in their own code, it's not necessarily amistake; perhaps they simply know that Perl has no builtin with thatname.<a href="#FOOTNOTE-120">[120]</a></p><blockquote class="footnote"> <a name="FOOTNOTE-120" /><p>[120]Then again, maybe it <em class="emphasis">is</em> amistake; you can search the <tt class="literal">perlfunc</tt> and<tt class="literal">perlop</tt> manpages for that name, though, to seewhether it's the same as a builtin. And Perl will usually beable to warn you about this, when you have warnings turned on.</p></blockquote><p>When programmers plan to call their subroutines as if they werecalling Perl's builtins, often when writing<em class="firstterm">modules</em><a name="INDEX-367" />,they often use<em class="firstterm">prototypes</em><a name="INDEX-368" />to tell Perl about the parameters to expect. Making modules is anadvanced topic, though; when you're ready for that, seePerl's documentation (in particular, the<em class="emphasis">perlmod</em> and <em class="emphasis">perlsub</em>documents) for more information about subroutine prototypes andmaking modules.<a name="INDEX-369" /> </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_10.htm"><img alt="Previous" border="0" src="../gifs/txtpreva.gif" /></a></td><td align="center" valign="top" width="228"><a href="index.htm"><img alt="Home" border="0" src="../gifs/txthome.gif" /></a></td><td align="right" valign="top" width="228"><a href="ch04_12.htm"><img alt="Next" border="0" src="../gifs/txtnexta.gif" /></a></td></tr><tr><td align="left" valign="top" width="228">4.10. The use strict Pragma</td><td align="center" valign="top" width="228"><a href="index/index.htm"><img alt="Book Index" border="0" src="../gifs/index.gif" /></a></td><td align="right" valign="top" width="228">4.12. Exercises</td></tr></table></div><hr width="684" align="left" /><img alt="Library Navigation Links" border="0" src="../gifs/navbar.gif" usemap="#library-map" /><p><p><font size="-1"><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 + -