Perl Die: How to Gracefully Catch Errors and Exit

perl diePerl is a general-purpose programming language that can be used for a very wide variety of programming tasks. The language was initially made to make report processing in UNIX-based systems easier. Today, however, the language can be used for almost everything. It can be used to make web applications, to run web servers, for networking, system administration and even graphics programming. Perl is very popular with some big companies and governments, because it is powerful and because it is open source. It is possible to modify Perl modules and the language itself to match it your needs. If you’re just getting started with Perl, you will find that Perl is an easy language to learn. It has a simple syntax that is reminiscent of spoken English. It has an automatic garbage collection feature- you can give your entire attention to programming and leave the memory management to Perl. Perl, like most other modern programming languages, is object oriented. It follows a certain style of programming. Once you get used to the style, writing Perl scripts will be a breeze. Perl is developed by a community of programmers. It’s easy to find learning resources for the language as well as support for developing applications. We offer a Perl course that you can get take to get acquainted with Perl basics. We take you through Perl in a step-wise way, and you’ll find yourself writing advanced Perl scripts in no time.

The Die Function

You will find that Perl is a very forgiving language in general, which makes writing Perl scripts an enjoyable experience. Perl will, for example, tell you if something went wrong with your program if you use certain functions. One of those functions is the die function. The die function will terminate your script, give an exception and display a message to you if it is invoked. Sometimes some scripts don’t work properly or can’t execute at all. For example, if you ask Perl to find a file, but the file doesn’t exist, your script will have to be terminated. In this case, you can use the die function to terminate the script and display a message saying “The File you requested does not exist”. The die function is similar to the warn function. The die function is used for extreme case scenarios, unlike the warn function. The warn function will display a message telling you that something is wrong with your program. It is usually possible to correct this mistake. If you entered a non-permissible value, for example, you may receive a warning. The script will continue executing after displaying the warning. In case of the die function, however, the script is terminated immediately. The die function, when invoked, will print a string message to STDERR (the standard error output channel). It will then force the script to exit. The syntax of the die function is as follows:

die LIST

Here, the LIST will have elements that will be printed to STDERR. Then the script will exit and return value received will be $! (errno). Let’s take a few simple examples and use the die function to throw up errors so you’ll understand it better.

Example 1: The Die function with the || Operator

#! /usr/bin/perl -w
chdir (‘/user/favorites’) || die ();

Output:

Died at test.pl line 2

This example is pretty self-explanatory. We used the chdir function on the directory named “favorites”. However, the directory named “favorites” didn’t exist. So, Perl skipped to the die function instead and we received an error message. Notice that we used the || operator in this case. Note that C does not have this kind of function. In C you would have to check the return value of the function, and use an if statement or similar conditional to catch the error. Learn more about C programming in this course.

Example 2: The Die function with the Unless statement

It’s not necessary to use the || operator in all cases. Take a look at this example:

use strict;
use warnings;
my $filename = "mynote.txt";
unless(open FILEHAN, $filename) {
die "Cannot open $filename";
}
while(my $lines = <FILEHAN>) {
print $lines;
}
close FILE;

Output (Because the file does NOT open successfully):

Cannot open mynote.txt at d:\src\test.pl line 6.

Here, we are attempting to open the file “mynote.txt” with the help of the “open” function. Because the file “mynote.txt” doesn’t exist, the die function we wrote was invoked and we got the output: Cannot open mynote.txt at d:\src\test.pl line 6. We used the unless function in this case. If you’re unfamiliar with the unless function, or the open function, you can take a look at our other Perl tutorials to get acquainted with them. Alternatively, you can take this Perl course for a more hands on learning.

Example 3: The Die function without The Location Information

The official die documentation at the Perl website says that if you don’t add a newline character at the end of the LIST elements, the script line number as well as the path of the script will be supplied. If you take a look at the output of the example above, you will see what we’re talking about:

Cannot open mynote.txt at d:\src\test.pl line 6.

While the location information and the line number are sometimes useful, as you know where your program was faulty, it can be an eyesore. You also might want to hide this info from a user, especially if you are making an application. To do that, you just need to add a newline character “\n” at the end of the LIST elements. This will just display the string on screen:

#! /usr/bin/perl -w
chdir (‘/user/favorites’) || die “This directory does not exist!\n”;

Output:

This directory does not exist!

All we did here was add the newline character at the end of the LIST elements. You will now receive the message “This directory does not exist!\” without the location info. You will encounter the die function in many places in Perl, so you should have a good grip on it. You may also want to check out how this is done in other scripting languages. This course gives a good overview of Bash Scripting and Python.