The Eval Command
#############################  Eval Demo  ################################
#!/usr/bin/perl -w

############################  String Eval  ###############################
print "Enter your program and we'll see if it works!\n\n";


$str .= $_ while <STDIN>;  #  CTRL-D for EOF on Unix. CTRL-Z on Windows.

eval $str;

if ($@)
{
     print "Code had bugs!  Errors: $@\n";
}
else
{
     print "Code was correct Perl!\n";
}


#############################  Block Eval  ################################


print "Enter two integers: ";
($a, $b) = split /\s+/, <STDIN>;

eval
{
     $c = $a/$b;   #  If $b is zero, fatal error terminates eval block and
};                 #  sets $@ variable.


print "Divide by zero!!\n\n" if $@;


#########  Block Eval Example:  Giving a User a Second Chance  #########

while(1)   #  Adapted from "Advanced Perl Programming" (Srinivasan)
{
     print "Enter filename: ";
     chomp($file = <STDIN>);
     eval{
         open(F, "$file") or die "Could not open: $file\n";
     };
     last unless $@;  #  Occurrence of die or fatal error sets $@
     print "Try another name!\n";
}



###########################  Output Below  ############################

$ eval.pl
Name "main::c" used only once: possible typo at eval.pl line 29.
Name "main::F" used only once: possible typo at eval.pl line 43.
Enter your program and we'll see if it works!

$a = 10;
$b = 20;
print $a + $b, "\n";
30
Code was correct Perl!

Enter two integers: 10 0
Divide by zero!!    #  Eval worked!

Enter filename: foo.bar
Try another name!   #  Eval worked!
Enter filename: x

$ eval.pl
Name "main::c" used only once: possible typo at eval.pl line 29.
Name "main::F" used only once: possible typo at eval.pl line 43.
Enter your program and we'll see if it works!

$a = 10;
b = 20;
Unquoted string "b" may clash with future reserved word at (eval 1) line 2, <STDIN> chunk 2.
Code had bugs!  Errors: Can't modify constant item in scalar assignment at (eval 1) line 2, at EOF

Enter two integers: 10 10  #  Didn't set off eval errors here.
Enter filename: x
##############################  Eval Usages  ##############################

1.  Transmitting code for a server to execute.  Useful but dangerous!
    Can the code be trusted??

2.  Trapping SIG{ALRM}.

3.  Computer-assisted instruction (needs exploration!).

4.  Elegant control of arithmetic overflow/underflow or other user-
    generated events when you want a "die" message.

5.  Program-generating programs.