What is eval in perl?

Questions by ms_2007

Showing Answers 1 - 3 of 3 Answers

aiyshwarya

  • Nov 19th, 2007
 


 "eval" and "if ($@)" is the equivalent of a try/catch in the C
programming world. My question is how to basically throw an error in
one perl script that can be caught by another

Consider the following example:

eval {

die("REASON"); # the script dies for some reason

};

if ($@) # $@ contains the exception that was thrown
{
print $@;
}


thanks
Aiyshwarya

The eval function provides a very simple way of checking certain events without affecting the overall execution of your script. In essence, the eval function just initiates a new instance of the Perl interpreter in order to evaluate a particular string or block. It’s used in all sorts of places within Perl—including in the debugger where it allows you to execute those arbitrary statements—but it can also be employed as a debugging tool.

Because eval evaluates a Perl statement or block within its own interpreter, we can use it in situations that might otherwise cause the Perl interpreter to fail. This process works because an embedded eval block reports any errors raised by a call to die through the $@ variable. In fact, any exit is reported through eval to the $@ special variable. We can demonstrate this with a simple eval block used to test the existence of a particular module:

eval
{
require Net::FTP;
}
print "Error: Module failed to load ($@)" if $@;


This outputs the following:


$ perl eval.pl
Failed to load Net::FTP: Can't locate Net/LICK.pm in @INC (@INC contains:
/usr/local/lib/perl5/5.6.0/i686-linux /usr/local/lib/perl5/5.6.0
/usr/local/lib/perl5/site_perl/5.6.0/i686-linux
/usr/local/lib/perl5/site_perl/5.6.0 /usr/local/lib/perl5/site_perl .) at
eval.pl line 1.

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions