1. Perl
  2. builtin functions
  3. here

eval - catch exceptions, dynamically execute strings

You can use the eval function to catch exceptions in the case of block syntax. For string syntax, you can execute strings dynamically.

# eval block-catch exceptions
eval {...};

# eval string-dynamically execute string
eval $string;

Note that the block syntax and the string syntax have completely different functions. Let's take a closer look at each syntax.

Exception catching - eval block

The one called the eval block is the syntax for catching exceptions in Perl.

# eval block-catch exceptions
eval {...};

This plays the same role as the catch syntax for exception handling in Java and elsewhere. If an exception occurs inside the eval block, you can catch the exception and prevent the program from terminating.

The content of the exception is assigned to predefined variable "$@", so let's check this. It is recommended to save $@in variable as it may be overwritten by other processing.

if (my $error = $@) {
  print "$error\n";

See the following articles for a detailed explanation of Perl's exception handling.

Dynamic execution of strings - eval string

The one called the eval string is a syntax that dynamically executes a string. If you pass a string to eval, that string will be executed as a Perl executable statement. Any errors that occur at runtime are stored in $@.

# eval string-dynamically execute string
eval $string;

As an example, you can define subroutine at runtime. The following example defines a subroutine called foo that returns 5 with an eval string and typeglob at runtime. "No string'refs'" temporarily allows symbolic reference.

  no strict'refs';
  * {"foo"} = eval "sub {return 5}";

This is the CPAN module, which is used by modules that create accessors.

Dangers of eval strings

However, in normal programming it is recommended not to use the eval string.

eval is not desirable from a security point of view as it will execute the passed string as is. If you are creating an application for business, you rarely use the eval string.

If your goal is to create a CPAN module, the eval string is a must-know.

Related Informatrion