Eval - Uses

Uses

A call to eval is sometimes used by inexperienced programmers for all sorts of things. In most cases, there are alternatives which are more flexible and do not require the speed penalty of parsing code.

For instance, eval is sometimes used for a simple mail merge facility, as in this PHP example:

$name = 'John Doe'; $greeting = 'Hello'; $template = '"$greeting, $name! How can I help you today?"'; print eval("return $template;");

Although this works, it can cause some security problems (see security risks), and will be much slower than other possible solutions. A faster and more secure solution would be changing the last line to print $template; and removing the single quotes from the previous line, or using printf.

eval is also sometimes used in applications needing to evaluate math expressions, such as spreadsheets. This is much easier than writing an expression parser, but finding or writing one would often be a wiser choice. Besides the fixable security risks, using the language's evaluation features would most likely be slower, and wouldn't be as customizable.

Perhaps the best use of eval is in bootstrapping a new language (as with Lisp), and in tutoring programs for languages which allow users to run their own programs in a controlled environment.

For the purpose of expression evaluation, the major advantage of eval over expression parsers is that, in most programming environments where eval is supported, the expression may be arbitrarily complex, and may include calls to functions written by the user that could not have possibly been known in advance by the parser's creator. This capability allows you to effectively augment the eval engine with a library of functions that you can enhance as needed, without having to continually maintain an expression parser. If, however, you do not need this ultimate level of flexibility, expression parsers are far more efficient and lightweight.

Read more about this topic:  Eval