O'Reilly logo

Advanced Perl Programming by Sriram Srinivasan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required