File input/output

The die function

Sometimes the open function fails. For example, opening an input file might fail because the file does not exist, and opening an output file might fail because the user does not have write permission.

A perl program will nevertheless use the filehandle, and will not warn you that all input and output activities are actually meaningless.

Therefore, it is recommended to explicitly check the result of the open command, and if it fails to print an error message and exit the program.

This is easily done using the die function.

Example:


my $k = open (IN_FILE, "filename");

unless ($k) {
  die ("cannot open file filename: $!");
}

# in case file "filename" cannot be opened,
# the argument of die will be printed on
# the screen and the program will exit.

# $! is a special variable that contains the respective
# error message sent by the operating system..

A short hand:

open (FILEHANDLE, "filename") || die "cannot open file filename: $!";
or (same thing):
open (FILEHANDLE, "filename") or die "cannot open file filename: $!";


Table of Contents.
Previous | Next.