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.