- 论坛徽章:
- 1
|
回复 7# shilin320 - 2.2. Trapping Errors with
- But just because something has gone wrong with one part of our code, that doesn't mean that we want everything to crash. Perl uses the eval operator as its error-trapping mechanism.
- eval { $average = $total / $count }
- 2.3. Dynamic Code with eval
-
- There's also a second form of eval, whose parameter is a string expression instead of a block. It compiles and executes code from a string at runtime.
- erl executes that code in the lexical context of the code around it, meaning that it's virtually as if we had typed that code right there. The result of the eval is the last evaluated expression, so we really don't need the entire statement inside the eval.
- #!/usr/bin/perl
- foreach my $operator ( qw(+ - * /) ) {
- my $result = eval "2 $operator 2";
- print "2 $operator 2 is $result\n";
- }
复制代码 书上这么说的 |
|