Wednesday, December 14, 2011

PERL DIE( ) AND EVAL( ) FUNCTIONS

PERL DIE() AND EVAL() FUNCTIONS


 

REVISED: Sunday, March 3, 2013




In this tutorial, you will learn how to use the Perl die( ) function and the Perl  eval( )  function.

I.  PERL DIE( ) FUNCTION

The die( ) function is used to quit your script and display an error message.

The die( ) function syntax is as follows:

die(LIST);

The elements of LIST are printed to STDERR, and then the script will exit, setting the script's return value to $! (errno).

die( ) terminates the Perl program if there is an error and prints out an error message.

The $! is a system generated error message number telling you why the system did not do what you requested.

To use the die( ) function, place it on the right side of the || operator.

chdir('/user/printer') || die( "printerYE2011.pl died changing directories.");

If the /user/printer directory does not exist the following error message will display:

printerYE2011.pl died changing directories.

Always include an error message telling the user what happened.  You also want the error messages to be informative and to look professional.

For example, you could use the following code to display the error text associated with errno:

chdir('/user/printer') || die("$!");

The above code could display the appropriate system error message.

II.  PERL EVAL( ) FUNCTION

Experiment and look for error messages that communicate best to your users.  Especially if you are the user.  If you only run a program on rare occasions, error messages will help you remember how to make your program work the way you designed it to work.  For example:

$code = "chdir('/user/printer')";

eval($code) || die("PROBLEM WITH LINE: $code\n$!, stopped.");

The above code could display the following error message:

PROBLEM WITH LINE: chdir('/user/printer')
No such file or directory, stopped.

The eval( ) function compiles and executes its arguments at runtime.

First, the Perl code in $code is executed.  If an error arises, the Perl code in $code is displayed as text by the die( ) function.

In this tutorial, you have learned how to use the Perl die( ) function and the Perl eval( ) function.

Elcric Otto Circle




-->   -->   -->







How to Link to My Home Page

It will appear on your website as:
"Link to ELCRIC OTTO CIRCLE's Home Page"






No comments:

Post a Comment