Perl

How can we evaluate and capture an exception in Perl?

Difficulty: unrated

Source: bregman-arie/devops-exercises by Arie Bregman

Answer

From the official eval docs:

"eval in all its forms is used to execute a little Perl program, trapping any errors encountered so they don't crash the calling program.".

e.g:

eval {
    die;
};
if ($@) {
    print "Error. Details: $@";
}

If we execute this we get the next output:

Error. Details: Died at eval.pl line 2.

The eval (try in another programming languages) is trying to execute a code. This code fails (it's a die), and then the code continues into the if condition that evaluates $@ error variable have something stored. This is like a catch in another programming languages. At this way we can handle errors.