This nine-part article series examines the variety of control structures Perl programmers can use to set up the way a program gets to where it's going. It is excerpted from chapter three of the book Beginning Perl, Second Edition, written by James Lee (Apress; ISBN: 159059391X).
Most of the programs we have seen so far have been very simply structured—they’ve done one statement after another in turn. If we were to represent statements by boxes, our programs would look like this:
This sort of diagram is called a flow chart, and programmers have used them for a long time to help design their programs. They’re considered a bit passé these days, but they’re still useful. The path Perl (or any other language) takes by following the arrows is called the flow of execution of the program. Boxes denote statements (or a single group of statements), and diamonds denote tests. There are also a whole host of other symbols for magnetic tapes, drum storage, and all sorts of wonderful devices, now happily lost in the mists of time.
We can choose our path through the program depending on certain things. For instance, we’ll do something if two strings are equal:
We can also iterate, or loop, through a number of things by executing a block of statements again and again for each element of the list:
We’ll take a look at the other sorts of control structures we have in Perl. For example, structures that do things if or unless something is true. We’ll see structures that do things while something is true, or until it is true. Structures that loop for a certain number of times, or foreach element in a list. Each of the words in italic in this paragraph is a Perl keyword, and we’ll examine them in this chapter.