8. Functions
Contents:
We've already seen and used predetermined, built-in functions, such as 8.1 Defining a User FunctionA user function, more commonly called a subroutine or just a sub , is defined in your Perl program using a construct like: sub
The
subname
is the name of the subroutine, which is like the names we've had for scalar variables, arrays, and hashes. Once again, these come from a different namespace, so you can have a scalar variable
The block of statements following the subroutine name becomes the definition of the subroutine. When the subroutine is invoked (described shortly), the block of statements that makes up the subroutine is executed, and any return value (described later) is returned to the caller. Here, for example, is a subroutine that displays that famous phrase: sub say_hello { print "hello, world!\n"; } Subroutine definitions can be anywhere in your program text (they are skipped on execution), but we like to put them at the end of the file, so that the main part of the program appears at the beginning of the file. (If you like to think in Pascal terms, you can put your subroutines at the beginning and your executable statements at the end, instead. It's up to you.) Subroutine definitions are global;[ 2 ] there are no local subroutines. If you have two subroutine definitions with the same name, the later one overwrites the earlier one without warning.[ 3 ]
Within the subroutine body, you may access or give values to variables that are shared with the rest of the program (a global variable). In fact, by default, any variable reference within a subroutine body refers to a global variable. We'll tell you about the exceptions in the later section entitled "Private Variables in Functions ." In the following example: sub say_what { print "hello, $what\n"; }
|
|