Chapter 5. Eval
One person’s data is another person’s program.
Years ago, a friend of mine showed me an elegant program running on a
tiny 32K machine, the BBC Micro, that accepted any mathematical
expression such as
(x**2) and graphed it.
Fresh from a study of parsers, I’d wondered how many hundreds
of lines it took him to write it. He showed me the code; the entire
program fit on the small screen. He had used the
eval statement provided by BASIC.
Most self-respecting scripting languages such as BASIC (some versions, anyway), Perl, Tcl, LISP, and Python have a feature that clearly sets them apart from systems programming languages like C: the ability to treat character strings as little programs.
For me, Perl’s
evaluation capability is one of the biggest reasons for using the
language. (The other is its terrific support for regular
expressions.) I use run-time evaluation for creating little snippets
of code on the fly, which then execute at typical Perl speeds (i.e.,
fast!), for writing sophisticated interpreters for little
eval function is the gateway to
this power. We will use this feature in Chapter 7,
for creating object accessor functions, and in Chapter 11, for building an SQL query evaluator, among
As it turns out, Perl’s
eval function works
in two somewhat distinct ways, depending on the type of its argument.
If given a string,
eval treats the string as ...