CSC/ECE 517 Fall 2012/ch1 1w28 mv
eval
Perl
The general form of Perl expects an expression or a block of code as an expression. The expr passed as an argument is parsed and executed as small Perl program. If there are no errors in the expr , which is parsed , then it is executed within the lexical content of the current Perl program.
Error Handling with eval
Eval can be used to trap the errors. During execution of the routines , the program might die due to errors and interrupts in the code. However , using eval , the code can still be running if the errors are handled inside the eval without being exited. We can evaluate the functionality of eval from the given code.
print "entern number 1 \n";
$number1 = <STDIN>;
chomp $number1;
print "enter number 2 \n";
$number2 = <STDIN>;
chomp $number2;
print "division output is ";
$x =eval {$result = $number1/$number2};
print "$x\n$@";
$sum = $number1 + $number2;
print "sum is $sum \n";
The above given code prompts the user to give 2 inputs and then performs the division and addition of the numbers. If the second number entered by the user is 0 , then in that case code exits showing the error message and it does not calculate the addition. However , we can handle this exception using eval. Eval handles the exception, shows the appropriate error message and then return the controller back to the program without exiting it. Hence , even if the second input is 0 , the addition is performed by the eval method.
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:
session['authenticated'] = False
data = get_data()
foo = eval(data)
An attacker could supply the program with the string "session.update(authenticated=True)"
as data, which would update the session
dictionary to set an authenticated key to be True. 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.