Chapter 5. Eval

One person’s data is another person’s program.

Programming Pearls, Communications of the ACM, Sept. 1985

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 sin(x) + cos (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.[22]

For me, Perl’s run-time 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 languages.[23] The 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 other things.

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 ...

Get Advanced Perl Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.