📄 ch29_01.htm
字号:
<html><head><title>Functions (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 & Associates, Inc."><meta name="DC.Source" content="" scheme="ISBN"><meta name="DC.Subject.Keyword" content=""><meta name="DC.Title" content="Functions"><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="ch28_02.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="part5.htm">Part 5: Reference Material</a></td><td align="right" valign="top" width="172"><a href="ch29_02.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0"></a></td></tr></table></div><hr width="515" align="left"><!-- SECTION BODY --><h1 class="chapter">Chapter 29. Functions</h1><div class="htmltoc"><h4 class="tochead">Contents:</h4><p><a href="ch29_01.htm">Perl Functions by Category</a><br><a href="ch29_02.htm">Perl Functions in Alphabetical Order</a><br></p></div><p><a name="INDEX-4604"></a><a name="INDEX-4605"></a>This chapter describes the built-in Perl functions in alphabeticalorder<a href="#FOOTNOTE-1">[1]</a> for convenient reference. Each functiondescription begins with a brief summary of the syntax for thatfunction. Parameter names like <em class="replaceable">THIS</em>represent placeholders for actual expressions, and the text followingthe syntax summary will describe the semantics of supplying (oromitting) the actual arguments.</p><blockquote class="footnote"><a name="FOOTNOTE-1"></a><p>[1] Sometimes tightly related functions are groupedtogether in the system manpages, so we respect that grouping here. Tofind the description of <tt class="literal">endpwent</tt>, for instance,you'll have to look under <tt class="literal">getpwent</tt>.</p></blockquote><p><a name="INDEX-4606"></a>You can think of functions as terms in an expression, along withliterals and variables. Or you can think of them as prefix operatorsthat process the arguments after them. We call them operators half thetime anyway.</p><p><a name="INDEX-4607"></a>Some of these operators, er, functions take a <em class="replaceable">LIST</em> as an argument.Elements of the <em class="replaceable">LIST</em> should be separated by commas (or by <tt class="literal">=></tt>,which is just a funny kind of comma). The elements of the <em class="replaceable">LIST</em> areevaluated in a list context, so each element will return either ascalar or a list value, depending on its sensitivity to list context.Each returned value, whether scalar or list, will be interpolated aspart of the overall sequence of scalar values. That is, all the listsget flattened into one list. From the viewpoint of the functionreceiving the arguments, the overall argument <em class="replaceable">LIST</em> is always asingle-dimensional list value. (To interpolate an array as a singleelement, you must explicitly create and interpolate a reference to thearray instead.)</p><p><a name="INDEX-4608"></a><a name="INDEX-4609"></a><a name="INDEX-4610"></a><a name="INDEX-4611"></a>Predefined Perl functions may be used either with or withoutparentheses around their arguments; the syntax summaries in thischapter omit the parentheses. If you do use parentheses, the simplebut occasionally surprising rule is this: if it looks like a function,then it <em class="emphasis">is</em> a function, so precedence doesn'tmatter. Otherwise, it's a list operator or unary operator, andprecedence does matter. Be careful, because even if you putwhitespace between the keyword and its left parenthesis, that doesn'tkeep it from being a function:<blockquote><pre class="programlisting">print 1+2*4; # Prints 9.print(1+2) * 4; # Prints 3!print (1+2)*4; # Also prints 3!print +(1+2)*4; # Prints 12.print ((1+2)*4); # Prints 12.</pre></blockquote><a name="INDEX-4612"></a>If you run Perl with the <tt class="userinput"><b>-w</b></tt> switch, it will warn you about this. For example, the second and third lines above producemessages like this:<blockquote><pre class="programlisting">print (...) interpreted as function at - line 2.Useless use of integer multiplication in void context at - line 2.</pre></blockquote>Given the simple definition of some functions, you have considerablelatitude in how you pass arguments. For instance, the mostcommon way to use <tt class="literal">chmod</tt> is to pass the file permissions (themode) as an initial argument:<blockquote><pre class="programlisting">chmod 0644, @array;</pre></blockquote>but the definition of <tt class="literal">chmod</tt> just says:<blockquote><pre class="programlisting">chmod <em class="replaceable">LIST</em></pre></blockquote>so you could just as well say:<blockquote><pre class="programlisting">unshift @array, 0644;chmod @array;</pre></blockquote>If the first argument of the list is not a valid mode, <tt class="literal">chmod</tt> willfail, but that's a run-time semantic problem unrelated to the syntax ofthe call. If the semantics require any special arguments to be passedfirst, the text will describe these restrictions.</p><p>In contrast to the simple <em class="replaceable">LIST</em> functions, other functions imposeadditional syntactic constraints. For instance, <tt class="literal">push</tt> has a syntaxsummary that looks like this:<blockquote><pre class="programlisting">push <em class="replaceable">ARRAY</em>, <em class="replaceable">LIST</em></pre></blockquote>This means that <tt class="literal">push</tt> requires a proper array as its first argument,but doesn't care about its subsequent arguments. That's what the<em class="replaceable">LIST</em> at the end means. (<em class="replaceable">LIST</em>s always come at the end, since theygobble up all remaining values.) Whenever a syntax summary containsany arguments before the <em class="replaceable">LIST</em>, those arguments are syntacticallydistinguished by the compiler, not just semantically distinguished bythe interpreter when it runs later. Such arguments are never evaluatedin list context. They may be evaluated in scalar context, or theymay be special referential arguments such as the array in <tt class="literal">push</tt>.(The description will tell you which is which.)</p><p><a name="INDEX-4613"></a><a name="INDEX-4614"></a><a name="INDEX-4615"></a>For those operations that are based directly on the C library'sfunctions, we do not attempt to duplicate your system's documentation.When a <tt class="literal">function</tt> description says to see<em class="emphasis">function</em>(2), that means that you shouldlook up the corresponding C version of that function to learn moreabout its semantics. The number in parentheses indicates the sectionof the system programmer's manual in which you will find the manpage,if you have the manpages installed. (And in which you won't, if youdon't.)</p><p>These manpages may document system-dependent behavior likeshadow password files, access control lists, and so forth. ManyPerl functions that derive from C library functions in Unix areemulated even on non-Unix platforms. For example, although youroperating system might not support the <em class="emphasis">flock</em>(2) or <em class="emphasis">fork</em>(2)syscalls, Perl will do its best to emulate them anyway by usingwhatever native facilities your platform provides.</p><p>Occasionally, you'll find that the documented C function has morearguments than the corresponding Perl function. Generally, the missingarguments are things that Perl knows already, such as the length of theprevious argument, so you needn't supply them in Perl. Any remainingdisparities are caused by the different ways Perl and C specifyfilehandles and success/failure values.</p><p>In general, functions in Perl that serve as wrappers for syscallsof the same name (like <em class="emphasis">chown</em>(2), <em class="emphasis">fork</em>(2), <em class="emphasis">closedir</em>(2), etc.) allreturn true when they succeed and <tt class="literal">undef</tt> otherwise, as mentionedin the descriptions that follow. This is different from the C library'sinterfaces to these operations, which all return <tt class="literal">-1</tt> on failure.Exceptions to this rule are <tt class="literal">wait</tt>, <tt class="literal">waitpid</tt>, and <tt class="literal">syscall</tt>.Syscalls also set the special <tt class="literal">$!</tt> (<tt class="literal">$OS_ERROR</tt>) variable on failure. Otherfunctions do not, except accidentally.</p><p><a name="INDEX-4616"></a><a name="INDEX-4617"></a><a name="INDEX-4618"></a>For functions that can be used in either scalar or list context,failure is generally indicated in scalar context by returning afalse value (usually <tt class="literal">undef</tt>) and in list context by returningthe null list. Successful execution is generally indicated byreturning a value that will evaluate to true (in context).</p><p>Remember the following rule: there is <em class="emphasis">no</em> rule that relates thebehavior of a function in list context to its behavior in scalarcontext, or vice versa. It might do two totally different things.</p><p>Each function knows the context in which it was called. The samefunction that returns a list when called in list context will,when called in scalar context, return whichever kind of value would be most appropriate. Some functions return thelength of the list that would have been returned in list context.Some operators return the first value in the list. Some functionsreturn the last value in the list. Some functions return the "other"value, when something can be looked up either by number or by name.Some functions return a count of successful operations. In general,Perl functions do exactly what you want, unless you want consistency.</p><p><a name="INDEX-4619"></a><a name="INDEX-4620"></a>One final note: we've tried to be very consistent in our use of theterms "byte" and "character". Historically, these terms have beenconfused with each other (and with themselves). But when we say "byte"we always mean an octet, 8 bits. When we say "character", we mean anabstract character, usually a Unicode character, which may berepresented by one or more bytes within your strings.</p><p>But notice that we said "usually". Perl purposefully confuses byteswith characters in the scope of a <tt class="literal">use bytes</tt> declaration, so wheneverwe say "character", you should take it to mean a byte in a <tt class="literal">use bytes</tt>context, and a Unicode character otherwise. In other words, <tt class="literal">use bytes</tt> just warps the definition of character back to what it was inolder versions of Perl. So, for instance, when we say that a scalar<tt class="literal">reverse</tt> reverses a string character by character, don't ask uswhether that <em class="emphasis">really</em> means characters or bytes, because the answer is,"Yes, it does."</p><h2 class="sect1">29.1. Perl Functions by Category</h2><p><a name="INDEX-4621"></a><a name="INDEX-4622"></a>Here are Perl's functions and function-like keywords, arranged bycategory. Some functions appear under more than one heading.</p><dl><dt><b>Scalar manipulation</b></dt><dd><p><a name="INDEX-"></a><tt class="literal">chomp</tt>, <tt class="literal">chop</tt>, <tt class="literal">chr</tt>, <tt class="literal">crypt</tt>, <tt class="literal">hex</tt>,<tt class="literal">index</tt>, <tt class="literal">lc</tt>, <tt class="literal">lcfirst</tt>, <tt class="literal">length</tt>, <tt class="literal">oct</tt>, <tt class="literal">ord</tt>, <tt class="literal">pack</tt>, <tt class="literal">q//</tt>, <tt class="literal">qq//</tt>, <tt class="literal">reverse</tt>, <tt class="literal">rindex</tt>,<tt class="literal">sprintf</tt>, <tt class="literal">substr</tt>, <tt class="literal">tr///</tt>,<tt class="literal">uc</tt>, <tt class="literal">ucfirst</tt>, <tt class="literal">y///</tt></p></dd>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -