Tuesday, 11 May 2010


eval() has two forms. The first takes a string, and treats it as Perl
code. It compiles and executes it, returning whatever value is
appropriate. If there is a fatal error, it sets the $@ variable.

my $string = "make the vowels capitals";
my $from = "aeiou";
my $to = "AEIOU";

eval "\$string =~ tr/$from/$to/";
# now $string is mAkE thE vOwEls cApItAls

We had to use eval() here, because tr/// doesn't interpolate variables.
If we'd just done

$string =~ tr/$from/$to/;

we'd be changing $ to $, f to t, r to o, o to o, and m to o, and the
string would be "oake the vowels capitals".

The other form is eval { CODE }. This executes a block of code in a
fail-safe environment. If there are any fatal errors, the $@ is set, and
the block is exited. A common use for this is:

print "Give me a number: ";
chomp(my $n = <STDIN>);
my $result = eval { 100 / $n };
if ($@) { print "You tried dividing by zero.\n" }

Basically, if we didn't use eval { } here, the program would die if the
user entered the number 0.

No comments:

Post a Comment

Tweets by @sriramperumalla