Perl Eval -- Using Eval to Run Code and Trap Errors in Perl

You can use eval() in Perl to "evaluate" code; that is, to run code contained in a string, or to run code that may throw errors.

A word of caution: use eval() sparingly. Improper or excessive use of eval() can lead to code that's hard to understand and full of security loopholes. Usually when you think you need eval(), you don't.

Really there are two separate ways of using eval(), although they are conceptually similar; one which catches errors at compile-time, and one which doesn't. The difference lies in whether you use eval() to run code contained in a string, or use it to run code contained in a code block.

The following program will help make things clear.

use strict;
use warnings;

# This parses OK.
eval "dsfa";

# This doesn't.
eval { dsfa };

Using Eval To Run Perl Code Contained In Strings

Let's take a look at how we can use eval() to execute Perl code contained in strings. We'll try to eval a program with a deliberate error in it, to demonstrate error checking in eval().

eval() returns undef if there's an error in the code you try to execute. You can find the error message in $@.

use strict;
use warnings;

# Create a string containing Perl code.
my $code = q|
    my $text = "Hello";
    print "$text\n";
    # Deliberately introduce an error.

my $result = eval($code);

# If there's a problem eval'ing the
# code, eval() returns undef and
# the error is found in $@.
unless($result) {
    print $@;

Bareword "jljlk" not allowed while "strict subs" in use at (eval 1) line 7.

If we remove the line causing the error, we get this, as expected:


Using Eval To Trap Errors

We can also use eval() to trap errors in Perl code, a bit like try-catch in other languages. Instead of supplying eval() with a string to execute, we supply it with a code block.

The eval block will fail at compile-time if you've got syntax errors in your script or you try to use non-existent modules or whatever. However, if a runtime error occurs in the eval block (even one that would previously have been fatal), the script carries on running.

The following program survives compile-time since there are no syntax errors in it, but a division by zero leaves the script unscathed instead of killing it.

use strict;
use warnings;

my $result = eval { 
    my $wrong = 5/0;
    print "Value: $wrong";

print "Script is still running!\n";

unless($result) {
    print $@;

Script is still running!
Illegal division by zero at line 6.