Perl Error Handling

Sometimes your program may produce an error at the time of program execution. Therefore you must have to handle those errors to run your perl program successfully.

The if statement

The if statement in perl, is a choice when you need to check the return value from a statement in your perl program. Here is an example:

if(open(DATA, $file))
   die "Error occurred in opening the file - $!";

Here, the variable $! returns the actual error message.

The unless function

The unless function in perl, is the logical opposite to the if statement, can completely bypass the success status and only be executed, if the expression returns as not true. Here is an example:

   die "Error occurred on changing the directory - $!";

The warn function

The warn function in perl, raises a warning message, and is printed to the STDERR, but in this case, there is no further action is taken. Here is an example:

chdir('/etc') or warn "Error occurred in changing the directory..";

Perl Online Test

« Previous Tutorial Next Tutorial »

Like/Share Us on Facebook 😋