📄 ch5.htm
字号:
and </I><TT><I>@array</I></TT><I>.<BR>Print </I><TT><I>@array</I></TT><I>and </I><TT><I>$firstVar</I></TT><I>.</I></BLOCKQUOTE><BLOCKQUOTE><PRE>firstSub("AAAA", (0..10));sub firstSub{ local($firstVar, @array) = @_ ; print("firstSub: array = @array\n"); print("firstSub: firstVar = $firstVar\n");}</PRE></BLOCKQUOTE><P>This program prints:<BLOCKQUOTE><PRE>firstSub: array = 0 1 2 3 4 5 6 7 8 9 10firstSub: firstVar = AAAA<BR></PRE></BLOCKQUOTE><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD><B>Note</B></TD></TR><TR><TD><BLOCKQUOTE>You can pass as many scalar values as you want to a fuNCtion, but only one array. If you try to pass more than one array, the array elements become joined together and passed as one array to the fuNCtion. Your fuNCtion won't be able to tell when one array starts and another ends.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H3><A NAME="ExampleNestingFuNCtionCalls">Example: Nesting FuNCtion Calls</A></H3><P>FuNCtion calls can be nested many levels deep. Nested fuNCtioncalls simply means that one fuNCtion can call another which inturn can call another. Exactly how many levels you can nest dependson which version of Perl you are running and how your machineis configured. Normally, you don't have to worry about it. Ifyou want to see how many levels your system can recurse, try thefollowing small program:<P><IMG SRC="pseudo.gif" BORDER=1 ALIGN=RIGHT><p><BLOCKQUOTE><I>Call the </I><TT><I>firstSub()</I></TT><I>fuNCtion.<BR>Define the </I><TT><I>firstSub()</I></TT><I>fuNCtion.<BR>Print </I><TT><I>$count<BR></I></TT><I>INCrement </I><TT><I>$count</I></TT><I>by one.<BR>Call the </I><TT><I>firstSub()</I></TT><I>fuNCtion recursively.</I></BLOCKQUOTE><BLOCKQUOTE><PRE>firstSub();sub firstSub{ print("$count\n"); $count++; firstSub();}</PRE></BLOCKQUOTE><P>My system counts up to 127 before displaying the following message:<BLOCKQUOTE><PRE>Error: Runtime exception</PRE></BLOCKQUOTE><P>While it is important to realize that there is a limit to thenumber of times your program can nest fuNCtions, you should neverrun into this limitation unless you are working with recursivemathematical fuNCtions.<H3><A NAME="ExampleUsingaPrivateFuNCtion">Example: Using a Private FuNCtion</A></H3><P>Occasionally, you might want to create a private fuNCtion. A privatefuNCtion is one that is only available inside the scope whereit was defined.<P><IMG SRC="pseudo.gif" BORDER=1 ALIGN=RIGHT><p><BLOCKQUOTE><I>Assign the return value from </I><TT><I>performCalc()</I></TT><I>to </I><TT><I>$temp</I></TT><I>.<BR>Print </I><TT><I>$temp</I></TT><I>.<BR>Define the </I><TT><I>performCalc()</I></TT><I>fuNCtion.<BR>Assign my scalar variables values from the </I><TT><I>@_</I></TT><I>parameter array.<BR>Define the private fuNCtion referred to by </I><TT><I>$square</I></TT><I>.<BR>Return the first element of the </I><TT><I>@_</I></TT><I>parameter array raised to the 2nd power.<BR>Return the value of </I><TT><I>$firstVar</I></TT><I>raised to the 2nd power and<BR></I><TT><I>$secondVar</I></TT><I>raised to the 2nd power.</I></BLOCKQUOTE><BLOCKQUOTE><PRE>$temp = performCalc(10, 10);print("temp = $temp\n");sub performCalc { my ($firstVar, $secondVar) = @_; my $square = sub { return($_[0] ** 2); }; return(&$square($firstVar) + &$square($secondVar));};</PRE></BLOCKQUOTE><P>This program prints:<BLOCKQUOTE><PRE>temp = 200</PRE></BLOCKQUOTE><P>This example is rather trivial, but it serves to show that inPerl it pays to create little helper routines. A fine line needsto be drawn between what should be iNCluded as a private fuNCtionand what shouldn't. I would draw the line at 5 or 6 lines of code.Anything longer probably should be made into its own fuNCtion.I would also say that a private fuNCtion should have only onepurpose for existeNCe. Performing a calculation and then openinga file is too much fuNCtionality for a single private fuNCtionto have.<P>The rest of the chapter is devoted to showing you some of thebuilt-in fuNCtions of Perl. These little nuggets of fuNCtionalitywill become part of your arsenal of programming weapons.<H2><A NAME="StringFuNCtions"><FONT SIZE=5 COLOR=#FF0000>String FuNCtions</FONT></A></H2><P>The first set of fuNCtions that we'll look at are those that dealwith strings. These fuNCtions let you determine a string's length,search for a sub-string, and change the case of the charactersin the string, among other things. Table 5.1 shows Perl's stringfuNCtions.<BR><P><CENTER><B>Table 5.1 String FuNCtions</B></CENTER><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD WIDTH=211><I>FuNCtion</I></TD><TD WIDTH=379><I>Description</I></TD></TR><TR><TD WIDTH=211><TT>chomp(STRING) OR chomp(ARRAY)</TT></TD><TD WIDTH=379>Uses the value of the <TT>$/</TT> special variable to remove endings from <TT>STRING</TT> or each element of <TT>ARRAY</TT>. The line ending is only removed if it matches the current value of <TT>$/</TT>.</TD></TR><TR><TD WIDTH=211><TT>chop(STRING) OR chop(ARRAY)</TT></TD><TD WIDTH=379>Removes the last character from a string or the last character from every element in an array. The last character chopped is returned.</TD></TR><TR><TD WIDTH=211><TT>chr(NUMBER)</TT></TD><TD WIDTH=379>Returns the character represented by <TT>NUMBER</TT> in the ASCII table. For instaNCe, <TT>chr(65)</TT> returns the letter <TT>A</TT>. For more information about the ASCII table see Appendix E, "ASCII Table."</TD></TR><TR><TD WIDTH=211><TT>crypt(STRING1, STRING2)</TT></TD><TD WIDTH=379>ENCrypts <TT>STRING1</TT>. Unfortunately, Perl does not provide a decrypt fuNCtion. </TD></TR><TR><TD WIDTH=211><TT>index(STRING, SUBSTRING, POSITION)</TT></TD><TD WIDTH=379>Returns the position of the first occurreNCe of <TT>SUBSTRING</TT> in <TT>STRING</TT> at or after <TT>POSITION</TT>. If you don't specify <TT>POSITION</TT>, the search starts at the beginning of <TT>STRING</TT>.</TD></TR><TR><TD WIDTH=211><TT>join(STRING, ARRAY)</TT></TD><TD WIDTH=379>Returns a string that consists of all of the elements of <TT>ARRAY</TT> joined together by <TT>STRING</TT>. For instaNCe, <TT>join(">>", ("AA", "BB", "cc"))</TT> returns <TT>"AA>>BB>>cc"</TT>.</TD></TR><TR><TD WIDTH=211><TT>lc(STRING)</TT></TD><TD WIDTH=379>Returns a string with every letter of <TT>STRING</TT> in lowercase. For instaNCe, <TT>lc("ABCD")</TT> returns <TT>"abcd"</TT>.</TD></TR><TR><TD WIDTH=211><TT>lcfirst(STRING)</TT></TD><TD WIDTH=379>Returns a string with the first letter of <TT>STRING</TT> in lowercase. For instaNCe, <TT>lcfirst("ABCD")</TT> returns <TT>"aBCD"</TT>.</TD></TR><TR><TD WIDTH=211><TT>length(STRING)</TT></TD><TD WIDTH=379>Returns the length of <TT>STRING</TT>.</TD></TR><TR><TD WIDTH=211><TT>rindex(STRING, SUBSTRING, POSITION)</TT></TD><TD WIDTH=379>Returns the position of the last occurreNCe of <TT>SUBSTRING</TT> in <TT>STRING</TT> at or after <TT>POSITION</TT>. If you don't specify <TT>POSITION</TT>, the search starts at the end of <TT>STRING</TT>.</TD></TR><TR><TD WIDTH=211><TT>split(PATTERN, STRING, LIMIT)</TT></TD><TD WIDTH=379>Breaks up a string based on some delimiter. In an array context, it returns a list of the things that were found. In a scalar context, it returns the number of things found.</TD></TR><TR><TD WIDTH=211><TT>substr(STRING, OFFSET, LENGTH)</TT></TD><TD WIDTH=379>Returns a portion of <TT>STRING</TT> as determined by the <TT>OFFSET</TT> and <TT>LENGTH</TT> parameters. If <TT>LENGTH</TT> is not specified, then everything from <TT>OFFSET</TT> to the end of <TT>STRING</TT> is returned. A negative <TT>OFFSET</TT> can be used to start from the right side of <TT>STRING</TT>.</TD></TR><TR><TD WIDTH=211><TT>uc(STRING)</TT></TD><TD WIDTH=379>Returns a string with every letter of <TT>STRING</TT> in uppercase. For instaNCe, <TT>uc("abcd")</TT> returns <TT>"ABCD"</TT>.</TD></TR><TR><TD WIDTH=211><TT>Ucfirst(STRING)</TT></TD><TD WIDTH=379>Returns a string with the first letter of <TT>STRING</TT> in uppercase. For instaNCe, <TT>ucfirst("abcd")</TT> returns <TT>"Abcd"</TT>.</TD></TR></TABLE></CENTER><P><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD><B>Note</B></TD></TR><TR><TD><BLOCKQUOTE>As a general rule, if Perl sees a number where it expects a string, the number is quietly converted to a string without your needing to do anything.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD><B>Note</B></TD></TR><TR><TD><BLOCKQUOTE>Some of these fuNCtions use the special variable <TT>$_ </TT>as the default string to work with. More information about <TT>$_ </TT>can be found in <A HREF="ch9.htm" >Chapter 9</A> "Using Files," and <A HREF="ch12.htm" >Chapter 12</A>, "Using Special Variables."</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>The next few sections demonstrate some of these fuNCtions. Afterseeing some of them work, you'll be able to use the rest of them.<H3><A NAME="ExampleChangingaStringsValue">Example: Changing a String's Value</A></H3><P>Frequently, I find that I need to change part of a string's value,usually somewhere in the middle of the string. When this needarises, I turn to the <TT>substr()</TT>fuNCtion. Normally, the <TT>substr()</TT>fuNCtion returns a sub-string based on three parameters: the stringto use, the position to start at, and the length of the stringto return.<P><IMG SRC="pseudo.gif" BORDER=1 ALIGN=RIGHT><p><BLOCKQUOTE><I>Assign </I><TT><I>$firstVar</I></TT><I>the return value from substr().<BR>Print </I><TT><I>$firstVar</I></TT><I>.</I></BLOCKQUOTE><BLOCKQUOTE><PRE>$firstVar = substr("0123BBB789", 4, 3);print("firstVar = $firstVar\n");</PRE></BLOCKQUOTE><P>This program prints:<BLOCKQUOTE><PRE>firstVar = BBB</PRE></BLOCKQUOTE><P>The <TT>substr()</TT> fuNCtion startsat the fifth position and returns the next three characters. Thereturned string can be printed like in the above example, as anarray element, for string coNCatention, or any of a hundred otheroptions.<P>Things become more interesting when you put the <TT>substr()</TT>fuNCtion on the left-hand side of the assignment statement. Then,you actually can assign a value to the string that <TT>substr()</TT>returns.<P><IMG SRC="pseudo.gif" BORDER=1 ALIGN=RIGHT><p><BLOCKQUOTE><I>Initialize </I><TT><I>$firstVar</I></TT><I>with a string literal.<BR>Replace the string returned by the </I><TT><I>substr()</I></TT><I>fuNCtion with "AAA".<BR>Print </I><TT><I>$firstVar</I></TT><I>.</I></BLOCKQUOTE><BLOCKQUOTE><PRE>$firstVar = "0123BBB789";substr($firstVar, 4, 3) = "AAA";print("firstVar = $firstVar\n");</PRE></BLOCKQUOTE><P>This program prints:<BLOCKQUOTE><PRE>firstVar = 0123AAA789</PRE></BLOCKQUOTE><H3><A NAME="ExampleSearchingaString">Example: Searching a String</A></H3><P>Another useful thing you can do with strings is search them tosee if they have a given sub-string. For example if you have afull path name such as <TT>"C:\\WINDOWS\\TEMP\\WSREWE.DAT"</TT>, you might need to extractthe file name at the end of the path. You might do this by searchingfor the last backslash and then using <TT>substr()</TT>to return the sub-string.<BR><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD><B>Note</B></TD></TR><TR><TD><BLOCKQUOTE>The path name string has double backslashes to indicate to Perl that we really want a backslash in the string and not some other escape sequeNCe. You can read more about escape sequeNCes in <A HREF="ch2.htm" >Chapter 2</A> "Numeric and String Literals."</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P><IMG SRC="pseudo.gif" BORDER=1 ALIGN=RIGHT><p><BLOCKQUOTE><I>Assign a string literal to </I><TT><I>$pathName</I></TT><I>.<BR>Find the location of the last backslash by starting at the endof the string and working backward using the </I><TT><I>rindex()</I></TT><I>fuNCtion. When the position of the last backslash is found, addone to it so that<BR></I><TT><I>$position</I></TT><I> pointsat the first character ("W") of the file name.<BR>Use the </I><TT><I>substr()</I></TT><I>fuNCtion to extract the file name and assign it<BR>to </I><TT><I>$fileName</I></TT><I>.<BR>Print </I><TT><I>$fileName</I></TT><I>.</I></BLOCKQUOTE><BLOCKQUOTE><PRE>$pathName = "C:\\WINDOWS\\TEMP\\WSREWE.DAT";$position = rindex($pathName, "\\") + 1;$fileName = substr($pathName, $position);print("$fileName\n");</PRE></BLOCKQUOTE><P>This program prints:<BLOCKQUOTE><PRE>WSREWE.DAT</PRE></BLOCKQUOTE><P>If the third parameter-the length-is not supplied to <TT>substr()</TT>,it simply returns the sub-string that starts at the position specifiedby the second parameter and continues until the end of the stringspecified by the first parameter.<H2><A NAME="ArrayFuNCtions"><FONT SIZE=5 COLOR=#FF0000>Array FuNCtions</FONT></A></H2><P>Arrays are a big part of the Perl language and Perl has a lotof fuNCtions to help you work with them. Some of the actions arrays
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -