FACTOID # 43: Japanese and South Korean kids are the best in the world at science and maths.
 
 Home   Encyclopedia   Statistics   Countries A-Z   Flags   Maps   Education   Forum   FAQ   About 
 
WHAT'S NEW
RELATED ARTICLES
People who viewed "Eval" also viewed:
RECENT ARTICLES
More Recent Articles »
 

SEARCH ALL

FACTS & STATISTICS    Advanced view

Search encyclopedia, statistics and forums:

 

 

(* = Graphable)

 

 


Encyclopedia > Eval

In some programming languages, eval is a function which evaluates a string as though it were an expression and returns a result; in others, it executes multiple lines of code as though they had been included instead of the line including the eval. A programming language is an artificial language that can be used to control the behavior of a machine, particularly a computer. ... In computer science, a subroutine (function, method, procedure, or subprogram) is a portion of code within a larger program, which performs a specific task and is relatively independent of the remaining code. ...


Eval-like functions are more common in interpreted languages than in compiled languages, since including one in a compiled language would require including an interpreter or compiler with the program, and more runtime information (such as variable names). Some compiled languages do have something similar to an eval function, see below. In computer programming, an interpreted language is a programming language whose programs may be executed from source form, by an interpreter. ... A compiled language is a programming language whose implementations are typically compilers (translators which generate machine code from source code), and not interpreters (step-by-step executors of source code, where no translation takes place). ...

Contents

Security risks

Special care must be taken when using eval with data from an untrusted source. For instance, assuming that the get_data() function gets data from the Internet, this Python code is insecure: Python is a high-level programming language first released by Guido van Rossum in 1991. ...

 data = get_data() foo = eval(data) 

An attacker could supply the program with the string "delete_system_files()" as data, which would result in the program calling the delete_system_files() function. To remedy this, all data which will be used with eval must be escaped, or it must be run without access to potentially harmful functions.


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 hit of parsing code.


For instance, eval is sometimes used for a simple mail merge facility, as in this PHP example: Mail merge is a computer term describing the production of multiple (and potentially large numbers of) documents from a single template form and a structured data source. ... PHP (PHP:Hypertext Preprocessor) is a reflective programming language originally designed for producing dynamic web pages. ...

 $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 simply replacing the text "$name" with the name.


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. Screenshot of a spreadsheet made with OpenOffice. ...


Perhaps the best use of eval is in bootstrapping a new language (as with Lisp), and in language tutor programs which allow users to run their own programs in a controlled environment. Bootstrapping is a term used in computer science to describe the techniques involved in writing a compiler (or assembler) in the target programming language which it is intended to compile. ... Lisp is a family of computer programming languages with a long history and a distinctive fully-parenthesized syntax. ...


Implementation

In interpreted languages, eval is almost always implemented with the same interpreter as normal code. In compiled languages, the same compiler used to compile programs may be embedded in programs using the eval function; separate interpreters are sometimes used, though this results in code duplication. In computer programming, an interpreted language is a programming language whose programs may be executed from source form, by an interpreter. ... A compiled language is a programming language whose implementations are typically compilers (translators which generate machine code from source code), and not interpreters (step-by-step executors of source code, where no translation takes place). ... Duplicate code is a computer programming term for a sequence of source code that occurs more than once in a program. ...


Programming languages

JavaScript

In JavaScript, eval is something of a hybrid between an expression evaluator and a statement executor. It returns the last expression evaluated (all statements are expressions in both Javascript & ActionScript), and allows the final semicolon to be left off. JavaScript is the name of Netscape Communications Corporations and now the Mozilla Foundations implementation of the ECMAScript standard, a scripting language based on the concept of prototype-based programming. ...


Example as an expression evaluator:

 foo = 2; alert(eval('foo + 2')); 

Example as a statement executor:

 foo = 2; eval('foo = foo + 2;alert(foo);'); 

