$ Total = 0;
$ COUNT = 0;
Eval {$ average = $ total/$ count; print "xxx/N ";};
If ($ @)
{
Print "wrong/N ";
}
Else
{
Print "right/N ";
}
The semicolon at the end of the eval block is required, because Eval is actually a function, unlike the if or while control structure. HoweverCodeBlocks are real blocks, so they can include lexical variables ("my" modified variables) and other arbitrary statements. Because it is a function, Eval has a return value like a subroutine (the result of the final expression, or the result returned by the Return Statement ). Of course, if a code block fails, no value is returned. If an undefined value is returned in the scalar environment, an empty list is returned in the list environment. Therefore, the safer way to calculate the average is as follows:
My $ average = eval {$ total/$ count };
Perl also supports eval code block nesting. As long as the code is executed, the eval block can always capture errors, so it can capture errors in nested subroutines. Even so, Eval cannot catch very serious errors, and Perl will interrupt the execution itself when these errors occur. These errors include uncaptured signals, memory overflow, or other disasters. Eval cannot catch syntax errors because Perl checks syntax errors when compiling eval and other code, rather than at runtime. Also, Eval cannot capture warnings. (Perl does provide a method to capture warning information. You can check the variable $ sig {__ warn __}).