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

📄 ch5.htm

📁 this is a book on pearl , simple example with explanation is given here. it could be beneficial for
💻 HTM
📖 第 1 页 / 共 4 页
字号:
<HTML><HEAD><TITLE>Chapter 5 -- FuNCtions</TITLE><META></HEAD><BODY TEXT="#000000" BGCOLOR="#FFFFFF" LINK="#0000EE" VLINK="#551A8B" ALINK="#CE2910"><H1><FONT SIZE=6 COLOR=#FF0000>Chapter&nbsp;5</FONT></H1><H1><FONT SIZE=6 COLOR=#FF0000>FuNCtions</FONT></H1><HR><P><CENTER><B><FONT SIZE=5>CONTENTS</FONT></B></CENTER><UL><UL><LI><A HREF="#ExampleUsingtheParameterArray">Example: Using the Parameter Array (@_)</A><LI><A HREF="#ExamplePassingParametersbyRefereNCe">Example: Passing Parameters by RefereNCe</A><LI><A HREF="#ExampleScopeofVariables">Example: Scope of Variables</A><LI><A HREF="#ExampleUsingaListasaFuNCtionParameter">Example: Using a List as a FuNCtion Parameter</A><LI><A HREF="#ExampleNestingFuNCtionCalls">Example: Nesting FuNCtion Calls</A><LI><A HREF="#ExampleUsingaPrivateFuNCtion">Example: Using a Private FuNCtion</A></UL><LI><A HREF="#StringFuNCtions">String FuNCtions</A><UL><LI><A HREF="#ExampleChangingaStringsValue">Example: Changing a String's Value</A><LI><A HREF="#ExampleSearchingaString">Example: Searching a String</A></UL><LI><A HREF="#ArrayFuNCtions">Array FuNCtions</A><UL><LI><A HREF="#ExamplePrintinganAssociativeArray">Example: Printing an Associative Array</A><LI><A HREF="#ExampleCheckingtheExisteNCeofanElement">Example: Checking the ExisteNCe of an Element</A></UL><LI><A HREF="#Summary">Summary</A><LI><A HREF="#ReviewQuestions">Review Questions</A><LI><A HREF="#ReviewExercises">Review Exercises</A></UL><HR><P>This chapter takes a look at <I>fuNCtions</I>. FuNCtions are blocksof codes that are given names so that you can use them as needed.FuNCtions help you to organize your code into pieces that areeasy to understand and work with. They let you build your programstep by step, testing the code along the way.<P>After you get the idea for a program, you need to develop a programoutline-either in your head or on paper. Each step in the outlinemight be one fuNCtion in your program. This is called <I>modularprogramming</I>. Modular programming is very good at allowingyou to hide the details so that readers of your source code canunderstand the overall aim of your program.<P>For instaNCe, if your program has a fuNCtion that calculates thearea of a circle, the following line of code might be used tocall it:<BLOCKQUOTE><PRE>$areaOfFirstCircle = areaOfCircle($firstRadius);</PRE></BLOCKQUOTE><P>By looking at the fuNCtion call, the reader knows what the programis doing. Detailed understanding of the actual fuNCtion is notneeded.<BR><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD><B>Tip</B></TD></TR><TR><TD><BLOCKQUOTE>Well thought out fuNCtion and variable names help people to understand your program. If the line of code was</BLOCKQUOTE><BLOCKQUOTE><TT>$areaFC = areaCirc($fRad);</TT></BLOCKQUOTE><BLOCKQUOTE>its meaning would not be as clear.</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>Calling a fuNCtion means that Perl stops executing the current series of program lines. Program flow jumps into the program code inside the fuNCtion. When the fuNCtion is finished, Perl jumps back to the point at which the fuNCtion call was made. Program execution continues from that point onward.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>Let's look at the fuNCtion call a little closer. The first thingon the line is a scalar variable and an assignment operator. Youalready know this means Perl assigns the value on the right ofthe assignment operator to <TT>$areaOfFirstCircle</TT>.But, what exactly is on the right?<P>The first thing you see is the fuNCtion name <TT>areaOfCircle()</TT>.The parentheses directly to the right and no <TT>$</TT>,<TT>@</TT>, or <TT>%</TT>beginning the name indicates that this is a fuNCtion call. Insidethe parentheses is a list of parameters or values that get passedto the fuNCtion. You can think of a parameter just like a football.When passed, the receiver (for example, the fuNCtion) has severaloptions: run (modify it in some way), pass (call other routines),fumble (call the error handler).<BR><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD><B>Note</B></TD></TR><TR><TD><BLOCKQUOTE>Perl enables you to use the <TT>&amp;</TT> character to start fuNCtion names, and in a few cases it is needed. Those few situations that the <TT>&amp;</TT> character is needed are beyond the scope of this book.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>Listing 5.1 shows a short program that calls and defines the <TT>areaOfCircle()</TT>fuNCtion.<P><IMG SRC="pseudo.gif" BORDER=1 ALIGN=RIGHT><p><BLOCKQUOTE><I>Assign </I><TT><I>$areaOfFirstCircle</I></TT><I>the value that is returned by the fuNCtionareaOfCircle().<BR>Print </I><TT><I>$areaOfFirstCircle</I></TT><I>.<BR>Define the areaOfCircle() fuNCtion.<BR>Get the first parameter from the </I><TT><I>@_</I></TT><I> parameter array.<BR>Calculate the area and return the new value.</I></BLOCKQUOTE><HR><BLOCKQUOTE><B>Listing 5.1&nbsp;&nbsp;05LST01.PL-Calculating the Area of aCircle<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>$areaOfFirstCircle = areaOfCircle(5);print(&quot;$areaOfFirstCircle\n&quot;);sub areaOfCircle {    $radius = $_[0];    return(3.1415 * ($radius ** 2));}</PRE></BLOCKQUOTE><HR><P>This program prints:<BLOCKQUOTE><PRE>78.7375</PRE></BLOCKQUOTE><P>The fact that something prints tells you that the program flowreturned to the print line after calling the <TT>areaOfCircle()</TT>fuNCtion.<P>A fuNCtion definition is very simple. It consists of:<BLOCKQUOTE><PRE>sub fuNCtionName {}</PRE></BLOCKQUOTE><P>That's it. Perl fuNCtion definitions never get any more complex.<P>The complicated part comes when dealing with parameters. <I>Parameters</I>are values passed to the fuNCtion (remember the football?).The parameters are specified inside the parentheses that immediatelyfollow the fuNCtion name. In Listing 5.1, the fuNCtion call was<TT>areaOfCircle(5)</TT>. There wasonly one parameter, the number 5. Even though there is only oneparameter, Perl creates a parameter array for the fuNCtion touse.<P>Inside the <TT>areaOfCircle()</TT>fuNCtion, the parameter array is named <TT>@_</TT>.All parameters specified during the fuNCtion call are stored inthe <TT>@_ </TT>array so that thefuNCtion can retrieve them. Our small fuNCtion did this with theline:<BLOCKQUOTE><PRE>$radius = $_[0];</PRE></BLOCKQUOTE><P>This line of code assigns the first element of the <TT>@_</TT>array to the <TT>$radius</TT>scalar.<BR><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD><B>Note</B></TD></TR><TR><TD><BLOCKQUOTE>Because parameters always are passed as lists, Perl fuNCtions also are referred to as list operators. And, if only one parameter is used, they are sometimes referred to as unary operators. However, I'll continue to call them fuNCtions and leave the finer points of distiNCtion to others.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>The next line of the fuNCtion:<BLOCKQUOTE><PRE>return(3.1415 * ($radius ** 2));</PRE></BLOCKQUOTE><P>calculates the circle's area and returns the newly calculatedvalue. In this case, the returning value is assigned to the <TT>$areaOfFirstCircle</TT>scalar variable.<BR><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD><B>Note</B></TD></TR><TR><TD><BLOCKQUOTE>If you prefer, you don't need to use the <TT>return()</TT> fuNCtion to return a value because Perl automatically returns the value of the last expression evaluated. I prefer to use the <TT>return()</TT> fuNCtion and be explicit so that there is no mistaking my intention.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>You may have used programming languages that distinguish betweena fuNCtion and a subroutine, the differeNCe being that a fuNCtionreturns a value and a subroutine does not. Perl makes no suchdistiNCtions. Everything is a fuNCtion-whether or not it returnsa value.<H3><A NAME="ExampleUsingtheParameterArray">Example: Using the Parameter Array (@_)</A></H3><P>All parameters to a fuNCtion are stored in an array called <TT>@_</TT>.One side effect of this is that you can find out how many parameterswere passed by evaluating <TT>@</TT>in a scalar context.<P><IMG SRC="pseudo.gif" BORDER=1 ALIGN=RIGHT><p><BLOCKQUOTE><I>Call the </I><TT><I>firstSub()</I></TT><I>fuNCtion with a variety of parameters.<BR>Define the </I><TT><I>firstSub()</I></TT><I>fuNCtion<BR>Assign </I><TT><I>$numParameters</I></TT><I>the number of elements in the array @_.<BR>Print out how any parameters were passed.</I></BLOCKQUOTE><BLOCKQUOTE><PRE>firstSub(1, 2, 3, 4, 5, 6);firstSub(1..3);firstSub(&quot;A&quot;..&quot;Z&quot;);sub firstSub {    $numParameters = @_ ;    print(&quot;The number of parameters is $numParameters\n&quot;);}</PRE></BLOCKQUOTE><P>This program prints out:<BLOCKQUOTE><PRE>The number of parameters is 6The number of parameters is 3The number of parameters is 26</PRE></BLOCKQUOTE><P>Perl lets you pass any number of parameters to a fuNCtion. ThefuNCtion decides which parameters to use and in what order. The<TT>@_</TT> array is used like anyother array.<P>Let's say that you want to use scalar variables to refereNCe theparameters so you don't have to use the clumsy and uninformative<TT>$_ [0]</TT> array element notation.By using the assignment operator, you can assign array elementsto scalars in one easy step.<P><IMG SRC="pseudo.gif" BORDER=1 ALIGN=RIGHT><p><BLOCKQUOTE><I>Call the </I><TT><I>areaOfRectangle()</I></TT><I>fuNCtion with varying parameters.<BR>Define the </I><TT><I>areaOfRectangle()</I></TT><I>fuNCtion.<BR>Assign the first two elements of </I><TT><I>@_</I></TT><I>to </I><TT><I>$height</I></TT><I>and </I><TT><I>$width</I></TT><I>respectively.<BR>Calculate the area.<BR>Print the three variables: </I><TT><I>$height</I></TT><I>,</I><TT><I>$width</I></TT><I>, and</I><TT><I>$area</I></TT><I>.</I></BLOCKQUOTE><BLOCKQUOTE><PRE>areaOfRectangle(2, 3);areaOfRectangle(5, 6);sub areaOfRectangle {    ($height, $width) = @_ ;    $area = $height * $width;    print(&quot;The height is $height. The width is $width.        The area is $area.\n\n&quot;);}</PRE></BLOCKQUOTE><P>This program prints out:<BLOCKQUOTE><PRE>The height is 2. The width is 3.        The area is 6.The height is 5. The width is 6.        The area is 30.</PRE></BLOCKQUOTE><P>The statement <TT>($height,$width) = @_;</TT>does the array element to scalar assignment. The first elementis assigned to <TT>$height</TT>, andthe second element is assigned to <TT>$width</TT>.After the assignment is made, you can use the scalar variablesto represent the parameters.<H3><A NAME="ExamplePassingParametersbyRefereNCe">Example: Passing Parameters by RefereNCe</A></H3><P>Using scalar variables inside your fuNCtions is a good idea foranother reason-besides simple readability coNCerns. When you changethe value of the elements of the <TT>@ </TT>array, you also change the value of the parameters in the restof the program. This is because Perl parameters are called by

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -