Home » Perl Programming, Programming Techniques » Error Handling in Perl & EVAL Block

0

This article covers two things.

1) Error handling in Perl using EVAL Block
2) Using the EVAL Block feature to check whether a directory exists on a remote FTP location.

The first time ever I had to work in Perl was last month when I was asked to look in to an issue with sending a file to a remote FTP from the server. Basically, the perl script fetches a file from the server and put it into a remote FTP location. Before copying the file to FTP, the script changes the current working directory of the remote destination using the $ftp-cwd command. We are using Net:FTP library to work with FTP. If the folder doesn’t exist on the FTP, perl needs to create the folder and FTP the file there. We faced basically two problems. 1) Using Net:FTP, there is no way to know that a folder exists or not. 2) The old versions of Perl doesn’t feature a dedicated error handling mechanism.

Since we don’t have a way to know whether a folder exists on the FTP or not, the only other way is to try changing the directory and then catch the error if the directory didn’t exist.  We can use “or die” with the $ftp->cwd command to terminate the script if the director doesn’t exist. But that doesn’t solve our problem. The script should not be terminated, and it should create the directory and upload the file.  All I wanted was something like a try{} catch(){} which is available in most of the programming languages.

Finally we found an alternative way of implementing an error catching mechanism in perl. That is using the EVAL block.

Here is a sample use of EVAL Blcok.

# Sample code to demonstrate EVAL usage
eval {
$ftp->cwd($ftpdir) or die "Directory doesn't exist. ".$ftp->message;  //the script doesn't get terminated here because its in an eval block.
}
if ($@) {
$ftp->mkdir($ftpdir);
$ftp->cwd($ftpdir);
}
#Continue your script

If the CWD command caused an error “$@” will hold the string value passed to the die command. If “$@” is null, we know that there is no error and just don’t do anything to handle the error. What I found out was we really need the die command inside the block and without the die command “$@” returned null though there was an error.

Thanks,
Anees

Leave a Reply

Page optimized by WP Minify WordPress Plugin