In dynamic languages, this is a method (or keyword of some type) that evaluates given string argument(s) as they were code. programming languages (scripting languages) that support this include any language which is worth its salt (and some that aren't), such as Ruby, Tcl, Perl, Bourne shell, C shell, and JavaScript.

Admittedly, eval can be useful, but is mostly a hack. Most common uses for eval are hacks in shell scripts. For example:

_print_dir_stack () {
        local _bar
        while  $_bar -gt -1 ; do
                eval echo -n \"\$_dir_stack$_bar \" >&2	# use eval to dereference a variable
                _bar=`expr $_bar - 1`
        echo >&2
Using eval is a form of dereferencing. In this case, eval has been used to simulate an array in Bourne. After the eval, the line is interpreted and run as, e.g. echo -n "$_dir_stack1 ", simulating the Korn shell line, echo -n "${_dir_stack[$((_bar--))\} " >&2

Another usage is to stick into the environment variables that certain utilities spit out. For example, SSH's ssh-agent(1) will give output in the form:

SSH_AUTH_SOCK=/tmp/ssh-Zig94521/agent.94521; export SSH_AUTH_SOCK;
echo Agent pid 94522;
If I "eval $(ssh-agent)" in the shell, it will define these variables to make the agent useful.

Ruby goes farther than other languages wrt its support of eval. Using methods like "eval", "instance_eval", "class_eval", the evaluation time and context of an eval statement can be set arbitrarily.

All evals are not created equal! Brian Feldman's writeup refers to the most common type: "parse this string and run it through the interpreter". This form is obviously slow and can easily (in the presence of strings from the program's input) be unsafe. Perl supports it as the "eval "string"" form. Of course, this (or its close variants) is the only way to write some programs which must read and execute some input.

A better form of eval simply says "run this code in a separate copy of the interpreter (and tell me if it worked)". In this case, the code is parsed once, but evaluated in different interpreters. This form is more akin to building some lambda expression, then executing it multiple times. Perl supports it as the "eval { block }" form. In that language, you can use it to do things like catch an abnormal exit (with die) from the code, so you can write catch and throw.

The second form is compiled only once, and cannot cause code based on program input to run. So it's much faster, has much more predictable efffects, and is a lot safer.

E"val (?), a. [L. aevum lifetime, age, eternity.]

Relating to time or duration.



© Webster 1913.

Log in or register to write something here or to contact authors.