Bootstrap FreeKB - Perl (Scripting) - eval function
Perl (Scripting) - eval function

Updated:   |  Perl (Scripting) articles

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";
}

 

Often, the eval function is use along with the assert_valid_json function to determine if JSON is properly formatted. Refer to the JSON::Parse module for more details on parsing JSON.

eval {
  assert_valid_json ($raw_json);
};

if ($@) {
  print "ERROR! Invalid JSON: $@ \n";
  exit 1;
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


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