FreeKB - Perl eval function
Perl - eval function

The eval function can be used to evaluate whether or not Perl markup is going to produce some error. Let's take the following example.

eval { print "Hello World \n"; };

 

Invoking this Perl script should simply return Hello World, meaning that the evaulation was successful or true.

Hello World

 

The result of the eval function will be stored in the $@ variable. Dumper can be used to display the content of the $@ variable.

use Data::Dumper;
print Dumper $@;

 

In this example, the following would be returned, meaning that the eval function did not append anything to the $@ variable.

$VAR1 = '';

 

Let's consider the alternative, where the eval function captures a problem. In this example, a bogus subroutine is evaluated.

eval { bogus(); };

 

Use Dumper to print the content of the $@ variable.

use Data::Dumper;
print Dumper $@;

 

And something like this will be returned.

$VAR1 = 'Undefined subroutine &main::bogus called at testing.pl line 13.
';

 

Instead of using Dumper, an if statement can be used to do something when the $@ variable is not empty (contains a value).

eval { bogus(); };
chomp $@;
if ($@) {
  print "eval found the following issue: $@ \n";
}

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter 0cea0 in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |