Error Handling in Perl - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Error Handling in Perl

Share This

In every programming language, errors are to be handled properly to avoid unexpected circumstances or termination.

There can be many reason, where an error can occur at run-time. Some of the techniques are discussed here with some example.

If a file is being opened which does not exist in specified location, the program will halt. Hence, instead of terminating the program, a meaningful message can be shown to the user. Moreover, necessary steps can be taken as per the requirements.

if(open(DATA, $file)) { # statements } else { die "Error: Unable to open the file $!"; }

or

open(DATA, $file) || die "Error: Unable to open the file $!";

Here, variable $! returns the actual error message.

warn Function

Using warn function, a warning message can be printed to STDERR, without taking any action. The warning function can be used as follow.

warn "Unable to change directory";

die Function

The die function is used to print message as well as to call exit. Example is shown below.

die "Unable to change directory";



Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.