nntp said:
if (something) { do it;}
vs
eval {do it;} if (something);
Are there any difference? Is eval simply a error catcher?
More or less
Read on ...
I don't understand the part in perldoc:
In the second form, the code within the BLOCK is parsed only
once--at the same time the code surrounding the eval itself was
parsed--and executed within the context of the current Perl
program. This form is typically used to trap exceptions more
efficiently than the first (see below), while also providing the
benefit of checking the code within BLOCK at compile time.
eval "\$$x++"; # CASE 5
"Does this reference exist (\$$x++)?" is what's going on in this case.
If it does and we can increment by 1, then the 'eval' succeeds and we
move on. If it doesn't or we can't increment by 1, then we can see what
happened in the special variable '$@' and deal with this run-time
occurrence.
The same applies here, but if we get a run time error, we 'die'.
What do those two cases do? add 1 to x then...? Why do we need eval in case
5?
I'm going to give, what I hope will be, a practical application of
'eval' for review.
Suppose you have an application that accepts user input. The
application doesn't rely upon the user input, but does need to do
something if it does get user input. The application should not die if
the user has elected to give invalid input. So, how do we do this? We
can use 'eval' to prevent a fatal run-time error.
Example:
=begin
#!/usr/bin/perl
use warnings;
use strict;
my $result = 0;
my $user_input = 0;
eval {
$result = 1 / $user_input;
};
if($@) {
print <<EOP;
User has entered zero (0) for a value.
We would 'die' here, but instead we will let you know and move on.
EOP
}
print "Program has finished with a result of $result\n";
=cut
As you can see, we "evaluate" the user input. If we get a run-time
error as a result of the user input, we print a message and move on.
But what happens if we don't use 'eval'? Well, let's comment out the
lines related to our use of 'eval' and see.
=begin
#!/usr/bin/perl
use warnings;
use strict;
my $result = 0;
my $user_input = 0;
#eval {
$result = 1 / $user_input;
#};
#if($@) {
# print <<EOP;
#User has entered zero (0) for a value.
#We would 'die' here, but instead we will let you know and move on.
#EOP
#}
print "Program has finished with a result of $result\n";
=cut
We get "Illegal division by zero at test_eval.pl line 10." and the
application ends. Remember the requirements of out example application
- we don't *have* to have user input to do what we need to do.
So, for the first part of your post, this is the reason for 'eval'. If
we try to evaluate a variable, expression, etc. that *may* give use a
run-time error, we can use 'eval' to evaluate the results and then do
something more appropriate than just 'die' This is similar to Java's
try-catch-finally exception catching mechanism (if this helps
).
HTH
Jim