?? ch5.htm
字號(hào):
<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 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 blocks
of codes that are given names so that you can use them as needed.
FuNCtions help you to organize your code into pieces that are
easy to understand and work with. They let you build your program
step by step, testing the code along the way.
<P>
After you get the idea for a program, you need to develop a program
outline-either in your head or on paper. Each step in the outline
might be one fuNCtion in your program. This is called <I>modular
programming</I>. Modular programming is very good at allowing
you to hide the details so that readers of your source code can
understand the overall aim of your program.
<P>
For instaNCe, if your program has a fuNCtion that calculates the
area of a circle, the following line of code might be used to
call it:
<BLOCKQUOTE>
<PRE>
$areaOfFirstCircle = areaOfCircle($firstRadius);
</PRE>
</BLOCKQUOTE>
<P>
By looking at the fuNCtion call, the reader knows what the program
is doing. Detailed understanding of the actual fuNCtion is not
needed.<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 thing
on the line is a scalar variable and an assignment operator. You
already know this means Perl assigns the value on the right of
the 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. Inside
the parentheses is a list of parameters or values that get passed
to the fuNCtion. You can think of a parameter just like a football.
When passed, the receiver (for example, the fuNCtion) has several
options: 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>&</TT> character to start fuNCtion names, and in a few cases it is needed. Those few situations that the <TT>&</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" tppabs="http://cheminf.nankai.edu.cn/~eb~/Perl%205%20By%20Example/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 05LST01.PL-Calculating the Area of a
Circle<BR>
</B>
</BLOCKQUOTE>
<BLOCKQUOTE>
<PRE>
$areaOfFirstCircle = areaOfCircle(5);
print("$areaOfFirstCircle\n");
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 flow
returned 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 immediately
follow the fuNCtion name. In Listing 5.1, the fuNCtion call was
<TT>areaOfCircle(5)</TT>. There was
only one parameter, the number 5. Even though there is only one
parameter, Perl creates a parameter array for the fuNCtion to
use.
<P>
Inside the <TT>areaOfCircle()</TT>
fuNCtion, the parameter array is named <TT>@_</TT>.
All parameters specified during the fuNCtion call are stored in
the <TT>@_ </TT>array so that the
fuNCtion can retrieve them. Our small fuNCtion did this with the
line:
<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 calculated
value. 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 between
a fuNCtion and a subroutine, the differeNCe being that a fuNCtion
returns a value and a subroutine does not. Perl makes no such
distiNCtions. Everything is a fuNCtion-whether or not it returns
a 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 parameters
were passed by evaluating <TT>@</TT>
in a scalar context.
<P>
<IMG SRC="pseudo.gif" tppabs="http://cheminf.nankai.edu.cn/~eb~/Perl%205%20By%20Example/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("A".."Z");
sub firstSub {
$numParameters = @_ ;
print("The number of parameters is $numParameters\n");
}
</PRE>
</BLOCKQUOTE>
<P>
This program prints out:
<BLOCKQUOTE>
<PRE>
The number of parameters is 6
The number of parameters is 3
The number of parameters is 26
</PRE>
</BLOCKQUOTE>
<P>
Perl lets you pass any number of parameters to a fuNCtion. The
fuNCtion decides which parameters to use and in what order. The
<TT>@_</TT> array is used like any
other array.
<P>
Let's say that you want to use scalar variables to refereNCe the
parameters 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 elements
to scalars in one easy step.
<P>
<IMG SRC="pseudo.gif" tppabs="http://cheminf.nankai.edu.cn/~eb~/Perl%205%20By%20Example/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("The height is $height. The width is $width.
The area is $area.\n\n");
}
</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 element
is assigned to <TT>$height</TT>, and
the second element is assigned to <TT>$width</TT>.
After the assignment is made, you can use the scalar variables
to 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 for
another reason-besides simple readability coNCerns. When you change
the value of the elements of the <TT>@ </TT>
array, you also change the value of the parameters in the rest
of the program. This is because Perl parameters are called by
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -