|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13
|
|
Chapter 1:
|
|
|
|
A Peek Into Programming
|
|
Are you sitting comfortably? Then I'll begin.
|
|
- Preamble to children's story in Listen With Mother,
B.B.C. radio program from 1950
|
|
The Macintosh is a truly wonderful invention: an approachable and highly
interactive information-handling appliance. Using a Mac, even a beginning
user can draw pictures, create and format documents, compose music, and
more. With practice and study, users can learn how to achieve marvelous
results in a wide range of disciplines.
|
|
MostMac OSusers are not, however, encouraged to program the computer
itself. If a Mac OS application lacks a needed function, the typical user is
forced to work around the problem. This may involve repetitive manual
effort, the use of a "helper" tool, or switching to a different application.
|
|
More generally, although the Finderis a powerful and comfortable envi-
ronment for interactive work, it fails to meet repetitive challenges grace-
fully. Renaming a single file is trivial: a matter of seconds. Renaming hun-
dreds or thousands of files, however, requires minutes or even hours of labor.
Worse, the process does not become significantly easier with practice.
|
|
By learning how to program your Macintosh, you can take control of the
machine's powerful "batch" capabilities. This won't solve every problem
you may encounter, but it will give you ways to avoid tedious, repetitive
efforts. And, down the road, you may find yourself generating some helper
tools of your own.
|
|
This chapter and the next two demystify computer programming, introduc-
ing a number of fundamental concepts at a theoretical and philosophical
level. In Chapter 1, we discuss programming principles and philosophy,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Chapter 2 adds the concept of data, without which most programs are
nearly worthless. Chapter 3 provides a first look at syntax - the structure
of programming languages - with examples in Perl.
|
|
We won't get very far into practical programming techniques in Part I,
however. If you are an experienced programmer, feel free to skip on to
chapter 3, where we will begin to discuss Perl syntax in particular, or to
Part II, where we begin learning the Perl language in depth, with real
programming examples. Or, if you like, stick around; you might learn
something ...
|
|
Cooking Up A Program
|
|
Rachel is a bright young girl who needs to learn some cooking skills. After
determining that Rachel likes to eat hard-boiled eggs, you set out to tell
her how to prepare them. Here is a plausible program(recipe) that should
allow a beginning cook to produce hard-boiled eggs:
|
|
Place several eggs in a sauce pan.
Add sufficient cold water to surround all of the eggs.
Heat the pan until the water boils.
Cover the pan and turn off the heat.
Wait 25 minutes.
Drain the pan, then refill with cold water.
|
|
In debugging(testing and correcting) this program, you might note that one
bath of cooling water may not be sufficient to cool the eggs properly. Also,
the program neglects to say anything about examining the raw eggs or stor-
ing cooked eggs. Finally, if you plan on giving Rachel more than one cooking
note, a descriptive title would be useful. So, let's edit the program:
|
|
Hard-boiled eggs
|
|
Inspect eggs, discarding cracked eggs.
Place several eggs in a sauce pan.
Add cold water to the pan, covering all of the eggs.
Heat the pan until the water boils.
Cover the pan and turn off the heat.
Wait 25 minutes for the eggs to cook.
Drain and refill the pan with cold water until the water stays cool.
Wait 5 minutes for the eggs to cool.
If any of the cooked eggs are cracked, use them first.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Refrigerate any eggs that are not immediately consumed.
|
|
This program makes certain assumptions about the party (Rachel, in this
case) that will be interpretingit. For instance, it doesn't bother to define
eggs, sauce pans, or water. Thus, it might cause a sufficiently naive cook (or
a computer) to make errors or even halt in confusion. When you are writing
programs (or books!), be sure that the intended audience has the necessary
background information to understand what you are saying.
|
|
Finally, always remember that your programs need to be both executable
(runnable by the computer) and understandable by some future programmer.
If you think of your programs as "executable essays", describing a problem
and its solution, you won't go far wrong.
|
|
Program Structure
|
|
Some computer systems could follow our egg-cooking program, but most need
more details and a slightly more explicit structure. Here is the program,
translated into explicit, commented, and structured pseudo-code(i.e., any
halfway step between English and a "real" programming language):
|
|
Hard-boiled eggs
|
|
# Select some eggs and prepare them for cooking.
|
|
Until you have enough eggs:
Select an egg from the carton.
If the egg is cracked:
Discard the cracked egg.
Otherwise:
Place the egg in the pan.
Return remaining eggs to the refrigerator.
Until all of the eggs are covered in water:
Add cold water to the pan.
|
|
# Cook the eggs.
|
|
Until the water boils:
Heat the pan on a stove burner set to high.
Cover the pan.
Turn off the heat.
Wait 25 minutes.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Cool and store the cooked eggs.
|
|
Until the rinse water stays cool:
Drain and refill the pan with cold rinse water.
Wait 5 minutes.
If any of the cooked eggs are cracked:
Use the cracked eggs first.
If any eggs are not immediately consumed:
Refrigerate the remaining eggs.
|
|
Although this program is far more explicit than Rachel would need, it only
begins to approach the level of detail required by a computer. For instance,
it fails to specify a test for "cracked eggs" or to say what implement should
be used to cover the pan. Also, the usage notes are not totally explicit.
|
|
Nonetheless, creating this sort of pseudo-code moves us several long steps
towards creating a real program. We have commented1the intent of each
section, just above the required actions. We have also been very explicit
about which things will be done, under what conditions, and in what order.
|
|
If you think of each line in the recipe being "in control" for a brief instant of
time, you can understand why programmers speak of the flow of controlin a
program. Many early programers allowed this flow to "jump around", using
and abusing the infamous (and totally unstructured) "goto" statement.
|
|
In the early 1970s, however, the structured programmingrevolution hit
programming. Its proponents2observed that three control flowconstructs,
taken together, were sufficient to express any desired flow of control, no
matter how complicated:
|
|
-
Sequences of actions, shown above as sequences of individual lines.
|
|
-
Selection, indicated above by the "if" and "otherwise" constructs.
|
|
-
Repetition, indicated above by the "until" construct.
|
|
|
|
1A bit of Perl syntax here; the "sharp" (hash, number, pound, etc.) sign is used to begin
a comment that continues through the end of the current line of text.
2Structured Programming(O.-J. Dahl, et al, Academic Press, 1972, 0-12-200556-2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
By using only these constructs, programmers can create code whose "struc-
ture" is evident upon inspection. This eases the burden of initial develop-
ment, but it really finds favor with programmers who need to delve into the
code at some later date: structured code, quite simply, is easier to maintain!
|
|
Assuming that Rachel is successful in following your program, you could go
on to describe the preparation of deviled eggs and egg-salad sandwiches.
These programs could specify "hard-boiled eggs" as an ingredient, making
the assumption that Rachel could remember (or look up) the needed recipe.
|
|
Because the program for egg-salad sandwiches can ignore the details of
preparing hard-boiled eggs, it can be shorter, simpler, and easier to debug.
And, if Rachel finds a better way of making hard-boiled eggs, she can use it
without having to modify her method of making sandwiches.
|
|
Most comprehensive cookbooks are mixtures of low-level and high-level
recipes. The low-level recipes (e.g., hard-boiled eggs, white sauce) can be
used on their own, but they can also be referenced by higher-level recipes
(e.g., poached salmon in egg sauce).
|
|
Similarly, by creating and using code libraries, programmers take advan-
tage of generic functions, keeping their programs as short as possible. The
Perl community is very rich in this sort of pre-defined code. Before you start
to write a complex program, be sure to check for existing code resources!
|
|
Error Checking
|
|
Rachel would not continue trying to get eggs from an empty carton, but most
computer systems have no such common sense. If our program were intended
for use by a computer, it could be greatly improved by adding a bit of error-
checking, as:
|
|
Until you have enough eggs:
Quit loop if the carton is empty.
Select an egg from the carton.
If the egg is cracked:
Discard the cracked egg.
Otherwise:
Place the egg in the pan.
Quit program if the pan is empty.
|
|
# Select and prepare eggs.
# Error-check
|
|
|
# Error-check
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The first added command (Quit loop ...)tells the interpreter to leave the
loop if the carton goes empty before we get the desired quantity. This may
result in our getting less eggs than we wanted, but it prevents us from end-
lessly examining an empty carton. This is an example of fail-softdesign;
the program may not be able to do precisely what is desired, but it can still
fail gently and gracefully.
|
|
The second added command (Quit program ...) tells the interpreter to stop
running the program if the pan never received any eggs. (Why boil a pan
with no eggs in it?)
|
|
Error-checking can be very useful, but it is also possible to go overboard on
it. In general, you should test for errors as early as possible, then relax a bit.
If another program hands you bad data, it's not really your program's fault.
More to the point, the other program should be fixed, not yours!
|
|
Don't fill your programs so full of error tests that you can't figure out what
is going on; that's self-defeating. Finally, although this advice may seem a
bit silly, don't check for errors unless you know what to do about them.
|
|
The Programming Process
|
|
Computer programming is, quite simply, telling the computer what you
want it to do. Practically anyone can learn to write a program. It doesn't
require a degree in computer science and you don't have to be a professional
programmer. It does take some understanding of the problem you wish to
solve, however, and some new ways of thinking about solutions.
|
|
Problem analysis may sound quite simple, but it is all too easy to fool your-
self. Be quite certain you understand the problem before you start your
design and programming efforts; a mistake at this stage can cause you to
spend a great deal of effort in vain.
|
|
Specifically, be sure to go over the problem description with the program's
"customers" (users). It doesn't matter how nifty or elegant your program is if
it doesn't meet the customers' needs!
|
|
Once you understand what you want to do, you must designa solution. (Don't
feel compelled to write a program or even to use a computer in solving your
problem; the objective is to solve the problem in the easiest way you can!)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
It is frequently useful, at this stage, to sketch out your solution in some sort
of outline or pictorial form. Don't feel you have to use any particular nota-
tion; if a diagramming technique helps you clarify your thinking, use it!
|
|
We recommend that you start your design effort by thinking about the data
flow. What are the format and content of the input data (information you
now have) and of the output data (information you need)? What kinds of
intermediate data storage will be needed? Should error-checking be per-
formed on the input data?
|
|
In our program for hard-boiled eggs, these aspects would correspond to the
packaging of the raw and cooked eggs, the type and size of the sauce pan,
and the necessity to check the raw eggs for cracks. Understand, however,
that computers do not share the kind of "common sense" that would allow
Rachel to handle most of these details by herself.
|
|
Now that you have a handle on the I/O(input/output) requirements, you
should decide what kinds of internal data structuresare needed. (In cook-
ing, this might correspond to the selection and arrangement of work surfaces
and utensils.) In programming, the containers become lists, queues, arrays,
trees, etc. If you choose your data structures carefully, the logic(specific
instructions and flow) of the program will often be self-explanatory.
|
|
Occasionally, however, you will need to employ an arcane data structure or
algorithm(piece of program logic). Don't be proud; a few minutes with a
good reference work can save you hours of head-scratching and debugging!
|
|
Alternatively, if you think someone else may have solved a similar prob-
lem, take a look at how they did it. And, if they were nice enough to pack-
age up their work in a library(collection of pre-defined software), use it!
|
|
Selecting an implementation languagenormally comes next, but we're going
to fudge a little on this issue. Perl is an extremely powerful and flexible
language, capable of handling a wide range of problems. Unless you know
that your problem requires very unusual language features, try writing it in
Perl. Even if you discover that you need to switch languages, you will have
clarified your thinking and created a useful prototype.
|
|
On the other hand, don't be afraid to switch languages if the need arises. If
Perl seems to be running out of steam, look for a language which has the fea-
tures you need. Perl is a wonderful "Swiss Army knife", but it may not be the
best tool to change a tire!
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Now you can try coding(writing down the exact text of) the program. If the
programming effort seems a bit imposing, consider breaking it up into a few
stages. Begin with a subset of the problem; add more features if and when
the existing parts have been shown to work. In any case, you should testand
debugthe program, attempting to ensure that it performs correctly.
|
|
Testing: 1, 2, 3, ...
|
|
Just as cooking for oneself does not necessarily qualify one to cook in a four-
star restaurant, there are many levels of "polish" that a program can have.
If a program has only been used by its author, it is all too likely to have a
few sharp edges and burrs.
|
|
There is nothing inherently wrong with this; most programs are only suita-
ble for use by their original authors. Although they may be perfectly func-
tional when used as designed, they aren't ready for use by anyone who isn't
familiar with their limitations.
|
|
These programs should not be confused, however, with commercial-grade
software or even widely distributed freeware and shareware. In general, a
great deal of effort goes into documentation, testing, and polishing of most
published software.
|
|
So, before you offer your "magnum opus" to the Internet, try to look at it as if
you were a stranger: Is the program well-documented? Easy to install?
Hard to break? Give it to some picky friends of varying skill levels and ask
them to try it out. Accept their feedback and use it to improve the program.
|
|
Finally, when you do release your software to the world, be sure to include
clear and complete release information. Be specific about any legal restric-
tions you may be imposing. Is the code Public Domain, GPL (GNU3General
Public License), or what? Put a version number on the code, along with rela-
tively permanent contact information for yourself. This will make the code
substantially more useful than an "anonymous" contribution might be.
|
|
|
|
3The GNU (GNU's Not Unix) Project is engaged in duplicating (with enhancements!)
the entire Unix operating systemin freeware (freely redistributable software).
|
Copyright © 1997-1998 by Prime Time Freeware. All Rights Reserved.