One use of Javascript's eval is to parse JSON text, perhaps as part of an Ajax framework. JSON (JavaScript Object Notation) is a lightweight computer data interchange format. ... Ajax (also known as AJAX), shorthand for Asynchronous JavaScript and XML, is a web development technique for creating interactive web applications. ...


See also [1], [2].


For mathematical functions and constants see [3].


ActionScript

In ActionScript (Flash's programming language), eval can not be used to evaluate arbitrary expressions. According to the Flash 8 documentation, its usage is limited to expressions which represent "the name of a variable, property, object, or movie clip to retrieve. This parameter can be either a String or a direct reference to the object instance." [4] ActionScript is a scripting language based on ECMAScript, primarily used to develop software for the Adobe Flash . ...


Lisp

Lisp was the original language to make use of an eval function. In fact, definition of the eval function led to the first implementation of the language interpreter. Lisp is a family of computer programming languages with a long history and a distinctive fully-parenthesized syntax. ...


Before the eval function was defined, Lisp functions were manually compiled to assembly language statements. However, once the eval function had been manually compiled it was then used as part of a simple read-eval-print loop which formed the basis of the first Lisp interpreter. For the programming language, see Lisp (programming language). ... An assembly language is a low-level language used in the writing of computer programs. ... A read-eval-print loop (REPL) is a simple, interactive computer programming environment. ...


Later versions of the Lisp eval function have also been implemented as compilers. For the programming language, see Lisp (programming language). ...


The eval function in Lisp expects a form to be evaluated and executed as argument. The return value of the given form will be the return value of the call to eval. For the programming language, see Lisp (programming language). ...


Now let us see some Lisp code: For the programming language, see Lisp (programming language). ...

 ; A form which calls the + function with 1,2 and 3 as arguments. ; It returns 6. (+ 1 2 3) ; In lisp any a form is meant to be evaluated, therefore ; the call to + was performed. ; We can pretend Lisp to perform evaluation ; of a form prefixing it with "'", for example: (setq form1 '(+ 1 2 3)) ; Now form1 contains a form that can be used by eval, for ; example: (eval form1) ; eval evaluated (+ 1 2 3) and returned 6. 

Lisp is well known to be very flexible and so is the eval function. If for example we would like to evaluate the content of a string, we would first have to convert the string into a Lisp form using the read-from-string function and then to pass the resulting form to eval, like this: For the programming language, see Lisp (programming language). ... For the programming language, see Lisp (programming language). ...

 (eval (read-from-string "(format t "Hello World!!!~%")")) 

Perl

Perl's eval operator serves as its exception trapping mechanism. Thus a block of code can be tested and then warned against, if necessary. For example, a run-time error "$@" in say, a division operation, can write a warning, as below, for if there were no warning, $@ would be empty: Perl is a dynamic programming language created by Larry Wall and first released in 1987. ...

 # make divide-by-zero nonfatal eval { $answer = $a / $b; }; warn $@ if $@; 

PHP

In PHP, eval executes code in a string almost exactly as if it had been put in the file instead of the call to eval(). The only exception is that errors are reported as coming from a call to eval(), and return statements become the result of the function. PHP (PHP:Hypertext Preprocessor) is a reflective programming language originally designed for producing dynamic web pages. ...


Example using echo:

 <?php $foo = "Hello, world!n"; eval('echo $foo;'); ?> 

Example returning a value:

 <?php $foo = "Goodbye, world!n"; echo eval('return $foo;'); ?> 

PostScript

PostScript's exec operator takes an operand - if it is a simple literal it pushes it back on the stack. If one takes a string containing a PostScript expression however, one can convert the string to an executable which then can be executed by the interpreter, for example: PostScript (PS) is a page description language and programming language used primarily in the electronic and desktop publishing areas. ...

 ((Hello World) =) cvx exec 

converts the PostScript expression

 (Hello World) = 

which pops the string "Hello World" off the stack and displays it on the screen, to have an executable type, then is executed.


PostScript's run operator is similar in functionality but instead the interpreter interprets PostScript expressions in a file, itself.


Python

In Python, the eval function in its simplest form evaluates a single expression. Python is an interpreted, interactive programming language created by Guido van Rossum in 1990, originally as a scripting language for Amoeba OS capable of making system calls. ...


eval example (interactive shell):

 >>> x = 1 >>> eval('x + 1') 2 >>> eval('x') 1 

The eval function takes two optional arguments, global and locals, which allow the programmer to setup a restricted environment for the evaluation of the expression, avoiding the security pitfalls mentioned above.


The exec statement executes statements:


exec example (interactive shell):

 >>> x = 1 >>> y = 1 >>> exec "x += 1; y -= 1" >>> x 2 >>> y 0 

The most general form for evaluating statements/expressions is using code objects. Those can be created by invoking the compile() function and by telling it what kind of input it has to compile: an "exec" statement, an "eval" statement or a "single" statement:


compile example (interactive shell):

 >>> x = 1 >>> y = 2 >>> eval (compile ("print 'x + y = ', x + y", "compile-sample.py", "single")) x + y = 3 

ColdFusion

ColdFusion's evaluate function lets you evaluate a string expression at runtime. This article or section does not adequately cite its references or sources. ...

 <cfset x = "int(1+1)"> <cfset y = Evaluate(x)> 

It is particularly useful when you need to programatically choose the variable you want to read from.

 <cfset x = Evaluate("queryname.#columnname#[rownumber]")> 

REALbasic

In REALbasic, there is a class called RBScript which can execute REALbasic code at runtime. RBScript is very sandboxed -- only the most core language features are there, you have to allow it access to things you want it to have. You can optionally assign an object to the context property. This allows for the code in RBScript to call functions and use properties of the context object. However, it is still limited to only understanding the most basic types, so if you have a function that returns a Dictionary or MySpiffyObject, RBScript will be unable to use it. You can also communicate with your RBScript through the Print and Input events. REALbasic or RB is an object-oriented dialect of the BASIC programming language commercially marketed by the Austin, Texas based REAL Software Inc. ... RBScript is a scripting language which is similar to, and shares many features with, REALbasic. ...


Ruby

The Ruby language interpreter offers an eval function similar to Python or Perl, and also allows an scope, or binding, to be specified. Ruby is an object-oriented programming language. ... In computer science, binding refers to the creation of a simple reference to something which is larger and more complicated and used frequently. ...


Aside for specifying a function's binding, eval may also be used to evaluate an expression within a specific class definition binding or object instance binding, allowing classes to be extended with new methods specified in strings

 a = 1 eval('a + 1') # (evaluates to 2) # evaluating within a context def getBinding(a) return binding end eval('a+1',getBinding(3)) # (evaluates to 4, because 'a' in the context of getBinding is 3) 
 class Test; end Test.class_eval("def hello; return 'hello';end") # add a method 'hello' to this class Test.new.hello # evaluates to "hello" 

External links

  • ANSI and GNU Common Lisp Document: eval function
  • Python Library Reference: eval built-in function
  • Jonathan Johnson on exposing classes to RBScript

  Results from FactBites:
 
Eval - Wikipedia, the free encyclopedia (955 words)
In some programming languages, eval is a function which evaluates a string as though it were an expression and returns a result; in others, it executes multiple lines of code as though they had been included instead of the line including the eval.
Eval is also sometimes used in applications needing to evaluate math expressions, such as spreadsheets.
Perhaps the best use of eval is in bootstrapping a new language (as with Lisp), and in language tutor programs which allow users to run their own programs in a controlled environment.
  More results at FactBites »


 

COMMENTARY     


Share your thoughts, questions and commentary here
Your name
Your comments
Please enter the 5-letter protection code

Want to know more?
Search encyclopedia, statistics and forums:

 


Lesson Plans | Student Area | Student FAQ | Reviews | Press Releases |  Feeds | Contact
The Wikipedia article included on this page is licensed under the GFDL.
Images may be subject to relevant owners' copyright.
All other elements are (c) copyright NationMaster.com 2003-5. All Rights Reserved.
Usage implies agreement with terms.