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
_bar=$_dir_stack_size
while $_bar -gt -1 ; do
eval echo -n \"\$_dir_stack$_bar \" >&2 # use eval to dereference a variable
_bar=`expr $_bar - 1`
done
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;
SSH_AGENT_PID=94522; export SSH_AGENT_PID;
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.