Two sides of EVAL !!!

Do you know EVAL has two sides ? Even I did not know till I read EVAL line by line !!!

EVAL function works in two somewhat distinct ways depending on the type of its argument.

USE-1 (The String Form: Expression Evaluation)

If given a string, eval treats the string as a little program and compiles and execute it which is called dynamic expression evaluation. The contents of the string may or may not be known at compile time.


#!/usr/bin/perl -w
use strict;
use warnings;

my $a = 10; my $b = 20;my $c =0;
my $str = ‘$c = $a + $b’;
eval $str;                                                   # execute string as a little program
print $c;                                                    # It prints 30

Danger: Things get interesting if $str comes from elsewhere, we will see in next blog and also preventing measures to create secure PERL and CGI scripts

USE-2  (The Block Form: Exception Handling)

In this form, eval is followed by a block of code, not a scalar containing a string. It is used for handling run-time errors, or exceptions . Errors can be internal built-in ones (out-of-memory, divide-by-zero) or user-defined ones produced by die .

The following example shows how you can use the block form eval to trap a run-time divide-by-zero error:

eval {
$a = 10; $b = 0;
$c = $a / $b;     # Causes a run-time error,
# which is trapped by eval
print $@;   # Prints  “Illegal division by 0 at line 3

When the script is compiled, Perl syntax-checks the block of code and generates code. If it encounters a run-time error, Perl skips the rest of the eval block and sets $@ to the corresponding error text.

To signal your own errors, you use die . Perl knows whether a piece of code is currently executing inside an eval , and so, when die is called, Perl simply gives the error string – die ‘s argument – to the global $@ , and jumps to the statement following the eval block.

Java/C++ programmers would of course recognize the parallel to the throw, try , and catch statements, where try corresponds to the eval block, catch to the checking of $@ , and throw to die . (Essentially, the caller says to the run-time environment, “Here, try this code, and catch whatever errors are thrown by the callee.”)


[Curtsey: Advanced Perl Programming By Sriram Srinivasan]

Read carefully to find new things “God is in the small details”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s