Perl, as a scripting language, can generate and execute code in real time. This feature can defer the compilation of code to the runtime, so it is called "Dynamic Code". In addition, Perl also provides exception handling mechanisms like Java and C + +. This article will explore the functions of implementing dynamic Code and exception handling mechanism in Perl: eval. If there is a lack of error, welcome to discuss and criticize.
The Eval function can be considered a Perl virtual machine, and its parameters are a piece of Perl code. Use ' perldoc–f eval ' to get the Eval function help, which describes two ways to use it:
EXPR is an expression, for example:
Eval "Print $a";
Eval ' Print $a '. ', $b ';
Eval 1 + 3;
Eval ' print '. ' $a + $b, ' \ n ';
eval $command; # $command = ' print ' Hello Perl '
Eval $ARGV [0];
At execution time, the Perl interpreter parses the value of an expression first, and then inserts the expression value as a Perl statement into the current execution context. Therefore, the newly generated statement has the same context as the Eval statement itself. In this way, each time an eval statement is executed, the expression is parsed. Therefore, if Eval EXPR appears in a loop, the expression may be parsed multiple times. This way of Eval enables the Perl script to generate and execute code in real time, thus implementing "Dynamic code".
A block is a piece of code, such as:
eval {print $a};
eval {$a = 1, $b = 2, $c = $a + $b};
Unlike the first method, the block is parsed only once, and the entire insert is inserted into the execution context of the current eval function. Because of the advantages of parsing performance and the ability to check code syntax at compile-time, this approach is often used as Perl to provide an exception-capture mechanism for a piece of code, although the previous approach is also possible.
By the name of the help, the eval parameter program is "applet" (Mini-program). In both ways, the return value of the Eval function is the value of the last statement in the applet, which is the same as the subroutine if it is encountered.
SCRIPT1:
#!/usr/bin/perl-w
Push (@program, ' $i = 1; ');
Push (@program, ' $i = 3; $j = 2; $k = $i + $j ');
Push (@program, ' $i = 3; return; $k = $i + $j ');
foreach $exp (@program)
{
$rtn =eval ($EXP);
Print $rtn, "\ n";
}
Output:
If there is a syntax error in the applet, and the Run-time error encounters the die statement, Eval returns UNDEF. The error code is saved in the $@.
SCRIPT2:
#!/usr/bin/perl-w
Push (@program, ' $i = 3; die "error message"; $k = $i + $j ');
foreach $exp (@program)
{
$rtn =eval ($EXP);
if (! defined ($RTN))
{
Print "Exception:", $@, "\ n";
}
Else
{
Print $rtn, "\ n";
}
} ;
Output:
Exception:error (eval 1) Line 1.
SCRIPT3:
#!/usr/bin/perl-w
# a Run-time error
Eval ' $answer = '; # sets $@
Warn $@ if$@;
Output:
Syntax error at (eval 1) Line 2, at EOF