next up previous contents
Next: A Simple Example Up: Functions Previous: Functions   Contents

Introduction

Functions are useful in perl programs for a variety of reasons. First, there are tasks which you'll be doing over and over again. If you write a function to perform the task, you don't need to worry over the details of how to do the job each time; you can simply call the function. This has the added benefit of reducing the amount of duplicated code in your programs. Such code is hard to maintain because, when you need to make changes, you need to make those changes in every occurence of the duplicated code, and it's easy to overlook some, or make incorrect changes.

But beyond that, it's sometimes very helpful to break your program into pieces, to help you understand the flow and structure of the program, and to make it easier to maintain when changes are required. For example, suppose you have a program which, among other things, verifies a user id against a data base, and the format of that data base changes. Without a function to perform the work, you'd need to check your entire program to see where the data base was being accessed. It's very possible that you'd overlook some code, or forget the overall structure of the program. But if you had implemented the data base check through a function, say check_data_base(), then you'd only need to modify that code, knowing that all the data base functionality was confined to that program. This style of programming is known as modular programming, and it dramatically simplifies program design and maintenance.

In perl, getting started with functions is very easy because, by default, all of the variables in perl are global; that is, they are known throughout your entire perl program. While it is tempting to rely on global variables to pass information to your functions, there are some negative consequences of this scheme. If a program goes wrong, and lots of global variables are manipulated inside of functions, it may be very difficult to pinpoint the problem in your program. Furthermore, this style of programming defeats some of the main advantages of using functions in the first place.

We'll start our study of functions by writing very simple functions which rely entirely on global variables for communication, then look at how arguments can be passed to functions, and how variables can be created which are not global, for use inside of functions.


next up previous contents
Next: A Simple Example Up: Functions Previous: Functions   Contents
Phil Spector 2002-10-18